Node highlighting.
[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.7.1.  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.7.1"
654 #define SQLITE_VERSION_NUMBER 3007007
655 #define SQLITE_SOURCE_ID      "2011-06-28 17:39:05 af0d91adf497f5f36ec3813f04235a6e195a605f"
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 ** 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 ** [sqlite3_vtab_on_conflict()] [SQLITE_ROLLBACK | result codes].
923 */
924 #define SQLITE_OK           0   /* Successful result */
925 /* beginning-of-error-codes */
926 #define SQLITE_ERROR        1   /* SQL error or missing database */
927 #define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
928 #define SQLITE_PERM         3   /* Access permission denied */
929 #define SQLITE_ABORT        4   /* Callback routine requested an abort */
930 #define SQLITE_BUSY         5   /* The database file is locked */
931 #define SQLITE_LOCKED       6   /* A table in the database is locked */
932 #define SQLITE_NOMEM        7   /* A malloc() failed */
933 #define SQLITE_READONLY     8   /* Attempt to write a readonly database */
934 #define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
935 #define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
936 #define SQLITE_CORRUPT     11   /* The database disk image is malformed */
937 #define SQLITE_NOTFOUND    12   /* Unknown opcode in sqlite3_file_control() */
938 #define SQLITE_FULL        13   /* Insertion failed because database is full */
939 #define SQLITE_CANTOPEN    14   /* Unable to open the database file */
940 #define SQLITE_PROTOCOL    15   /* Database lock protocol error */
941 #define SQLITE_EMPTY       16   /* Database is empty */
942 #define SQLITE_SCHEMA      17   /* The database schema changed */
943 #define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
944 #define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
945 #define SQLITE_MISMATCH    20   /* Data type mismatch */
946 #define SQLITE_MISUSE      21   /* Library used incorrectly */
947 #define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
948 #define SQLITE_AUTH        23   /* Authorization denied */
949 #define SQLITE_FORMAT      24   /* Auxiliary database format error */
950 #define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
951 #define SQLITE_NOTADB      26   /* File opened that is not a database file */
952 #define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
953 #define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
954 /* end-of-error-codes */
955
956 /*
957 ** CAPI3REF: Extended Result Codes
958 ** KEYWORDS: {extended error code} {extended error codes}
959 ** KEYWORDS: {extended result code} {extended result codes}
960 **
961 ** In its default configuration, SQLite API routines return one of 26 integer
962 ** [SQLITE_OK | result codes].  However, experience has shown that many of
963 ** these result codes are too coarse-grained.  They do not provide as
964 ** much information about problems as programmers might like.  In an effort to
965 ** address this, newer versions of SQLite (version 3.3.8 and later) include
966 ** support for additional result codes that provide more detailed information
967 ** about errors. The extended result codes are enabled or disabled
968 ** on a per database connection basis using the
969 ** [sqlite3_extended_result_codes()] API.
970 **
971 ** Some of the available extended result codes are listed here.
972 ** One may expect the number of extended result codes will be expand
973 ** over time.  Software that uses extended result codes should expect
974 ** to see new result codes in future releases of SQLite.
975 **
976 ** The SQLITE_OK result code will never be extended.  It will always
977 ** be exactly zero.
978 */
979 #define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
980 #define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
981 #define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
982 #define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
983 #define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
984 #define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
985 #define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
986 #define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
987 #define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
988 #define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
989 #define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
990 #define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
991 #define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
992 #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
993 #define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
994 #define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
995 #define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
996 #define SQLITE_IOERR_SHMOPEN           (SQLITE_IOERR | (18<<8))
997 #define SQLITE_IOERR_SHMSIZE           (SQLITE_IOERR | (19<<8))
998 #define SQLITE_IOERR_SHMLOCK           (SQLITE_IOERR | (20<<8))
999 #define SQLITE_IOERR_SHMMAP            (SQLITE_IOERR | (21<<8))
1000 #define SQLITE_IOERR_SEEK              (SQLITE_IOERR | (22<<8))
1001 #define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))
1002 #define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))
1003 #define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))
1004 #define SQLITE_CORRUPT_VTAB            (SQLITE_CORRUPT | (1<<8))
1005 #define SQLITE_READONLY_RECOVERY       (SQLITE_READONLY | (1<<8))
1006 #define SQLITE_READONLY_CANTLOCK       (SQLITE_READONLY | (2<<8))
1007
1008 /*
1009 ** CAPI3REF: Flags For File Open Operations
1010 **
1011 ** These bit values are intended for use in the
1012 ** 3rd parameter to the [sqlite3_open_v2()] interface and
1013 ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
1014 */
1015 #define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
1016 #define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
1017 #define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */
1018 #define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
1019 #define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
1020 #define SQLITE_OPEN_AUTOPROXY        0x00000020  /* VFS only */
1021 #define SQLITE_OPEN_URI              0x00000040  /* Ok for sqlite3_open_v2() */
1022 #define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */
1023 #define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */
1024 #define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */
1025 #define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
1026 #define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
1027 #define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
1028 #define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
1029 #define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
1030 #define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
1031 #define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
1032 #define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
1033 #define SQLITE_OPEN_WAL              0x00080000  /* VFS only */
1034
1035 /* Reserved:                         0x00F00000 */
1036
1037 /*
1038 ** CAPI3REF: Device Characteristics
1039 **
1040 ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
1041 ** object returns an integer which is a vector of the these
1042 ** bit values expressing I/O characteristics of the mass storage
1043 ** device that holds the file that the [sqlite3_io_methods]
1044 ** refers to.
1045 **
1046 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1047 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1048 ** mean that writes of blocks that are nnn bytes in size and
1049 ** are aligned to an address which is an integer multiple of
1050 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1051 ** that when data is appended to a file, the data is appended
1052 ** first then the size of the file is extended, never the other
1053 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1054 ** information is written to disk in the same order as calls
1055 ** to xWrite().
1056 */
1057 #define SQLITE_IOCAP_ATOMIC                 0x00000001
1058 #define SQLITE_IOCAP_ATOMIC512              0x00000002
1059 #define SQLITE_IOCAP_ATOMIC1K               0x00000004
1060 #define SQLITE_IOCAP_ATOMIC2K               0x00000008
1061 #define SQLITE_IOCAP_ATOMIC4K               0x00000010
1062 #define SQLITE_IOCAP_ATOMIC8K               0x00000020
1063 #define SQLITE_IOCAP_ATOMIC16K              0x00000040
1064 #define SQLITE_IOCAP_ATOMIC32K              0x00000080
1065 #define SQLITE_IOCAP_ATOMIC64K              0x00000100
1066 #define SQLITE_IOCAP_SAFE_APPEND            0x00000200
1067 #define SQLITE_IOCAP_SEQUENTIAL             0x00000400
1068 #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN  0x00000800
1069
1070 /*
1071 ** CAPI3REF: File Locking Levels
1072 **
1073 ** SQLite uses one of these integer values as the second
1074 ** argument to calls it makes to the xLock() and xUnlock() methods
1075 ** of an [sqlite3_io_methods] object.
1076 */
1077 #define SQLITE_LOCK_NONE          0
1078 #define SQLITE_LOCK_SHARED        1
1079 #define SQLITE_LOCK_RESERVED      2
1080 #define SQLITE_LOCK_PENDING       3
1081 #define SQLITE_LOCK_EXCLUSIVE     4
1082
1083 /*
1084 ** CAPI3REF: Synchronization Type Flags
1085 **
1086 ** When SQLite invokes the xSync() method of an
1087 ** [sqlite3_io_methods] object it uses a combination of
1088 ** these integer values as the second argument.
1089 **
1090 ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
1091 ** sync operation only needs to flush data to mass storage.  Inode
1092 ** information need not be flushed. If the lower four bits of the flag
1093 ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
1094 ** If the lower four bits equal SQLITE_SYNC_FULL, that means
1095 ** to use Mac OS X style fullsync instead of fsync().
1096 **
1097 ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
1098 ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
1099 ** settings.  The [synchronous pragma] determines when calls to the
1100 ** xSync VFS method occur and applies uniformly across all platforms.
1101 ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
1102 ** energetic or rigorous or forceful the sync operations are and
1103 ** only make a difference on Mac OSX for the default SQLite code.
1104 ** (Third-party VFS implementations might also make the distinction
1105 ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
1106 ** operating systems natively supported by SQLite, only Mac OSX
1107 ** cares about the difference.)
1108 */
1109 #define SQLITE_SYNC_NORMAL        0x00002
1110 #define SQLITE_SYNC_FULL          0x00003
1111 #define SQLITE_SYNC_DATAONLY      0x00010
1112
1113 /*
1114 ** CAPI3REF: OS Interface Open File Handle
1115 **
1116 ** An [sqlite3_file] object represents an open file in the 
1117 ** [sqlite3_vfs | OS interface layer].  Individual OS interface
1118 ** implementations will
1119 ** want to subclass this object by appending additional fields
1120 ** for their own use.  The pMethods entry is a pointer to an
1121 ** [sqlite3_io_methods] object that defines methods for performing
1122 ** I/O operations on the open file.
1123 */
1124 typedef struct sqlite3_file sqlite3_file;
1125 struct sqlite3_file {
1126   const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
1127 };
1128
1129 /*
1130 ** CAPI3REF: OS Interface File Virtual Methods Object
1131 **
1132 ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
1133 ** [sqlite3_file] object (or, more commonly, a subclass of the
1134 ** [sqlite3_file] object) with a pointer to an instance of this object.
1135 ** This object defines the methods used to perform various operations
1136 ** against the open file represented by the [sqlite3_file] object.
1137 **
1138 ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element 
1139 ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
1140 ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed.  The
1141 ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
1142 ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
1143 ** to NULL.
1144 **
1145 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
1146 ** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
1147 ** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]
1148 ** flag may be ORed in to indicate that only the data of the file
1149 ** and not its inode needs to be synced.
1150 **
1151 ** The integer values to xLock() and xUnlock() are one of
1152 ** <ul>
1153 ** <li> [SQLITE_LOCK_NONE],
1154 ** <li> [SQLITE_LOCK_SHARED],
1155 ** <li> [SQLITE_LOCK_RESERVED],
1156 ** <li> [SQLITE_LOCK_PENDING], or
1157 ** <li> [SQLITE_LOCK_EXCLUSIVE].
1158 ** </ul>
1159 ** xLock() increases the lock. xUnlock() decreases the lock.
1160 ** The xCheckReservedLock() method checks whether any database connection,
1161 ** either in this process or in some other process, is holding a RESERVED,
1162 ** PENDING, or EXCLUSIVE lock on the file.  It returns true
1163 ** if such a lock exists and false otherwise.
1164 **
1165 ** The xFileControl() method is a generic interface that allows custom
1166 ** VFS implementations to directly control an open file using the
1167 ** [sqlite3_file_control()] interface.  The second "op" argument is an
1168 ** integer opcode.  The third argument is a generic pointer intended to
1169 ** point to a structure that may contain arguments or space in which to
1170 ** write return values.  Potential uses for xFileControl() might be
1171 ** functions to enable blocking locks with timeouts, to change the
1172 ** locking strategy (for example to use dot-file locks), to inquire
1173 ** about the status of a lock, or to break stale locks.  The SQLite
1174 ** core reserves all opcodes less than 100 for its own use.
1175 ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
1176 ** Applications that define a custom xFileControl method should use opcodes
1177 ** greater than 100 to avoid conflicts.  VFS implementations should
1178 ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
1179 ** recognize.
1180 **
1181 ** The xSectorSize() method returns the sector size of the
1182 ** device that underlies the file.  The sector size is the
1183 ** minimum write that can be performed without disturbing
1184 ** other bytes in the file.  The xDeviceCharacteristics()
1185 ** method returns a bit vector describing behaviors of the
1186 ** underlying device:
1187 **
1188 ** <ul>
1189 ** <li> [SQLITE_IOCAP_ATOMIC]
1190 ** <li> [SQLITE_IOCAP_ATOMIC512]
1191 ** <li> [SQLITE_IOCAP_ATOMIC1K]
1192 ** <li> [SQLITE_IOCAP_ATOMIC2K]
1193 ** <li> [SQLITE_IOCAP_ATOMIC4K]
1194 ** <li> [SQLITE_IOCAP_ATOMIC8K]
1195 ** <li> [SQLITE_IOCAP_ATOMIC16K]
1196 ** <li> [SQLITE_IOCAP_ATOMIC32K]
1197 ** <li> [SQLITE_IOCAP_ATOMIC64K]
1198 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
1199 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
1200 ** </ul>
1201 **
1202 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1203 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1204 ** mean that writes of blocks that are nnn bytes in size and
1205 ** are aligned to an address which is an integer multiple of
1206 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1207 ** that when data is appended to a file, the data is appended
1208 ** first then the size of the file is extended, never the other
1209 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1210 ** information is written to disk in the same order as calls
1211 ** to xWrite().
1212 **
1213 ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
1214 ** in the unread portions of the buffer with zeros.  A VFS that
1215 ** fails to zero-fill short reads might seem to work.  However,
1216 ** failure to zero-fill short reads will eventually lead to
1217 ** database corruption.
1218 */
1219 typedef struct sqlite3_io_methods sqlite3_io_methods;
1220 struct sqlite3_io_methods {
1221   int iVersion;
1222   int (*xClose)(sqlite3_file*);
1223   int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
1224   int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
1225   int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
1226   int (*xSync)(sqlite3_file*, int flags);
1227   int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
1228   int (*xLock)(sqlite3_file*, int);
1229   int (*xUnlock)(sqlite3_file*, int);
1230   int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
1231   int (*xFileControl)(sqlite3_file*, int op, void *pArg);
1232   int (*xSectorSize)(sqlite3_file*);
1233   int (*xDeviceCharacteristics)(sqlite3_file*);
1234   /* Methods above are valid for version 1 */
1235   int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
1236   int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
1237   void (*xShmBarrier)(sqlite3_file*);
1238   int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
1239   /* Methods above are valid for version 2 */
1240   /* Additional methods may be added in future releases */
1241 };
1242
1243 /*
1244 ** CAPI3REF: Standard File Control Opcodes
1245 **
1246 ** These integer constants are opcodes for the xFileControl method
1247 ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
1248 ** interface.
1249 **
1250 ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
1251 ** opcode causes the xFileControl method to write the current state of
1252 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
1253 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
1254 ** into an integer that the pArg argument points to. This capability
1255 ** is used during testing and only needs to be supported when SQLITE_TEST
1256 ** is defined.
1257 **
1258 ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
1259 ** layer a hint of how large the database file will grow to be during the
1260 ** current transaction.  This hint is not guaranteed to be accurate but it
1261 ** is often close.  The underlying VFS might choose to preallocate database
1262 ** file space based on this hint in order to help writes to the database
1263 ** file run faster.
1264 **
1265 ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
1266 ** extends and truncates the database file in chunks of a size specified
1267 ** by the user. The fourth argument to [sqlite3_file_control()] should 
1268 ** point to an integer (type int) containing the new chunk-size to use
1269 ** for the nominated database. Allocating database file space in large
1270 ** chunks (say 1MB at a time), may reduce file-system fragmentation and
1271 ** improve performance on some systems.
1272 **
1273 ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
1274 ** to the [sqlite3_file] object associated with a particular database
1275 ** connection.  See the [sqlite3_file_control()] documentation for
1276 ** additional information.
1277 **
1278 ** ^(The [SQLITE_FCNTL_SYNC_OMITTED] opcode is generated internally by
1279 ** SQLite and sent to all VFSes in place of a call to the xSync method
1280 ** when the database connection has [PRAGMA synchronous] set to OFF.)^
1281 ** Some specialized VFSes need this signal in order to operate correctly
1282 ** when [PRAGMA synchronous | PRAGMA synchronous=OFF] is set, but most 
1283 ** VFSes do not need this signal and should silently ignore this opcode.
1284 ** Applications should not call [sqlite3_file_control()] with this
1285 ** opcode as doing so may disrupt the operation of the specialized VFSes
1286 ** that do require it.  
1287 */
1288 #define SQLITE_FCNTL_LOCKSTATE        1
1289 #define SQLITE_GET_LOCKPROXYFILE      2
1290 #define SQLITE_SET_LOCKPROXYFILE      3
1291 #define SQLITE_LAST_ERRNO             4
1292 #define SQLITE_FCNTL_SIZE_HINT        5
1293 #define SQLITE_FCNTL_CHUNK_SIZE       6
1294 #define SQLITE_FCNTL_FILE_POINTER     7
1295 #define SQLITE_FCNTL_SYNC_OMITTED     8
1296
1297
1298 /*
1299 ** CAPI3REF: Mutex Handle
1300 **
1301 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
1302 ** abstract type for a mutex object.  The SQLite core never looks
1303 ** at the internal representation of an [sqlite3_mutex].  It only
1304 ** deals with pointers to the [sqlite3_mutex] object.
1305 **
1306 ** Mutexes are created using [sqlite3_mutex_alloc()].
1307 */
1308 typedef struct sqlite3_mutex sqlite3_mutex;
1309
1310 /*
1311 ** CAPI3REF: OS Interface Object
1312 **
1313 ** An instance of the sqlite3_vfs object defines the interface between
1314 ** the SQLite core and the underlying operating system.  The "vfs"
1315 ** in the name of the object stands for "virtual file system".  See
1316 ** the [VFS | VFS documentation] for further information.
1317 **
1318 ** The value of the iVersion field is initially 1 but may be larger in
1319 ** future versions of SQLite.  Additional fields may be appended to this
1320 ** object when the iVersion value is increased.  Note that the structure
1321 ** of the sqlite3_vfs object changes in the transaction between
1322 ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
1323 ** modified.
1324 **
1325 ** The szOsFile field is the size of the subclassed [sqlite3_file]
1326 ** structure used by this VFS.  mxPathname is the maximum length of
1327 ** a pathname in this VFS.
1328 **
1329 ** Registered sqlite3_vfs objects are kept on a linked list formed by
1330 ** the pNext pointer.  The [sqlite3_vfs_register()]
1331 ** and [sqlite3_vfs_unregister()] interfaces manage this list
1332 ** in a thread-safe way.  The [sqlite3_vfs_find()] interface
1333 ** searches the list.  Neither the application code nor the VFS
1334 ** implementation should use the pNext pointer.
1335 **
1336 ** The pNext field is the only field in the sqlite3_vfs
1337 ** structure that SQLite will ever modify.  SQLite will only access
1338 ** or modify this field while holding a particular static mutex.
1339 ** The application should never modify anything within the sqlite3_vfs
1340 ** object once the object has been registered.
1341 **
1342 ** The zName field holds the name of the VFS module.  The name must
1343 ** be unique across all VFS modules.
1344 **
1345 ** [[sqlite3_vfs.xOpen]]
1346 ** ^SQLite guarantees that the zFilename parameter to xOpen
1347 ** is either a NULL pointer or string obtained
1348 ** from xFullPathname() with an optional suffix added.
1349 ** ^If a suffix is added to the zFilename parameter, it will
1350 ** consist of a single "-" character followed by no more than
1351 ** 10 alphanumeric and/or "-" characters.
1352 ** ^SQLite further guarantees that
1353 ** the string will be valid and unchanged until xClose() is
1354 ** called. Because of the previous sentence,
1355 ** the [sqlite3_file] can safely store a pointer to the
1356 ** filename if it needs to remember the filename for some reason.
1357 ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
1358 ** must invent its own temporary name for the file.  ^Whenever the 
1359 ** xFilename parameter is NULL it will also be the case that the
1360 ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1361 **
1362 ** The flags argument to xOpen() includes all bits set in
1363 ** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
1364 ** or [sqlite3_open16()] is used, then flags includes at least
1365 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. 
1366 ** If xOpen() opens a file read-only then it sets *pOutFlags to
1367 ** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
1368 **
1369 ** ^(SQLite will also add one of the following flags to the xOpen()
1370 ** call, depending on the object being opened:
1371 **
1372 ** <ul>
1373 ** <li>  [SQLITE_OPEN_MAIN_DB]
1374 ** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
1375 ** <li>  [SQLITE_OPEN_TEMP_DB]
1376 ** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
1377 ** <li>  [SQLITE_OPEN_TRANSIENT_DB]
1378 ** <li>  [SQLITE_OPEN_SUBJOURNAL]
1379 ** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
1380 ** <li>  [SQLITE_OPEN_WAL]
1381 ** </ul>)^
1382 **
1383 ** The file I/O implementation can use the object type flags to
1384 ** change the way it deals with files.  For example, an application
1385 ** that does not care about crash recovery or rollback might make
1386 ** the open of a journal file a no-op.  Writes to this journal would
1387 ** also be no-ops, and any attempt to read the journal would return
1388 ** SQLITE_IOERR.  Or the implementation might recognize that a database
1389 ** file will be doing page-aligned sector reads and writes in a random
1390 ** order and set up its I/O subsystem accordingly.
1391 **
1392 ** SQLite might also add one of the following flags to the xOpen method:
1393 **
1394 ** <ul>
1395 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
1396 ** <li> [SQLITE_OPEN_EXCLUSIVE]
1397 ** </ul>
1398 **
1399 ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1400 ** deleted when it is closed.  ^The [SQLITE_OPEN_DELETEONCLOSE]
1401 ** will be set for TEMP databases and their journals, transient
1402 ** databases, and subjournals.
1403 **
1404 ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
1405 ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
1406 ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
1407 ** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the 
1408 ** SQLITE_OPEN_CREATE, is used to indicate that file should always
1409 ** be created, and that it is an error if it already exists.
1410 ** It is <i>not</i> used to indicate the file should be opened 
1411 ** for exclusive access.
1412 **
1413 ** ^At least szOsFile bytes of memory are allocated by SQLite
1414 ** to hold the  [sqlite3_file] structure passed as the third
1415 ** argument to xOpen.  The xOpen method does not have to
1416 ** allocate the structure; it should just fill it in.  Note that
1417 ** the xOpen method must set the sqlite3_file.pMethods to either
1418 ** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do
1419 ** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods
1420 ** element will be valid after xOpen returns regardless of the success
1421 ** or failure of the xOpen call.
1422 **
1423 ** [[sqlite3_vfs.xAccess]]
1424 ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1425 ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1426 ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1427 ** to test whether a file is at least readable.   The file can be a
1428 ** directory.
1429 **
1430 ** ^SQLite will always allocate at least mxPathname+1 bytes for the
1431 ** output buffer xFullPathname.  The exact size of the output buffer
1432 ** is also passed as a parameter to both  methods. If the output buffer
1433 ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1434 ** handled as a fatal error by SQLite, vfs implementations should endeavor
1435 ** to prevent this by setting mxPathname to a sufficiently large value.
1436 **
1437 ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
1438 ** interfaces are not strictly a part of the filesystem, but they are
1439 ** included in the VFS structure for completeness.
1440 ** The xRandomness() function attempts to return nBytes bytes
1441 ** of good-quality randomness into zOut.  The return value is
1442 ** the actual number of bytes of randomness obtained.
1443 ** The xSleep() method causes the calling thread to sleep for at
1444 ** least the number of microseconds given.  ^The xCurrentTime()
1445 ** method returns a Julian Day Number for the current date and time as
1446 ** a floating point value.
1447 ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
1448 ** Day Number multiplied by 86400000 (the number of milliseconds in 
1449 ** a 24-hour day).  
1450 ** ^SQLite will use the xCurrentTimeInt64() method to get the current
1451 ** date and time if that method is available (if iVersion is 2 or 
1452 ** greater and the function pointer is not NULL) and will fall back
1453 ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
1454 **
1455 ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
1456 ** are not used by the SQLite core.  These optional interfaces are provided
1457 ** by some VFSes to facilitate testing of the VFS code. By overriding 
1458 ** system calls with functions under its control, a test program can
1459 ** simulate faults and error conditions that would otherwise be difficult
1460 ** or impossible to induce.  The set of system calls that can be overridden
1461 ** varies from one VFS to another, and from one version of the same VFS to the
1462 ** next.  Applications that use these interfaces must be prepared for any
1463 ** or all of these interfaces to be NULL or for their behavior to change
1464 ** from one release to the next.  Applications must not attempt to access
1465 ** any of these methods if the iVersion of the VFS is less than 3.
1466 */
1467 typedef struct sqlite3_vfs sqlite3_vfs;
1468 typedef void (*sqlite3_syscall_ptr)(void);
1469 struct sqlite3_vfs {
1470   int iVersion;            /* Structure version number (currently 3) */
1471   int szOsFile;            /* Size of subclassed sqlite3_file */
1472   int mxPathname;          /* Maximum file pathname length */
1473   sqlite3_vfs *pNext;      /* Next registered VFS */
1474   const char *zName;       /* Name of this virtual file system */
1475   void *pAppData;          /* Pointer to application-specific data */
1476   int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1477                int flags, int *pOutFlags);
1478   int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1479   int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1480   int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1481   void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1482   void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1483   void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
1484   void (*xDlClose)(sqlite3_vfs*, void*);
1485   int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1486   int (*xSleep)(sqlite3_vfs*, int microseconds);
1487   int (*xCurrentTime)(sqlite3_vfs*, double*);
1488   int (*xGetLastError)(sqlite3_vfs*, int, char *);
1489   /*
1490   ** The methods above are in version 1 of the sqlite_vfs object
1491   ** definition.  Those that follow are added in version 2 or later
1492   */
1493   int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
1494   /*
1495   ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
1496   ** Those below are for version 3 and greater.
1497   */
1498   int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
1499   sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
1500   const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
1501   /*
1502   ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
1503   ** New fields may be appended in figure versions.  The iVersion
1504   ** value will increment whenever this happens. 
1505   */
1506 };
1507
1508 /*
1509 ** CAPI3REF: Flags for the xAccess VFS method
1510 **
1511 ** These integer constants can be used as the third parameter to
1512 ** the xAccess method of an [sqlite3_vfs] object.  They determine
1513 ** what kind of permissions the xAccess method is looking for.
1514 ** With SQLITE_ACCESS_EXISTS, the xAccess method
1515 ** simply checks whether the file exists.
1516 ** With SQLITE_ACCESS_READWRITE, the xAccess method
1517 ** checks whether the named directory is both readable and writable
1518 ** (in other words, if files can be added, removed, and renamed within
1519 ** the directory).
1520 ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
1521 ** [temp_store_directory pragma], though this could change in a future
1522 ** release of SQLite.
1523 ** With SQLITE_ACCESS_READ, the xAccess method
1524 ** checks whether the file is readable.  The SQLITE_ACCESS_READ constant is
1525 ** currently unused, though it might be used in a future release of
1526 ** SQLite.
1527 */
1528 #define SQLITE_ACCESS_EXISTS    0
1529 #define SQLITE_ACCESS_READWRITE 1   /* Used by PRAGMA temp_store_directory */
1530 #define SQLITE_ACCESS_READ      2   /* Unused */
1531
1532 /*
1533 ** CAPI3REF: Flags for the xShmLock VFS method
1534 **
1535 ** These integer constants define the various locking operations
1536 ** allowed by the xShmLock method of [sqlite3_io_methods].  The
1537 ** following are the only legal combinations of flags to the
1538 ** xShmLock method:
1539 **
1540 ** <ul>
1541 ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
1542 ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
1543 ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
1544 ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
1545 ** </ul>
1546 **
1547 ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
1548 ** was given no the corresponding lock.  
1549 **
1550 ** The xShmLock method can transition between unlocked and SHARED or
1551 ** between unlocked and EXCLUSIVE.  It cannot transition between SHARED
1552 ** and EXCLUSIVE.
1553 */
1554 #define SQLITE_SHM_UNLOCK       1
1555 #define SQLITE_SHM_LOCK         2
1556 #define SQLITE_SHM_SHARED       4
1557 #define SQLITE_SHM_EXCLUSIVE    8
1558
1559 /*
1560 ** CAPI3REF: Maximum xShmLock index
1561 **
1562 ** The xShmLock method on [sqlite3_io_methods] may use values
1563 ** between 0 and this upper bound as its "offset" argument.
1564 ** The SQLite core will never attempt to acquire or release a
1565 ** lock outside of this range
1566 */
1567 #define SQLITE_SHM_NLOCK        8
1568
1569
1570 /*
1571 ** CAPI3REF: Initialize The SQLite Library
1572 **
1573 ** ^The sqlite3_initialize() routine initializes the
1574 ** SQLite library.  ^The sqlite3_shutdown() routine
1575 ** deallocates any resources that were allocated by sqlite3_initialize().
1576 ** These routines are designed to aid in process initialization and
1577 ** shutdown on embedded systems.  Workstation applications using
1578 ** SQLite normally do not need to invoke either of these routines.
1579 **
1580 ** A call to sqlite3_initialize() is an "effective" call if it is
1581 ** the first time sqlite3_initialize() is invoked during the lifetime of
1582 ** the process, or if it is the first time sqlite3_initialize() is invoked
1583 ** following a call to sqlite3_shutdown().  ^(Only an effective call
1584 ** of sqlite3_initialize() does any initialization.  All other calls
1585 ** are harmless no-ops.)^
1586 **
1587 ** A call to sqlite3_shutdown() is an "effective" call if it is the first
1588 ** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only
1589 ** an effective call to sqlite3_shutdown() does any deinitialization.
1590 ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
1591 **
1592 ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
1593 ** is not.  The sqlite3_shutdown() interface must only be called from a
1594 ** single thread.  All open [database connections] must be closed and all
1595 ** other SQLite resources must be deallocated prior to invoking
1596 ** sqlite3_shutdown().
1597 **
1598 ** Among other things, ^sqlite3_initialize() will invoke
1599 ** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()
1600 ** will invoke sqlite3_os_end().
1601 **
1602 ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
1603 ** ^If for some reason, sqlite3_initialize() is unable to initialize
1604 ** the library (perhaps it is unable to allocate a needed resource such
1605 ** as a mutex) it returns an [error code] other than [SQLITE_OK].
1606 **
1607 ** ^The sqlite3_initialize() routine is called internally by many other
1608 ** SQLite interfaces so that an application usually does not need to
1609 ** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
1610 ** calls sqlite3_initialize() so the SQLite library will be automatically
1611 ** initialized when [sqlite3_open()] is called if it has not be initialized
1612 ** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
1613 ** compile-time option, then the automatic calls to sqlite3_initialize()
1614 ** are omitted and the application must call sqlite3_initialize() directly
1615 ** prior to using any other SQLite interface.  For maximum portability,
1616 ** it is recommended that applications always invoke sqlite3_initialize()
1617 ** directly prior to using any other SQLite interface.  Future releases
1618 ** of SQLite may require this.  In other words, the behavior exhibited
1619 ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
1620 ** default behavior in some future release of SQLite.
1621 **
1622 ** The sqlite3_os_init() routine does operating-system specific
1623 ** initialization of the SQLite library.  The sqlite3_os_end()
1624 ** routine undoes the effect of sqlite3_os_init().  Typical tasks
1625 ** performed by these routines include allocation or deallocation
1626 ** of static resources, initialization of global variables,
1627 ** setting up a default [sqlite3_vfs] module, or setting up
1628 ** a default configuration using [sqlite3_config()].
1629 **
1630 ** The application should never invoke either sqlite3_os_init()
1631 ** or sqlite3_os_end() directly.  The application should only invoke
1632 ** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
1633 ** interface is called automatically by sqlite3_initialize() and
1634 ** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
1635 ** implementations for sqlite3_os_init() and sqlite3_os_end()
1636 ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
1637 ** When [custom builds | built for other platforms]
1638 ** (using the [SQLITE_OS_OTHER=1] compile-time
1639 ** option) the application must supply a suitable implementation for
1640 ** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
1641 ** implementation of sqlite3_os_init() or sqlite3_os_end()
1642 ** must return [SQLITE_OK] on success and some other [error code] upon
1643 ** failure.
1644 */
1645 SQLITE_API int sqlite3_initialize(void);
1646 SQLITE_API int sqlite3_shutdown(void);
1647 SQLITE_API int sqlite3_os_init(void);
1648 SQLITE_API int sqlite3_os_end(void);
1649
1650 /*
1651 ** CAPI3REF: Configuring The SQLite Library
1652 **
1653 ** The sqlite3_config() interface is used to make global configuration
1654 ** changes to SQLite in order to tune SQLite to the specific needs of
1655 ** the application.  The default configuration is recommended for most
1656 ** applications and so this routine is usually not necessary.  It is
1657 ** provided to support rare applications with unusual needs.
1658 **
1659 ** The sqlite3_config() interface is not threadsafe.  The application
1660 ** must insure that no other SQLite interfaces are invoked by other
1661 ** threads while sqlite3_config() is running.  Furthermore, sqlite3_config()
1662 ** may only be invoked prior to library initialization using
1663 ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1664 ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
1665 ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
1666 ** Note, however, that ^sqlite3_config() can be called as part of the
1667 ** implementation of an application-defined [sqlite3_os_init()].
1668 **
1669 ** The first argument to sqlite3_config() is an integer
1670 ** [configuration option] that determines
1671 ** what property of SQLite is to be configured.  Subsequent arguments
1672 ** vary depending on the [configuration option]
1673 ** in the first argument.
1674 **
1675 ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
1676 ** ^If the option is unknown or SQLite is unable to set the option
1677 ** then this routine returns a non-zero [error code].
1678 */
1679 SQLITE_API int sqlite3_config(int, ...);
1680
1681 /*
1682 ** CAPI3REF: Configure database connections
1683 **
1684 ** The sqlite3_db_config() interface is used to make configuration
1685 ** changes to a [database connection].  The interface is similar to
1686 ** [sqlite3_config()] except that the changes apply to a single
1687 ** [database connection] (specified in the first argument).
1688 **
1689 ** The second argument to sqlite3_db_config(D,V,...)  is the
1690 ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code 
1691 ** that indicates what aspect of the [database connection] is being configured.
1692 ** Subsequent arguments vary depending on the configuration verb.
1693 **
1694 ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
1695 ** the call is considered successful.
1696 */
1697 SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
1698
1699 /*
1700 ** CAPI3REF: Memory Allocation Routines
1701 **
1702 ** An instance of this object defines the interface between SQLite
1703 ** and low-level memory allocation routines.
1704 **
1705 ** This object is used in only one place in the SQLite interface.
1706 ** A pointer to an instance of this object is the argument to
1707 ** [sqlite3_config()] when the configuration option is
1708 ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].  
1709 ** By creating an instance of this object
1710 ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
1711 ** during configuration, an application can specify an alternative
1712 ** memory allocation subsystem for SQLite to use for all of its
1713 ** dynamic memory needs.
1714 **
1715 ** Note that SQLite comes with several [built-in memory allocators]
1716 ** that are perfectly adequate for the overwhelming majority of applications
1717 ** and that this object is only useful to a tiny minority of applications
1718 ** with specialized memory allocation requirements.  This object is
1719 ** also used during testing of SQLite in order to specify an alternative
1720 ** memory allocator that simulates memory out-of-memory conditions in
1721 ** order to verify that SQLite recovers gracefully from such
1722 ** conditions.
1723 **
1724 ** The xMalloc and xFree methods must work like the
1725 ** malloc() and free() functions from the standard C library.
1726 ** The xRealloc method must work like realloc() from the standard C library
1727 ** with the exception that if the second argument to xRealloc is zero,
1728 ** xRealloc must be a no-op - it must not perform any allocation or
1729 ** deallocation.  ^SQLite guarantees that the second argument to
1730 ** xRealloc is always a value returned by a prior call to xRoundup.
1731 ** And so in cases where xRoundup always returns a positive number,
1732 ** xRealloc can perform exactly as the standard library realloc() and
1733 ** still be in compliance with this specification.
1734 **
1735 ** xSize should return the allocated size of a memory allocation
1736 ** previously obtained from xMalloc or xRealloc.  The allocated size
1737 ** is always at least as big as the requested size but may be larger.
1738 **
1739 ** The xRoundup method returns what would be the allocated size of
1740 ** a memory allocation given a particular requested size.  Most memory
1741 ** allocators round up memory allocations at least to the next multiple
1742 ** of 8.  Some allocators round up to a larger multiple or to a power of 2.
1743 ** Every memory allocation request coming in through [sqlite3_malloc()]
1744 ** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0, 
1745 ** that causes the corresponding memory allocation to fail.
1746 **
1747 ** The xInit method initializes the memory allocator.  (For example,
1748 ** it might allocate any require mutexes or initialize internal data
1749 ** structures.  The xShutdown method is invoked (indirectly) by
1750 ** [sqlite3_shutdown()] and should deallocate any resources acquired
1751 ** by xInit.  The pAppData pointer is used as the only parameter to
1752 ** xInit and xShutdown.
1753 **
1754 ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
1755 ** the xInit method, so the xInit method need not be threadsafe.  The
1756 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
1757 ** not need to be threadsafe either.  For all other methods, SQLite
1758 ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
1759 ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
1760 ** it is by default) and so the methods are automatically serialized.
1761 ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
1762 ** methods must be threadsafe or else make their own arrangements for
1763 ** serialization.
1764 **
1765 ** SQLite will never invoke xInit() more than once without an intervening
1766 ** call to xShutdown().
1767 */
1768 typedef struct sqlite3_mem_methods sqlite3_mem_methods;
1769 struct sqlite3_mem_methods {
1770   void *(*xMalloc)(int);         /* Memory allocation function */
1771   void (*xFree)(void*);          /* Free a prior allocation */
1772   void *(*xRealloc)(void*,int);  /* Resize an allocation */
1773   int (*xSize)(void*);           /* Return the size of an allocation */
1774   int (*xRoundup)(int);          /* Round up request size to allocation size */
1775   int (*xInit)(void*);           /* Initialize the memory allocator */
1776   void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
1777   void *pAppData;                /* Argument to xInit() and xShutdown() */
1778 };
1779
1780 /*
1781 ** CAPI3REF: Configuration Options
1782 ** KEYWORDS: {configuration option}
1783 **
1784 ** These constants are the available integer configuration options that
1785 ** can be passed as the first argument to the [sqlite3_config()] interface.
1786 **
1787 ** New configuration options may be added in future releases of SQLite.
1788 ** Existing configuration options might be discontinued.  Applications
1789 ** should check the return code from [sqlite3_config()] to make sure that
1790 ** the call worked.  The [sqlite3_config()] interface will return a
1791 ** non-zero [error code] if a discontinued or unsupported configuration option
1792 ** is invoked.
1793 **
1794 ** <dl>
1795 ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
1796 ** <dd>There are no arguments to this option.  ^This option sets the
1797 ** [threading mode] to Single-thread.  In other words, it disables
1798 ** all mutexing and puts SQLite into a mode where it can only be used
1799 ** by a single thread.   ^If SQLite is compiled with
1800 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1801 ** it is not possible to change the [threading mode] from its default
1802 ** value of Single-thread and so [sqlite3_config()] will return 
1803 ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
1804 ** configuration option.</dd>
1805 **
1806 ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
1807 ** <dd>There are no arguments to this option.  ^This option sets the
1808 ** [threading mode] to Multi-thread.  In other words, it disables
1809 ** mutexing on [database connection] and [prepared statement] objects.
1810 ** The application is responsible for serializing access to
1811 ** [database connections] and [prepared statements].  But other mutexes
1812 ** are enabled so that SQLite will be safe to use in a multi-threaded
1813 ** environment as long as no two threads attempt to use the same
1814 ** [database connection] at the same time.  ^If SQLite is compiled with
1815 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1816 ** it is not possible to set the Multi-thread [threading mode] and
1817 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1818 ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
1819 **
1820 ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
1821 ** <dd>There are no arguments to this option.  ^This option sets the
1822 ** [threading mode] to Serialized. In other words, this option enables
1823 ** all mutexes including the recursive
1824 ** mutexes on [database connection] and [prepared statement] objects.
1825 ** In this mode (which is the default when SQLite is compiled with
1826 ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
1827 ** to [database connections] and [prepared statements] so that the
1828 ** application is free to use the same [database connection] or the
1829 ** same [prepared statement] in different threads at the same time.
1830 ** ^If SQLite is compiled with
1831 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1832 ** it is not possible to set the Serialized [threading mode] and
1833 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1834 ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
1835 **
1836 ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
1837 ** <dd> ^(This option takes a single argument which is a pointer to an
1838 ** instance of the [sqlite3_mem_methods] structure.  The argument specifies
1839 ** alternative low-level memory allocation routines to be used in place of
1840 ** the memory allocation routines built into SQLite.)^ ^SQLite makes
1841 ** its own private copy of the content of the [sqlite3_mem_methods] structure
1842 ** before the [sqlite3_config()] call returns.</dd>
1843 **
1844 ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
1845 ** <dd> ^(This option takes a single argument which is a pointer to an
1846 ** instance of the [sqlite3_mem_methods] structure.  The [sqlite3_mem_methods]
1847 ** structure is filled with the currently defined memory allocation routines.)^
1848 ** This option can be used to overload the default memory allocation
1849 ** routines with a wrapper that simulations memory allocation failure or
1850 ** tracks memory usage, for example. </dd>
1851 **
1852 ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
1853 ** <dd> ^This option takes single argument of type int, interpreted as a 
1854 ** boolean, which enables or disables the collection of memory allocation 
1855 ** statistics. ^(When memory allocation statistics are disabled, the 
1856 ** following SQLite interfaces become non-operational:
1857 **   <ul>
1858 **   <li> [sqlite3_memory_used()]
1859 **   <li> [sqlite3_memory_highwater()]
1860 **   <li> [sqlite3_soft_heap_limit64()]
1861 **   <li> [sqlite3_status()]
1862 **   </ul>)^
1863 ** ^Memory allocation statistics are enabled by default unless SQLite is
1864 ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
1865 ** allocation statistics are disabled by default.
1866 ** </dd>
1867 **
1868 ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
1869 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
1870 ** scratch memory.  There are three arguments:  A pointer an 8-byte
1871 ** aligned memory buffer from which the scratch allocations will be
1872 ** drawn, the size of each scratch allocation (sz),
1873 ** and the maximum number of scratch allocations (N).  The sz
1874 ** argument must be a multiple of 16.
1875 ** The first argument must be a pointer to an 8-byte aligned buffer
1876 ** of at least sz*N bytes of memory.
1877 ** ^SQLite will use no more than two scratch buffers per thread.  So
1878 ** N should be set to twice the expected maximum number of threads.
1879 ** ^SQLite will never require a scratch buffer that is more than 6
1880 ** times the database page size. ^If SQLite needs needs additional
1881 ** scratch memory beyond what is provided by this configuration option, then 
1882 ** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
1883 **
1884 ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
1885 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
1886 ** the database page cache with the default page cache implementation.  
1887 ** This configuration should not be used if an application-define page
1888 ** cache implementation is loaded using the SQLITE_CONFIG_PCACHE option.
1889 ** There are three arguments to this option: A pointer to 8-byte aligned
1890 ** memory, the size of each page buffer (sz), and the number of pages (N).
1891 ** The sz argument should be the size of the largest database page
1892 ** (a power of two between 512 and 32768) plus a little extra for each
1893 ** page header.  ^The page header size is 20 to 40 bytes depending on
1894 ** the host architecture.  ^It is harmless, apart from the wasted memory,
1895 ** to make sz a little too large.  The first
1896 ** argument should point to an allocation of at least sz*N bytes of memory.
1897 ** ^SQLite will use the memory provided by the first argument to satisfy its
1898 ** memory needs for the first N pages that it adds to cache.  ^If additional
1899 ** page cache memory is needed beyond what is provided by this option, then
1900 ** SQLite goes to [sqlite3_malloc()] for the additional storage space.
1901 ** The pointer in the first argument must
1902 ** be aligned to an 8-byte boundary or subsequent behavior of SQLite
1903 ** will be undefined.</dd>
1904 **
1905 ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
1906 ** <dd> ^This option specifies a static memory buffer that SQLite will use
1907 ** for all of its dynamic memory allocation needs beyond those provided
1908 ** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
1909 ** There are three arguments: An 8-byte aligned pointer to the memory,
1910 ** the number of bytes in the memory buffer, and the minimum allocation size.
1911 ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
1912 ** to using its default memory allocator (the system malloc() implementation),
1913 ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the
1914 ** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
1915 ** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
1916 ** allocator is engaged to handle all of SQLites memory allocation needs.
1917 ** The first pointer (the memory pointer) must be aligned to an 8-byte
1918 ** boundary or subsequent behavior of SQLite will be undefined.
1919 ** The minimum allocation size is capped at 2^12. Reasonable values
1920 ** for the minimum allocation size are 2^5 through 2^8.</dd>
1921 **
1922 ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
1923 ** <dd> ^(This option takes a single argument which is a pointer to an
1924 ** instance of the [sqlite3_mutex_methods] structure.  The argument specifies
1925 ** alternative low-level mutex routines to be used in place
1926 ** the mutex routines built into SQLite.)^  ^SQLite makes a copy of the
1927 ** content of the [sqlite3_mutex_methods] structure before the call to
1928 ** [sqlite3_config()] returns. ^If SQLite is compiled with
1929 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1930 ** the entire mutexing subsystem is omitted from the build and hence calls to
1931 ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
1932 ** return [SQLITE_ERROR].</dd>
1933 **
1934 ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
1935 ** <dd> ^(This option takes a single argument which is a pointer to an
1936 ** instance of the [sqlite3_mutex_methods] structure.  The
1937 ** [sqlite3_mutex_methods]
1938 ** structure is filled with the currently defined mutex routines.)^
1939 ** This option can be used to overload the default mutex allocation
1940 ** routines with a wrapper used to track mutex usage for performance
1941 ** profiling or testing, for example.   ^If SQLite is compiled with
1942 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1943 ** the entire mutexing subsystem is omitted from the build and hence calls to
1944 ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
1945 ** return [SQLITE_ERROR].</dd>
1946 **
1947 ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
1948 ** <dd> ^(This option takes two arguments that determine the default
1949 ** memory allocation for the lookaside memory allocator on each
1950 ** [database connection].  The first argument is the
1951 ** size of each lookaside buffer slot and the second is the number of
1952 ** slots allocated to each database connection.)^  ^(This option sets the
1953 ** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
1954 ** verb to [sqlite3_db_config()] can be used to change the lookaside
1955 ** configuration on individual connections.)^ </dd>
1956 **
1957 ** [[SQLITE_CONFIG_PCACHE]] <dt>SQLITE_CONFIG_PCACHE</dt>
1958 ** <dd> ^(This option takes a single argument which is a pointer to
1959 ** an [sqlite3_pcache_methods] object.  This object specifies the interface
1960 ** to a custom page cache implementation.)^  ^SQLite makes a copy of the
1961 ** object and uses it for page cache memory allocations.</dd>
1962 **
1963 ** [[SQLITE_CONFIG_GETPCACHE]] <dt>SQLITE_CONFIG_GETPCACHE</dt>
1964 ** <dd> ^(This option takes a single argument which is a pointer to an
1965 ** [sqlite3_pcache_methods] object.  SQLite copies of the current
1966 ** page cache implementation into that object.)^ </dd>
1967 **
1968 ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
1969 ** <dd> ^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
1970 ** function with a call signature of void(*)(void*,int,const char*), 
1971 ** and a pointer to void. ^If the function pointer is not NULL, it is
1972 ** invoked by [sqlite3_log()] to process each logging event.  ^If the
1973 ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
1974 ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
1975 ** passed through as the first parameter to the application-defined logger
1976 ** function whenever that function is invoked.  ^The second parameter to
1977 ** the logger function is a copy of the first parameter to the corresponding
1978 ** [sqlite3_log()] call and is intended to be a [result code] or an
1979 ** [extended result code].  ^The third parameter passed to the logger is
1980 ** log message after formatting via [sqlite3_snprintf()].
1981 ** The SQLite logging interface is not reentrant; the logger function
1982 ** supplied by the application must not invoke any SQLite interface.
1983 ** In a multi-threaded application, the application-defined logger
1984 ** function must be threadsafe. </dd>
1985 **
1986 ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
1987 ** <dd> This option takes a single argument of type int. If non-zero, then
1988 ** URI handling is globally enabled. If the parameter is zero, then URI handling
1989 ** is globally disabled. If URI handling is globally enabled, all filenames
1990 ** passed to [sqlite3_open()], [sqlite3_open_v2()], [sqlite3_open16()] or
1991 ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
1992 ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
1993 ** connection is opened. If it is globally disabled, filenames are
1994 ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
1995 ** database connection is opened. By default, URI handling is globally
1996 ** disabled. The default value may be changed by compiling with the
1997 ** [SQLITE_USE_URI] symbol defined.
1998 ** </dl>
1999 */
2000 #define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
2001 #define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
2002 #define SQLITE_CONFIG_SERIALIZED    3  /* nil */
2003 #define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
2004 #define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
2005 #define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */
2006 #define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
2007 #define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
2008 #define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
2009 #define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
2010 #define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
2011 /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ 
2012 #define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
2013 #define SQLITE_CONFIG_PCACHE       14  /* sqlite3_pcache_methods* */
2014 #define SQLITE_CONFIG_GETPCACHE    15  /* sqlite3_pcache_methods* */
2015 #define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
2016 #define SQLITE_CONFIG_URI          17  /* int */
2017
2018 /*
2019 ** CAPI3REF: Database Connection Configuration Options
2020 **
2021 ** These constants are the available integer configuration options that
2022 ** can be passed as the second argument to the [sqlite3_db_config()] interface.
2023 **
2024 ** New configuration options may be added in future releases of SQLite.
2025 ** Existing configuration options might be discontinued.  Applications
2026 ** should check the return code from [sqlite3_db_config()] to make sure that
2027 ** the call worked.  ^The [sqlite3_db_config()] interface will return a
2028 ** non-zero [error code] if a discontinued or unsupported configuration option
2029 ** is invoked.
2030 **
2031 ** <dl>
2032 ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
2033 ** <dd> ^This option takes three additional arguments that determine the 
2034 ** [lookaside memory allocator] configuration for the [database connection].
2035 ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
2036 ** pointer to a memory buffer to use for lookaside memory.
2037 ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
2038 ** may be NULL in which case SQLite will allocate the
2039 ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
2040 ** size of each lookaside buffer slot.  ^The third argument is the number of
2041 ** slots.  The size of the buffer in the first argument must be greater than
2042 ** or equal to the product of the second and third arguments.  The buffer
2043 ** must be aligned to an 8-byte boundary.  ^If the second argument to
2044 ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
2045 ** rounded down to the next smaller multiple of 8.  ^(The lookaside memory
2046 ** configuration for a database connection can only be changed when that
2047 ** connection is not currently using lookaside memory, or in other words
2048 ** when the "current value" returned by
2049 ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
2050 ** Any attempt to change the lookaside memory configuration when lookaside
2051 ** memory is in use leaves the configuration unchanged and returns 
2052 ** [SQLITE_BUSY].)^</dd>
2053 **
2054 ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
2055 ** <dd> ^This option is used to enable or disable the enforcement of
2056 ** [foreign key constraints].  There should be two additional arguments.
2057 ** The first argument is an integer which is 0 to disable FK enforcement,
2058 ** positive to enable FK enforcement or negative to leave FK enforcement
2059 ** unchanged.  The second parameter is a pointer to an integer into which
2060 ** is written 0 or 1 to indicate whether FK enforcement is off or on
2061 ** following this call.  The second parameter may be a NULL pointer, in
2062 ** which case the FK enforcement setting is not reported back. </dd>
2063 **
2064 ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
2065 ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
2066 ** There should be two additional arguments.
2067 ** The first argument is an integer which is 0 to disable triggers,
2068 ** positive to enable triggers or negative to leave the setting unchanged.
2069 ** The second parameter is a pointer to an integer into which
2070 ** is written 0 or 1 to indicate whether triggers are disabled or enabled
2071 ** following this call.  The second parameter may be a NULL pointer, in
2072 ** which case the trigger setting is not reported back. </dd>
2073 **
2074 ** </dl>
2075 */
2076 #define SQLITE_DBCONFIG_LOOKASIDE       1001  /* void* int int */
2077 #define SQLITE_DBCONFIG_ENABLE_FKEY     1002  /* int int* */
2078 #define SQLITE_DBCONFIG_ENABLE_TRIGGER  1003  /* int int* */
2079
2080
2081 /*
2082 ** CAPI3REF: Enable Or Disable Extended Result Codes
2083 **
2084 ** ^The sqlite3_extended_result_codes() routine enables or disables the
2085 ** [extended result codes] feature of SQLite. ^The extended result
2086 ** codes are disabled by default for historical compatibility.
2087 */
2088 SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
2089
2090 /*
2091 ** CAPI3REF: Last Insert Rowid
2092 **
2093 ** ^Each entry in an SQLite table has a unique 64-bit signed
2094 ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
2095 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
2096 ** names are not also used by explicitly declared columns. ^If
2097 ** the table has a column of type [INTEGER PRIMARY KEY] then that column
2098 ** is another alias for the rowid.
2099 **
2100 ** ^This routine returns the [rowid] of the most recent
2101 ** successful [INSERT] into the database from the [database connection]
2102 ** in the first argument.  ^As of SQLite version 3.7.7, this routines
2103 ** records the last insert rowid of both ordinary tables and [virtual tables].
2104 ** ^If no successful [INSERT]s
2105 ** have ever occurred on that database connection, zero is returned.
2106 **
2107 ** ^(If an [INSERT] occurs within a trigger or within a [virtual table]
2108 ** method, then this routine will return the [rowid] of the inserted
2109 ** row as long as the trigger or virtual table method is running.
2110 ** But once the trigger or virtual table method ends, the value returned 
2111 ** by this routine reverts to what it was before the trigger or virtual
2112 ** table method began.)^
2113 **
2114 ** ^An [INSERT] that fails due to a constraint violation is not a
2115 ** successful [INSERT] and does not change the value returned by this
2116 ** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
2117 ** and INSERT OR ABORT make no changes to the return value of this
2118 ** routine when their insertion fails.  ^(When INSERT OR REPLACE
2119 ** encounters a constraint violation, it does not fail.  The
2120 ** INSERT continues to completion after deleting rows that caused
2121 ** the constraint problem so INSERT OR REPLACE will always change
2122 ** the return value of this interface.)^
2123 **
2124 ** ^For the purposes of this routine, an [INSERT] is considered to
2125 ** be successful even if it is subsequently rolled back.
2126 **
2127 ** This function is accessible to SQL statements via the
2128 ** [last_insert_rowid() SQL function].
2129 **
2130 ** If a separate thread performs a new [INSERT] on the same
2131 ** database connection while the [sqlite3_last_insert_rowid()]
2132 ** function is running and thus changes the last insert [rowid],
2133 ** then the value returned by [sqlite3_last_insert_rowid()] is
2134 ** unpredictable and might not equal either the old or the new
2135 ** last insert [rowid].
2136 */
2137 SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
2138
2139 /*
2140 ** CAPI3REF: Count The Number Of Rows Modified
2141 **
2142 ** ^This function returns the number of database rows that were changed
2143 ** or inserted or deleted by the most recently completed SQL statement
2144 ** on the [database connection] specified by the first parameter.
2145 ** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
2146 ** or [DELETE] statement are counted.  Auxiliary changes caused by
2147 ** triggers or [foreign key actions] are not counted.)^ Use the
2148 ** [sqlite3_total_changes()] function to find the total number of changes
2149 ** including changes caused by triggers and foreign key actions.
2150 **
2151 ** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
2152 ** are not counted.  Only real table changes are counted.
2153 **
2154 ** ^(A "row change" is a change to a single row of a single table
2155 ** caused by an INSERT, DELETE, or UPDATE statement.  Rows that
2156 ** are changed as side effects of [REPLACE] constraint resolution,
2157 ** rollback, ABORT processing, [DROP TABLE], or by any other
2158 ** mechanisms do not count as direct row changes.)^
2159 **
2160 ** A "trigger context" is a scope of execution that begins and
2161 ** ends with the script of a [CREATE TRIGGER | trigger]. 
2162 ** Most SQL statements are
2163 ** evaluated outside of any trigger.  This is the "top level"
2164 ** trigger context.  If a trigger fires from the top level, a
2165 ** new trigger context is entered for the duration of that one
2166 ** trigger.  Subtriggers create subcontexts for their duration.
2167 **
2168 ** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
2169 ** not create a new trigger context.
2170 **
2171 ** ^This function returns the number of direct row changes in the
2172 ** most recent INSERT, UPDATE, or DELETE statement within the same
2173 ** trigger context.
2174 **
2175 ** ^Thus, when called from the top level, this function returns the
2176 ** number of changes in the most recent INSERT, UPDATE, or DELETE
2177 ** that also occurred at the top level.  ^(Within the body of a trigger,
2178 ** the sqlite3_changes() interface can be called to find the number of
2179 ** changes in the most recently completed INSERT, UPDATE, or DELETE
2180 ** statement within the body of the same trigger.
2181 ** However, the number returned does not include changes
2182 ** caused by subtriggers since those have their own context.)^
2183 **
2184 ** See also the [sqlite3_total_changes()] interface, the
2185 ** [count_changes pragma], and the [changes() SQL function].
2186 **
2187 ** If a separate thread makes changes on the same database connection
2188 ** while [sqlite3_changes()] is running then the value returned
2189 ** is unpredictable and not meaningful.
2190 */
2191 SQLITE_API int sqlite3_changes(sqlite3*);
2192
2193 /*
2194 ** CAPI3REF: Total Number Of Rows Modified
2195 **
2196 ** ^This function returns the number of row changes caused by [INSERT],
2197 ** [UPDATE] or [DELETE] statements since the [database connection] was opened.
2198 ** ^(The count returned by sqlite3_total_changes() includes all changes
2199 ** from all [CREATE TRIGGER | trigger] contexts and changes made by
2200 ** [foreign key actions]. However,
2201 ** the count does not include changes used to implement [REPLACE] constraints,
2202 ** do rollbacks or ABORT processing, or [DROP TABLE] processing.  The
2203 ** count does not include rows of views that fire an [INSTEAD OF trigger],
2204 ** though if the INSTEAD OF trigger makes changes of its own, those changes 
2205 ** are counted.)^
2206 ** ^The sqlite3_total_changes() function counts the changes as soon as
2207 ** the statement that makes them is completed (when the statement handle
2208 ** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
2209 **
2210 ** See also the [sqlite3_changes()] interface, the
2211 ** [count_changes pragma], and the [total_changes() SQL function].
2212 **
2213 ** If a separate thread makes changes on the same database connection
2214 ** while [sqlite3_total_changes()] is running then the value
2215 ** returned is unpredictable and not meaningful.
2216 */
2217 SQLITE_API int sqlite3_total_changes(sqlite3*);
2218
2219 /*
2220 ** CAPI3REF: Interrupt A Long-Running Query
2221 **
2222 ** ^This function causes any pending database operation to abort and
2223 ** return at its earliest opportunity. This routine is typically
2224 ** called in response to a user action such as pressing "Cancel"
2225 ** or Ctrl-C where the user wants a long query operation to halt
2226 ** immediately.
2227 **
2228 ** ^It is safe to call this routine from a thread different from the
2229 ** thread that is currently running the database operation.  But it
2230 ** is not safe to call this routine with a [database connection] that
2231 ** is closed or might close before sqlite3_interrupt() returns.
2232 **
2233 ** ^If an SQL operation is very nearly finished at the time when
2234 ** sqlite3_interrupt() is called, then it might not have an opportunity
2235 ** to be interrupted and might continue to completion.
2236 **
2237 ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
2238 ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
2239 ** that is inside an explicit transaction, then the entire transaction
2240 ** will be rolled back automatically.
2241 **
2242 ** ^The sqlite3_interrupt(D) call is in effect until all currently running
2243 ** SQL statements on [database connection] D complete.  ^Any new SQL statements
2244 ** that are started after the sqlite3_interrupt() call and before the 
2245 ** running statements reaches zero are interrupted as if they had been
2246 ** running prior to the sqlite3_interrupt() call.  ^New SQL statements
2247 ** that are started after the running statement count reaches zero are
2248 ** not effected by the sqlite3_interrupt().
2249 ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
2250 ** SQL statements is a no-op and has no effect on SQL statements
2251 ** that are started after the sqlite3_interrupt() call returns.
2252 **
2253 ** If the database connection closes while [sqlite3_interrupt()]
2254 ** is running then bad things will likely happen.
2255 */
2256 SQLITE_API void sqlite3_interrupt(sqlite3*);
2257
2258 /*
2259 ** CAPI3REF: Determine If An SQL Statement Is Complete
2260 **
2261 ** These routines are useful during command-line input to determine if the
2262 ** currently entered text seems to form a complete SQL statement or
2263 ** if additional input is needed before sending the text into
2264 ** SQLite for parsing.  ^These routines return 1 if the input string
2265 ** appears to be a complete SQL statement.  ^A statement is judged to be
2266 ** complete if it ends with a semicolon token and is not a prefix of a
2267 ** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within
2268 ** string literals or quoted identifier names or comments are not
2269 ** independent tokens (they are part of the token in which they are
2270 ** embedded) and thus do not count as a statement terminator.  ^Whitespace
2271 ** and comments that follow the final semicolon are ignored.
2272 **
2273 ** ^These routines return 0 if the statement is incomplete.  ^If a
2274 ** memory allocation fails, then SQLITE_NOMEM is returned.
2275 **
2276 ** ^These routines do not parse the SQL statements thus
2277 ** will not detect syntactically incorrect SQL.
2278 **
2279 ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior 
2280 ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
2281 ** automatically by sqlite3_complete16().  If that initialization fails,
2282 ** then the return value from sqlite3_complete16() will be non-zero
2283 ** regardless of whether or not the input SQL is complete.)^
2284 **
2285 ** The input to [sqlite3_complete()] must be a zero-terminated
2286 ** UTF-8 string.
2287 **
2288 ** The input to [sqlite3_complete16()] must be a zero-terminated
2289 ** UTF-16 string in native byte order.
2290 */
2291 SQLITE_API int sqlite3_complete(const char *sql);
2292 SQLITE_API int sqlite3_complete16(const void *sql);
2293
2294 /*
2295 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
2296 **
2297 ** ^This routine sets a callback function that might be invoked whenever
2298 ** an attempt is made to open a database table that another thread
2299 ** or process has locked.
2300 **
2301 ** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
2302 ** is returned immediately upon encountering the lock.  ^If the busy callback
2303 ** is not NULL, then the callback might be invoked with two arguments.
2304 **
2305 ** ^The first argument to the busy handler is a copy of the void* pointer which
2306 ** is the third argument to sqlite3_busy_handler().  ^The second argument to
2307 ** the busy handler callback is the number of times that the busy handler has
2308 ** been invoked for this locking event.  ^If the
2309 ** busy callback returns 0, then no additional attempts are made to
2310 ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
2311 ** ^If the callback returns non-zero, then another attempt
2312 ** is made to open the database for reading and the cycle repeats.
2313 **
2314 ** The presence of a busy handler does not guarantee that it will be invoked
2315 ** when there is lock contention. ^If SQLite determines that invoking the busy
2316 ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
2317 ** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
2318 ** Consider a scenario where one process is holding a read lock that
2319 ** it is trying to promote to a reserved lock and
2320 ** a second process is holding a reserved lock that it is trying
2321 ** to promote to an exclusive lock.  The first process cannot proceed
2322 ** because it is blocked by the second and the second process cannot
2323 ** proceed because it is blocked by the first.  If both processes
2324 ** invoke the busy handlers, neither will make any progress.  Therefore,
2325 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
2326 ** will induce the first process to release its read lock and allow
2327 ** the second process to proceed.
2328 **
2329 ** ^The default busy callback is NULL.
2330 **
2331 ** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
2332 ** when SQLite is in the middle of a large transaction where all the
2333 ** changes will not fit into the in-memory cache.  SQLite will
2334 ** already hold a RESERVED lock on the database file, but it needs
2335 ** to promote this lock to EXCLUSIVE so that it can spill cache
2336 ** pages into the database file without harm to concurrent
2337 ** readers.  ^If it is unable to promote the lock, then the in-memory
2338 ** cache will be left in an inconsistent state and so the error
2339 ** code is promoted from the relatively benign [SQLITE_BUSY] to
2340 ** the more severe [SQLITE_IOERR_BLOCKED].  ^This error code promotion
2341 ** forces an automatic rollback of the changes.  See the
2342 ** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
2343 ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
2344 ** this is important.
2345 **
2346 ** ^(There can only be a single busy handler defined for each
2347 ** [database connection].  Setting a new busy handler clears any
2348 ** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]
2349 ** will also set or clear the busy handler.
2350 **
2351 ** The busy callback should not take any actions which modify the
2352 ** database connection that invoked the busy handler.  Any such actions
2353 ** result in undefined behavior.
2354 ** 
2355 ** A busy handler must not close the database connection
2356 ** or [prepared statement] that invoked the busy handler.
2357 */
2358 SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
2359
2360 /*
2361 ** CAPI3REF: Set A Busy Timeout
2362 **
2363 ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
2364 ** for a specified amount of time when a table is locked.  ^The handler
2365 ** will sleep multiple times until at least "ms" milliseconds of sleeping
2366 ** have accumulated.  ^After at least "ms" milliseconds of sleeping,
2367 ** the handler returns 0 which causes [sqlite3_step()] to return
2368 ** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
2369 **
2370 ** ^Calling this routine with an argument less than or equal to zero
2371 ** turns off all busy handlers.
2372 **
2373 ** ^(There can only be a single busy handler for a particular
2374 ** [database connection] any any given moment.  If another busy handler
2375 ** was defined  (using [sqlite3_busy_handler()]) prior to calling
2376 ** this routine, that other busy handler is cleared.)^
2377 */
2378 SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
2379
2380 /*
2381 ** CAPI3REF: Convenience Routines For Running Queries
2382 **
2383 ** This is a legacy interface that is preserved for backwards compatibility.
2384 ** Use of this interface is not recommended.
2385 **
2386 ** Definition: A <b>result table</b> is memory data structure created by the
2387 ** [sqlite3_get_table()] interface.  A result table records the
2388 ** complete query results from one or more queries.
2389 **
2390 ** The table conceptually has a number of rows and columns.  But
2391 ** these numbers are not part of the result table itself.  These
2392 ** numbers are obtained separately.  Let N be the number of rows
2393 ** and M be the number of columns.
2394 **
2395 ** A result table is an array of pointers to zero-terminated UTF-8 strings.
2396 ** There are (N+1)*M elements in the array.  The first M pointers point
2397 ** to zero-terminated strings that  contain the names of the columns.
2398 ** The remaining entries all point to query results.  NULL values result
2399 ** in NULL pointers.  All other values are in their UTF-8 zero-terminated
2400 ** string representation as returned by [sqlite3_column_text()].
2401 **
2402 ** A result table might consist of one or more memory allocations.
2403 ** It is not safe to pass a result table directly to [sqlite3_free()].
2404 ** A result table should be deallocated using [sqlite3_free_table()].
2405 **
2406 ** ^(As an example of the result table format, suppose a query result
2407 ** is as follows:
2408 **
2409 ** <blockquote><pre>
2410 **        Name        | Age
2411 **        -----------------------
2412 **        Alice       | 43
2413 **        Bob         | 28
2414 **        Cindy       | 21
2415 ** </pre></blockquote>
2416 **
2417 ** There are two column (M==2) and three rows (N==3).  Thus the
2418 ** result table has 8 entries.  Suppose the result table is stored
2419 ** in an array names azResult.  Then azResult holds this content:
2420 **
2421 ** <blockquote><pre>
2422 **        azResult&#91;0] = "Name";
2423 **        azResult&#91;1] = "Age";
2424 **        azResult&#91;2] = "Alice";
2425 **        azResult&#91;3] = "43";
2426 **        azResult&#91;4] = "Bob";
2427 **        azResult&#91;5] = "28";
2428 **        azResult&#91;6] = "Cindy";
2429 **        azResult&#91;7] = "21";
2430 ** </pre></blockquote>)^
2431 **
2432 ** ^The sqlite3_get_table() function evaluates one or more
2433 ** semicolon-separated SQL statements in the zero-terminated UTF-8
2434 ** string of its 2nd parameter and returns a result table to the
2435 ** pointer given in its 3rd parameter.
2436 **
2437 ** After the application has finished with the result from sqlite3_get_table(),
2438 ** it must pass the result table pointer to sqlite3_free_table() in order to
2439 ** release the memory that was malloced.  Because of the way the
2440 ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
2441 ** function must not try to call [sqlite3_free()] directly.  Only
2442 ** [sqlite3_free_table()] is able to release the memory properly and safely.
2443 **
2444 ** The sqlite3_get_table() interface is implemented as a wrapper around
2445 ** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
2446 ** to any internal data structures of SQLite.  It uses only the public
2447 ** interface defined here.  As a consequence, errors that occur in the
2448 ** wrapper layer outside of the internal [sqlite3_exec()] call are not
2449 ** reflected in subsequent calls to [sqlite3_errcode()] or
2450 ** [sqlite3_errmsg()].
2451 */
2452 SQLITE_API int sqlite3_get_table(
2453   sqlite3 *db,          /* An open database */
2454   const char *zSql,     /* SQL to be evaluated */
2455   char ***pazResult,    /* Results of the query */
2456   int *pnRow,           /* Number of result rows written here */
2457   int *pnColumn,        /* Number of result columns written here */
2458   char **pzErrmsg       /* Error msg written here */
2459 );
2460 SQLITE_API void sqlite3_free_table(char **result);
2461
2462 /*
2463 ** CAPI3REF: Formatted String Printing Functions
2464 **
2465 ** These routines are work-alikes of the "printf()" family of functions
2466 ** from the standard C library.
2467 **
2468 ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
2469 ** results into memory obtained from [sqlite3_malloc()].
2470 ** The strings returned by these two routines should be
2471 ** released by [sqlite3_free()].  ^Both routines return a
2472 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
2473 ** memory to hold the resulting string.
2474 **
2475 ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
2476 ** the standard C library.  The result is written into the
2477 ** buffer supplied as the second parameter whose size is given by
2478 ** the first parameter. Note that the order of the
2479 ** first two parameters is reversed from snprintf().)^  This is an
2480 ** historical accident that cannot be fixed without breaking
2481 ** backwards compatibility.  ^(Note also that sqlite3_snprintf()
2482 ** returns a pointer to its buffer instead of the number of
2483 ** characters actually written into the buffer.)^  We admit that
2484 ** the number of characters written would be a more useful return
2485 ** value but we cannot change the implementation of sqlite3_snprintf()
2486 ** now without breaking compatibility.
2487 **
2488 ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
2489 ** guarantees that the buffer is always zero-terminated.  ^The first
2490 ** parameter "n" is the total size of the buffer, including space for
2491 ** the zero terminator.  So the longest string that can be completely
2492 ** written will be n-1 characters.
2493 **
2494 ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
2495 **
2496 ** These routines all implement some additional formatting
2497 ** options that are useful for constructing SQL statements.
2498 ** All of the usual printf() formatting options apply.  In addition, there
2499 ** is are "%q", "%Q", and "%z" options.
2500 **
2501 ** ^(The %q option works like %s in that it substitutes a null-terminated
2502 ** string from the argument list.  But %q also doubles every '\'' character.
2503 ** %q is designed for use inside a string literal.)^  By doubling each '\''
2504 ** character it escapes that character and allows it to be inserted into
2505 ** the string.
2506 **
2507 ** For example, assume the string variable zText contains text as follows:
2508 **
2509 ** <blockquote><pre>
2510 **  char *zText = "It's a happy day!";
2511 ** </pre></blockquote>
2512 **
2513 ** One can use this text in an SQL statement as follows:
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 ** Because the %q format string is used, the '\'' character in zText
2522 ** is escaped and the SQL generated is as follows:
2523 **
2524 ** <blockquote><pre>
2525 **  INSERT INTO table1 VALUES('It''s a happy day!')
2526 ** </pre></blockquote>
2527 **
2528 ** This is correct.  Had we used %s instead of %q, the generated SQL
2529 ** would have looked like this:
2530 **
2531 ** <blockquote><pre>
2532 **  INSERT INTO table1 VALUES('It's a happy day!');
2533 ** </pre></blockquote>
2534 **
2535 ** This second example is an SQL syntax error.  As a general rule you should
2536 ** always use %q instead of %s when inserting text into a string literal.
2537 **
2538 ** ^(The %Q option works like %q except it also adds single quotes around
2539 ** the outside of the total string.  Additionally, if the parameter in the
2540 ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
2541 ** single quotes).)^  So, for example, one could say:
2542 **
2543 ** <blockquote><pre>
2544 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
2545 **  sqlite3_exec(db, zSQL, 0, 0, 0);
2546 **  sqlite3_free(zSQL);
2547 ** </pre></blockquote>
2548 **
2549 ** The code above will render a correct SQL statement in the zSQL
2550 ** variable even if the zText variable is a NULL pointer.
2551 **
2552 ** ^(The "%z" formatting option works like "%s" but with the
2553 ** addition that after the string has been read and copied into
2554 ** the result, [sqlite3_free()] is called on the input string.)^
2555 */
2556 SQLITE_API char *sqlite3_mprintf(const char*,...);
2557 SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
2558 SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
2559 SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
2560
2561 /*
2562 ** CAPI3REF: Memory Allocation Subsystem
2563 **
2564 ** The SQLite core uses these three routines for all of its own
2565 ** internal memory allocation needs. "Core" in the previous sentence
2566 ** does not include operating-system specific VFS implementation.  The
2567 ** Windows VFS uses native malloc() and free() for some operations.
2568 **
2569 ** ^The sqlite3_malloc() routine returns a pointer to a block
2570 ** of memory at least N bytes in length, where N is the parameter.
2571 ** ^If sqlite3_malloc() is unable to obtain sufficient free
2572 ** memory, it returns a NULL pointer.  ^If the parameter N to
2573 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
2574 ** a NULL pointer.
2575 **
2576 ** ^Calling sqlite3_free() with a pointer previously returned
2577 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
2578 ** that it might be reused.  ^The sqlite3_free() routine is
2579 ** a no-op if is called with a NULL pointer.  Passing a NULL pointer
2580 ** to sqlite3_free() is harmless.  After being freed, memory
2581 ** should neither be read nor written.  Even reading previously freed
2582 ** memory might result in a segmentation fault or other severe error.
2583 ** Memory corruption, a segmentation fault, or other severe error
2584 ** might result if sqlite3_free() is called with a non-NULL pointer that
2585 ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
2586 **
2587 ** ^(The sqlite3_realloc() interface attempts to resize a
2588 ** prior memory allocation to be at least N bytes, where N is the
2589 ** second parameter.  The memory allocation to be resized is the first
2590 ** parameter.)^ ^ If the first parameter to sqlite3_realloc()
2591 ** is a NULL pointer then its behavior is identical to calling
2592 ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
2593 ** ^If the second parameter to sqlite3_realloc() is zero or
2594 ** negative then the behavior is exactly the same as calling
2595 ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
2596 ** ^sqlite3_realloc() returns a pointer to a memory allocation
2597 ** of at least N bytes in size or NULL if sufficient memory is unavailable.
2598 ** ^If M is the size of the prior allocation, then min(N,M) bytes
2599 ** of the prior allocation are copied into the beginning of buffer returned
2600 ** by sqlite3_realloc() and the prior allocation is freed.
2601 ** ^If sqlite3_realloc() returns NULL, then the prior allocation
2602 ** is not freed.
2603 **
2604 ** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
2605 ** is always aligned to at least an 8 byte boundary, or to a
2606 ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
2607 ** option is used.
2608 **
2609 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2610 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
2611 ** implementation of these routines to be omitted.  That capability
2612 ** is no longer provided.  Only built-in memory allocators can be used.
2613 **
2614 ** The Windows OS interface layer calls
2615 ** the system malloc() and free() directly when converting
2616 ** filenames between the UTF-8 encoding used by SQLite
2617 ** and whatever filename encoding is used by the particular Windows
2618 ** installation.  Memory allocation errors are detected, but
2619 ** they are reported back as [SQLITE_CANTOPEN] or
2620 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
2621 **
2622 ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
2623 ** must be either NULL or else pointers obtained from a prior
2624 ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
2625 ** not yet been released.
2626 **
2627 ** The application must not read or write any part of
2628 ** a block of memory after it has been released using
2629 ** [sqlite3_free()] or [sqlite3_realloc()].
2630 */
2631 SQLITE_API void *sqlite3_malloc(int);
2632 SQLITE_API void *sqlite3_realloc(void*, int);
2633 SQLITE_API void sqlite3_free(void*);
2634
2635 /*
2636 ** CAPI3REF: Memory Allocator Statistics
2637 **
2638 ** SQLite provides these two interfaces for reporting on the status
2639 ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
2640 ** routines, which form the built-in memory allocation subsystem.
2641 **
2642 ** ^The [sqlite3_memory_used()] routine returns the number of bytes
2643 ** of memory currently outstanding (malloced but not freed).
2644 ** ^The [sqlite3_memory_highwater()] routine returns the maximum
2645 ** value of [sqlite3_memory_used()] since the high-water mark
2646 ** was last reset.  ^The values returned by [sqlite3_memory_used()] and
2647 ** [sqlite3_memory_highwater()] include any overhead
2648 ** added by SQLite in its implementation of [sqlite3_malloc()],
2649 ** but not overhead added by the any underlying system library
2650 ** routines that [sqlite3_malloc()] may call.
2651 **
2652 ** ^The memory high-water mark is reset to the current value of
2653 ** [sqlite3_memory_used()] if and only if the parameter to
2654 ** [sqlite3_memory_highwater()] is true.  ^The value returned
2655 ** by [sqlite3_memory_highwater(1)] is the high-water mark
2656 ** prior to the reset.
2657 */
2658 SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
2659 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
2660
2661 /*
2662 ** CAPI3REF: Pseudo-Random Number Generator
2663 **
2664 ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2665 ** select random [ROWID | ROWIDs] when inserting new records into a table that
2666 ** already uses the largest possible [ROWID].  The PRNG is also used for
2667 ** the build-in random() and randomblob() SQL functions.  This interface allows
2668 ** applications to access the same PRNG for other purposes.
2669 **
2670 ** ^A call to this routine stores N bytes of randomness into buffer P.
2671 **
2672 ** ^The first time this routine is invoked (either internally or by
2673 ** the application) the PRNG is seeded using randomness obtained
2674 ** from the xRandomness method of the default [sqlite3_vfs] object.
2675 ** ^On all subsequent invocations, the pseudo-randomness is generated
2676 ** internally and without recourse to the [sqlite3_vfs] xRandomness
2677 ** method.
2678 */
2679 SQLITE_API void sqlite3_randomness(int N, void *P);
2680
2681 /*
2682 ** CAPI3REF: Compile-Time Authorization Callbacks
2683 **
2684 ** ^This routine registers an authorizer callback with a particular
2685 ** [database connection], supplied in the first argument.
2686 ** ^The authorizer callback is invoked as SQL statements are being compiled
2687 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
2688 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  ^At various
2689 ** points during the compilation process, as logic is being created
2690 ** to perform various actions, the authorizer callback is invoked to
2691 ** see if those actions are allowed.  ^The authorizer callback should
2692 ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
2693 ** specific action but allow the SQL statement to continue to be
2694 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
2695 ** rejected with an error.  ^If the authorizer callback returns
2696 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
2697 ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
2698 ** the authorizer will fail with an error message.
2699 **
2700 ** When the callback returns [SQLITE_OK], that means the operation
2701 ** requested is ok.  ^When the callback returns [SQLITE_DENY], the
2702 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
2703 ** authorizer will fail with an error message explaining that
2704 ** access is denied. 
2705 **
2706 ** ^The first parameter to the authorizer callback is a copy of the third
2707 ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
2708 ** to the callback is an integer [SQLITE_COPY | action code] that specifies
2709 ** the particular action to be authorized. ^The third through sixth parameters
2710 ** to the callback are zero-terminated strings that contain additional
2711 ** details about the action to be authorized.
2712 **
2713 ** ^If the action code is [SQLITE_READ]
2714 ** and the callback returns [SQLITE_IGNORE] then the
2715 ** [prepared statement] statement is constructed to substitute
2716 ** a NULL value in place of the table column that would have
2717 ** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
2718 ** return can be used to deny an untrusted user access to individual
2719 ** columns of a table.
2720 ** ^If the action code is [SQLITE_DELETE] and the callback returns
2721 ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
2722 ** [truncate optimization] is disabled and all rows are deleted individually.
2723 **
2724 ** An authorizer is used when [sqlite3_prepare | preparing]
2725 ** SQL statements from an untrusted source, to ensure that the SQL statements
2726 ** do not try to access data they are not allowed to see, or that they do not
2727 ** try to execute malicious statements that damage the database.  For
2728 ** example, an application may allow a user to enter arbitrary
2729 ** SQL queries for evaluation by a database.  But the application does
2730 ** not want the user to be able to make arbitrary changes to the
2731 ** database.  An authorizer could then be put in place while the
2732 ** user-entered SQL is being [sqlite3_prepare | prepared] that
2733 ** disallows everything except [SELECT] statements.
2734 **
2735 ** Applications that need to process SQL from untrusted sources
2736 ** might also consider lowering resource limits using [sqlite3_limit()]
2737 ** and limiting database size using the [max_page_count] [PRAGMA]
2738 ** in addition to using an authorizer.
2739 **
2740 ** ^(Only a single authorizer can be in place on a database connection
2741 ** at a time.  Each call to sqlite3_set_authorizer overrides the
2742 ** previous call.)^  ^Disable the authorizer by installing a NULL callback.
2743 ** The authorizer is disabled by default.
2744 **
2745 ** The authorizer callback must not do anything that will modify
2746 ** the database connection that invoked the authorizer callback.
2747 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2748 ** database connections for the meaning of "modify" in this paragraph.
2749 **
2750 ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
2751 ** statement might be re-prepared during [sqlite3_step()] due to a 
2752 ** schema change.  Hence, the application should ensure that the
2753 ** correct authorizer callback remains in place during the [sqlite3_step()].
2754 **
2755 ** ^Note that the authorizer callback is invoked only during
2756 ** [sqlite3_prepare()] or its variants.  Authorization is not
2757 ** performed during statement evaluation in [sqlite3_step()], unless
2758 ** as stated in the previous paragraph, sqlite3_step() invokes
2759 ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
2760 */
2761 SQLITE_API int sqlite3_set_authorizer(
2762   sqlite3*,
2763   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
2764   void *pUserData
2765 );
2766
2767 /*
2768 ** CAPI3REF: Authorizer Return Codes
2769 **
2770 ** The [sqlite3_set_authorizer | authorizer callback function] must
2771 ** return either [SQLITE_OK] or one of these two constants in order
2772 ** to signal SQLite whether or not the action is permitted.  See the
2773 ** [sqlite3_set_authorizer | authorizer documentation] for additional
2774 ** information.
2775 **
2776 ** Note that SQLITE_IGNORE is also used as a [SQLITE_ROLLBACK | return code]
2777 ** from the [sqlite3_vtab_on_conflict()] interface.
2778 */
2779 #define SQLITE_DENY   1   /* Abort the SQL statement with an error */
2780 #define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
2781
2782 /*
2783 ** CAPI3REF: Authorizer Action Codes
2784 **
2785 ** The [sqlite3_set_authorizer()] interface registers a callback function
2786 ** that is invoked to authorize certain SQL statement actions.  The
2787 ** second parameter to the callback is an integer code that specifies
2788 ** what action is being authorized.  These are the integer action codes that
2789 ** the authorizer callback may be passed.
2790 **
2791 ** These action code values signify what kind of operation is to be
2792 ** authorized.  The 3rd and 4th parameters to the authorization
2793 ** callback function will be parameters or NULL depending on which of these
2794 ** codes is used as the second parameter.  ^(The 5th parameter to the
2795 ** authorizer callback is the name of the database ("main", "temp",
2796 ** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback
2797 ** is the name of the inner-most trigger or view that is responsible for
2798 ** the access attempt or NULL if this access attempt is directly from
2799 ** top-level SQL code.
2800 */
2801 /******************************************* 3rd ************ 4th ***********/
2802 #define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
2803 #define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
2804 #define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
2805 #define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
2806 #define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
2807 #define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
2808 #define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
2809 #define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
2810 #define SQLITE_DELETE                9   /* Table Name      NULL            */
2811 #define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
2812 #define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
2813 #define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
2814 #define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
2815 #define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
2816 #define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
2817 #define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
2818 #define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
2819 #define SQLITE_INSERT               18   /* Table Name      NULL            */
2820 #define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
2821 #define SQLITE_READ                 20   /* Table Name      Column Name     */
2822 #define SQLITE_SELECT               21   /* NULL            NULL            */
2823 #define SQLITE_TRANSACTION          22   /* Operation       NULL            */
2824 #define SQLITE_UPDATE               23   /* Table Name      Column Name     */
2825 #define SQLITE_ATTACH               24   /* Filename        NULL            */
2826 #define SQLITE_DETACH               25   /* Database Name   NULL            */
2827 #define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
2828 #define SQLITE_REINDEX              27   /* Index Name      NULL            */
2829 #define SQLITE_ANALYZE              28   /* Table Name      NULL            */
2830 #define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
2831 #define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
2832 #define SQLITE_FUNCTION             31   /* NULL            Function Name   */
2833 #define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */
2834 #define SQLITE_COPY                  0   /* No longer used */
2835
2836 /*
2837 ** CAPI3REF: Tracing And Profiling Functions
2838 **
2839 ** These routines register callback functions that can be used for
2840 ** tracing and profiling the execution of SQL statements.
2841 **
2842 ** ^The callback function registered by sqlite3_trace() is invoked at
2843 ** various times when an SQL statement is being run by [sqlite3_step()].
2844 ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
2845 ** SQL statement text as the statement first begins executing.
2846 ** ^(Additional sqlite3_trace() callbacks might occur
2847 ** as each triggered subprogram is entered.  The callbacks for triggers
2848 ** contain a UTF-8 SQL comment that identifies the trigger.)^
2849 **
2850 ** ^The callback function registered by sqlite3_profile() is invoked
2851 ** as each SQL statement finishes.  ^The profile callback contains
2852 ** the original statement text and an estimate of wall-clock time
2853 ** of how long that statement took to run.  ^The profile callback
2854 ** time is in units of nanoseconds, however the current implementation
2855 ** is only capable of millisecond resolution so the six least significant
2856 ** digits in the time are meaningless.  Future versions of SQLite
2857 ** might provide greater resolution on the profiler callback.  The
2858 ** sqlite3_profile() function is considered experimental and is
2859 ** subject to change in future versions of SQLite.
2860 */
2861 SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
2862 SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
2863    void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
2864
2865 /*
2866 ** CAPI3REF: Query Progress Callbacks
2867 **
2868 ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
2869 ** function X to be invoked periodically during long running calls to
2870 ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
2871 ** database connection D.  An example use for this
2872 ** interface is to keep a GUI updated during a large query.
2873 **
2874 ** ^The parameter P is passed through as the only parameter to the 
2875 ** callback function X.  ^The parameter N is the number of 
2876 ** [virtual machine instructions] that are evaluated between successive
2877 ** invocations of the callback X.
2878 **
2879 ** ^Only a single progress handler may be defined at one time per
2880 ** [database connection]; setting a new progress handler cancels the
2881 ** old one.  ^Setting parameter X to NULL disables the progress handler.
2882 ** ^The progress handler is also disabled by setting N to a value less
2883 ** than 1.
2884 **
2885 ** ^If the progress callback returns non-zero, the operation is
2886 ** interrupted.  This feature can be used to implement a
2887 ** "Cancel" button on a GUI progress dialog box.
2888 **
2889 ** The progress handler callback must not do anything that will modify
2890 ** the database connection that invoked the progress handler.
2891 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2892 ** database connections for the meaning of "modify" in this paragraph.
2893 **
2894 */
2895 SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
2896
2897 /*
2898 ** CAPI3REF: Opening A New Database Connection
2899 **
2900 ** ^These routines open an SQLite database file as specified by the 
2901 ** filename argument. ^The filename argument is interpreted as UTF-8 for
2902 ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
2903 ** order for sqlite3_open16(). ^(A [database connection] handle is usually
2904 ** returned in *ppDb, even if an error occurs.  The only exception is that
2905 ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
2906 ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
2907 ** object.)^ ^(If the database is opened (and/or created) successfully, then
2908 ** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The
2909 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
2910 ** an English language description of the error following a failure of any
2911 ** of the sqlite3_open() routines.
2912 **
2913 ** ^The default encoding for the database will be UTF-8 if
2914 ** sqlite3_open() or sqlite3_open_v2() is called and
2915 ** UTF-16 in the native byte order if sqlite3_open16() is used.
2916 **
2917 ** Whether or not an error occurs when it is opened, resources
2918 ** associated with the [database connection] handle should be released by
2919 ** passing it to [sqlite3_close()] when it is no longer required.
2920 **
2921 ** The sqlite3_open_v2() interface works like sqlite3_open()
2922 ** except that it accepts two additional parameters for additional control
2923 ** over the new database connection.  ^(The flags parameter to
2924 ** sqlite3_open_v2() can take one of
2925 ** the following three values, optionally combined with the 
2926 ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
2927 ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
2928 **
2929 ** <dl>
2930 ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
2931 ** <dd>The database is opened in read-only mode.  If the database does not
2932 ** already exist, an error is returned.</dd>)^
2933 **
2934 ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
2935 ** <dd>The database is opened for reading and writing if possible, or reading
2936 ** only if the file is write protected by the operating system.  In either
2937 ** case the database must already exist, otherwise an error is returned.</dd>)^
2938 **
2939 ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
2940 ** <dd>The database is opened for reading and writing, and is created if
2941 ** it does not already exist. This is the behavior that is always used for
2942 ** sqlite3_open() and sqlite3_open16().</dd>)^
2943 ** </dl>
2944 **
2945 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
2946 ** combinations shown above optionally combined with other
2947 ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
2948 ** then the behavior is undefined.
2949 **
2950 ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
2951 ** opens in the multi-thread [threading mode] as long as the single-thread
2952 ** mode has not been set at compile-time or start-time.  ^If the
2953 ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
2954 ** in the serialized [threading mode] unless single-thread was
2955 ** previously selected at compile-time or start-time.
2956 ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
2957 ** eligible to use [shared cache mode], regardless of whether or not shared
2958 ** cache is enabled using [sqlite3_enable_shared_cache()].  ^The
2959 ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
2960 ** participate in [shared cache mode] even if it is enabled.
2961 **
2962 ** ^The fourth parameter to sqlite3_open_v2() is the name of the
2963 ** [sqlite3_vfs] object that defines the operating system interface that
2964 ** the new database connection should use.  ^If the fourth parameter is
2965 ** a NULL pointer then the default [sqlite3_vfs] object is used.
2966 **
2967 ** ^If the filename is ":memory:", then a private, temporary in-memory database
2968 ** is created for the connection.  ^This in-memory database will vanish when
2969 ** the database connection is closed.  Future versions of SQLite might
2970 ** make use of additional special filenames that begin with the ":" character.
2971 ** It is recommended that when a database filename actually does begin with
2972 ** a ":" character you should prefix the filename with a pathname such as
2973 ** "./" to avoid ambiguity.
2974 **
2975 ** ^If the filename is an empty string, then a private, temporary
2976 ** on-disk database will be created.  ^This private database will be
2977 ** automatically deleted as soon as the database connection is closed.
2978 **
2979 ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
2980 **
2981 ** ^If [URI filename] interpretation is enabled, and the filename argument
2982 ** begins with "file:", then the filename is interpreted as a URI. ^URI
2983 ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
2984 ** set in the fourth argument to sqlite3_open_v2(), or if it has
2985 ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
2986 ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
2987 ** As of SQLite version 3.7.7, URI filename interpretation is turned off
2988 ** by default, but future releases of SQLite might enable URI filename
2989 ** interpretation by default.  See "[URI filenames]" for additional
2990 ** information.
2991 **
2992 ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
2993 ** authority, then it must be either an empty string or the string 
2994 ** "localhost". ^If the authority is not an empty string or "localhost", an 
2995 ** error is returned to the caller. ^The fragment component of a URI, if 
2996 ** present, is ignored.
2997 **
2998 ** ^SQLite uses the path component of the URI as the name of the disk file
2999 ** which contains the database. ^If the path begins with a '/' character, 
3000 ** then it is interpreted as an absolute path. ^If the path does not begin 
3001 ** with a '/' (meaning that the authority section is omitted from the URI)
3002 ** then the path is interpreted as a relative path. 
3003 ** ^On windows, the first component of an absolute path 
3004 ** is a drive specification (e.g. "C:").
3005 **
3006 ** [[core URI query parameters]]
3007 ** The query component of a URI may contain parameters that are interpreted
3008 ** either by SQLite itself, or by a [VFS | custom VFS implementation].
3009 ** SQLite interprets the following three query parameters:
3010 **
3011 ** <ul>
3012 **   <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
3013 **     a VFS object that provides the operating system interface that should
3014 **     be used to access the database file on disk. ^If this option is set to
3015 **     an empty string the default VFS object is used. ^Specifying an unknown
3016 **     VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
3017 **     present, then the VFS specified by the option takes precedence over
3018 **     the value passed as the fourth parameter to sqlite3_open_v2().
3019 **
3020 **   <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw" or
3021 **     "rwc". Attempting to set it to any other value is an error)^. 
3022 **     ^If "ro" is specified, then the database is opened for read-only 
3023 **     access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the 
3024 **     third argument to sqlite3_prepare_v2(). ^If the mode option is set to 
3025 **     "rw", then the database is opened for read-write (but not create) 
3026 **     access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had 
3027 **     been set. ^Value "rwc" is equivalent to setting both 
3028 **     SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If sqlite3_open_v2() is 
3029 **     used, it is an error to specify a value for the mode parameter that is 
3030 **     less restrictive than that specified by the flags passed as the third 
3031 **     parameter.
3032 **
3033 **   <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
3034 **     "private". ^Setting it to "shared" is equivalent to setting the
3035 **     SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
3036 **     sqlite3_open_v2(). ^Setting the cache parameter to "private" is 
3037 **     equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
3038 **     ^If sqlite3_open_v2() is used and the "cache" parameter is present in
3039 **     a URI filename, its value overrides any behaviour requested by setting
3040 **     SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
3041 ** </ul>
3042 **
3043 ** ^Specifying an unknown parameter in the query component of a URI is not an
3044 ** error.  Future versions of SQLite might understand additional query
3045 ** parameters.  See "[query parameters with special meaning to SQLite]" for
3046 ** additional information.
3047 **
3048 ** [[URI filename examples]] <h3>URI filename examples</h3>
3049 **
3050 ** <table border="1" align=center cellpadding=5>
3051 ** <tr><th> URI filenames <th> Results
3052 ** <tr><td> file:data.db <td> 
3053 **          Open the file "data.db" in the current directory.
3054 ** <tr><td> file:/home/fred/data.db<br>
3055 **          file:///home/fred/data.db <br> 
3056 **          file://localhost/home/fred/data.db <br> <td> 
3057 **          Open the database file "/home/fred/data.db".
3058 ** <tr><td> file://darkstar/home/fred/data.db <td> 
3059 **          An error. "darkstar" is not a recognized authority.
3060 ** <tr><td style="white-space:nowrap"> 
3061 **          file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
3062 **     <td> Windows only: Open the file "data.db" on fred's desktop on drive
3063 **          C:. Note that the %20 escaping in this example is not strictly 
3064 **          necessary - space characters can be used literally
3065 **          in URI filenames.
3066 ** <tr><td> file:data.db?mode=ro&cache=private <td> 
3067 **          Open file "data.db" in the current directory for read-only access.
3068 **          Regardless of whether or not shared-cache mode is enabled by
3069 **          default, use a private cache.
3070 ** <tr><td> file:/home/fred/data.db?vfs=unix-nolock <td>
3071 **          Open file "/home/fred/data.db". Use the special VFS "unix-nolock".
3072 ** <tr><td> file:data.db?mode=readonly <td> 
3073 **          An error. "readonly" is not a valid option for the "mode" parameter.
3074 ** </table>
3075 **
3076 ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
3077 ** query components of a URI. A hexadecimal escape sequence consists of a
3078 ** percent sign - "%" - followed by exactly two hexadecimal digits 
3079 ** specifying an octet value. ^Before the path or query components of a
3080 ** URI filename are interpreted, they are encoded using UTF-8 and all 
3081 ** hexadecimal escape sequences replaced by a single byte containing the
3082 ** corresponding octet. If this process generates an invalid UTF-8 encoding,
3083 ** the results are undefined.
3084 **
3085 ** <b>Note to Windows users:</b>  The encoding used for the filename argument
3086 ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
3087 ** codepage is currently defined.  Filenames containing international
3088 ** characters must be converted to UTF-8 prior to passing them into
3089 ** sqlite3_open() or sqlite3_open_v2().
3090 */
3091 SQLITE_API int sqlite3_open(
3092   const char *filename,   /* Database filename (UTF-8) */
3093   sqlite3 **ppDb          /* OUT: SQLite db handle */
3094 );
3095 SQLITE_API int sqlite3_open16(
3096   const void *filename,   /* Database filename (UTF-16) */
3097   sqlite3 **ppDb          /* OUT: SQLite db handle */
3098 );
3099 SQLITE_API int sqlite3_open_v2(
3100   const char *filename,   /* Database filename (UTF-8) */
3101   sqlite3 **ppDb,         /* OUT: SQLite db handle */
3102   int flags,              /* Flags */
3103   const char *zVfs        /* Name of VFS module to use */
3104 );
3105
3106 /*
3107 ** CAPI3REF: Obtain Values For URI Parameters
3108 **
3109 ** This is a utility routine, useful to VFS implementations, that checks
3110 ** to see if a database file was a URI that contained a specific query 
3111 ** parameter, and if so obtains the value of the query parameter.
3112 **
3113 ** The zFilename argument is the filename pointer passed into the xOpen()
3114 ** method of a VFS implementation.  The zParam argument is the name of the
3115 ** query parameter we seek.  This routine returns the value of the zParam
3116 ** parameter if it exists.  If the parameter does not exist, this routine
3117 ** returns a NULL pointer.
3118 **
3119 ** If the zFilename argument to this function is not a pointer that SQLite
3120 ** passed into the xOpen VFS method, then the behavior of this routine
3121 ** is undefined and probably undesirable.
3122 */
3123 SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
3124
3125
3126 /*
3127 ** CAPI3REF: Error Codes And Messages
3128 **
3129 ** ^The sqlite3_errcode() interface returns the numeric [result code] or
3130 ** [extended result code] for the most recent failed sqlite3_* API call
3131 ** associated with a [database connection]. If a prior API call failed
3132 ** but the most recent API call succeeded, the return value from
3133 ** sqlite3_errcode() is undefined.  ^The sqlite3_extended_errcode()
3134 ** interface is the same except that it always returns the 
3135 ** [extended result code] even when extended result codes are
3136 ** disabled.
3137 **
3138 ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
3139 ** text that describes the error, as either UTF-8 or UTF-16 respectively.
3140 ** ^(Memory to hold the error message string is managed internally.
3141 ** The application does not need to worry about freeing the result.
3142 ** However, the error string might be overwritten or deallocated by
3143 ** subsequent calls to other SQLite interface functions.)^
3144 **
3145 ** When the serialized [threading mode] is in use, it might be the
3146 ** case that a second error occurs on a separate thread in between
3147 ** the time of the first error and the call to these interfaces.
3148 ** When that happens, the second error will be reported since these
3149 ** interfaces always report the most recent result.  To avoid
3150 ** this, each thread can obtain exclusive use of the [database connection] D
3151 ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
3152 ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
3153 ** all calls to the interfaces listed here are completed.
3154 **
3155 ** If an interface fails with SQLITE_MISUSE, that means the interface
3156 ** was invoked incorrectly by the application.  In that case, the
3157 ** error code and message may or may not be set.
3158 */
3159 SQLITE_API int sqlite3_errcode(sqlite3 *db);
3160 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
3161 SQLITE_API const char *sqlite3_errmsg(sqlite3*);
3162 SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
3163
3164 /*
3165 ** CAPI3REF: SQL Statement Object
3166 ** KEYWORDS: {prepared statement} {prepared statements}
3167 **
3168 ** An instance of this object represents a single SQL statement.
3169 ** This object is variously known as a "prepared statement" or a
3170 ** "compiled SQL statement" or simply as a "statement".
3171 **
3172 ** The life of a statement object goes something like this:
3173 **
3174 ** <ol>
3175 ** <li> Create the object using [sqlite3_prepare_v2()] or a related
3176 **      function.
3177 ** <li> Bind values to [host parameters] using the sqlite3_bind_*()
3178 **      interfaces.
3179 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
3180 ** <li> Reset the statement using [sqlite3_reset()] then go back
3181 **      to step 2.  Do this zero or more times.
3182 ** <li> Destroy the object using [sqlite3_finalize()].
3183 ** </ol>
3184 **
3185 ** Refer to documentation on individual methods above for additional
3186 ** information.
3187 */
3188 typedef struct sqlite3_stmt sqlite3_stmt;
3189
3190 /*
3191 ** CAPI3REF: Run-time Limits
3192 **
3193 ** ^(This interface allows the size of various constructs to be limited
3194 ** on a connection by connection basis.  The first parameter is the
3195 ** [database connection] whose limit is to be set or queried.  The
3196 ** second parameter is one of the [limit categories] that define a
3197 ** class of constructs to be size limited.  The third parameter is the
3198 ** new limit for that construct.)^
3199 **
3200 ** ^If the new limit is a negative number, the limit is unchanged.
3201 ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a 
3202 ** [limits | hard upper bound]
3203 ** set at compile-time by a C preprocessor macro called
3204 ** [limits | SQLITE_MAX_<i>NAME</i>].
3205 ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
3206 ** ^Attempts to increase a limit above its hard upper bound are
3207 ** silently truncated to the hard upper bound.
3208 **
3209 ** ^Regardless of whether or not the limit was changed, the 
3210 ** [sqlite3_limit()] interface returns the prior value of the limit.
3211 ** ^Hence, to find the current value of a limit without changing it,
3212 ** simply invoke this interface with the third parameter set to -1.
3213 **
3214 ** Run-time limits are intended for use in applications that manage
3215 ** both their own internal database and also databases that are controlled
3216 ** by untrusted external sources.  An example application might be a
3217 ** web browser that has its own databases for storing history and
3218 ** separate databases controlled by JavaScript applications downloaded
3219 ** off the Internet.  The internal databases can be given the
3220 ** large, default limits.  Databases managed by external sources can
3221 ** be given much smaller limits designed to prevent a denial of service
3222 ** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
3223 ** interface to further control untrusted SQL.  The size of the database
3224 ** created by an untrusted script can be contained using the
3225 ** [max_page_count] [PRAGMA].
3226 **
3227 ** New run-time limit categories may be added in future releases.
3228 */
3229 SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
3230
3231 /*
3232 ** CAPI3REF: Run-Time Limit Categories
3233 ** KEYWORDS: {limit category} {*limit categories}
3234 **
3235 ** These constants define various performance limits
3236 ** that can be lowered at run-time using [sqlite3_limit()].
3237 ** The synopsis of the meanings of the various limits is shown below.
3238 ** Additional information is available at [limits | Limits in SQLite].
3239 **
3240 ** <dl>
3241 ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
3242 ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
3243 **
3244 ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
3245 ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
3246 **
3247 ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
3248 ** <dd>The maximum number of columns in a table definition or in the
3249 ** result set of a [SELECT] or the maximum number of columns in an index
3250 ** or in an ORDER BY or GROUP BY clause.</dd>)^
3251 **
3252 ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
3253 ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
3254 **
3255 ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
3256 ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
3257 **
3258 ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
3259 ** <dd>The maximum number of instructions in a virtual machine program
3260 ** used to implement an SQL statement.  This limit is not currently
3261 ** enforced, though that might be added in some future release of
3262 ** SQLite.</dd>)^
3263 **
3264 ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
3265 ** <dd>The maximum number of arguments on a function.</dd>)^
3266 **
3267 ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
3268 ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
3269 **
3270 ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
3271 ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
3272 ** <dd>The maximum length of the pattern argument to the [LIKE] or
3273 ** [GLOB] operators.</dd>)^
3274 **
3275 ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
3276 ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
3277 ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
3278 **
3279 ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
3280 ** <dd>The maximum depth of recursion for triggers.</dd>)^
3281 ** </dl>
3282 */
3283 #define SQLITE_LIMIT_LENGTH                    0
3284 #define SQLITE_LIMIT_SQL_LENGTH                1
3285 #define SQLITE_LIMIT_COLUMN                    2
3286 #define SQLITE_LIMIT_EXPR_DEPTH                3
3287 #define SQLITE_LIMIT_COMPOUND_SELECT           4
3288 #define SQLITE_LIMIT_VDBE_OP                   5
3289 #define SQLITE_LIMIT_FUNCTION_ARG              6
3290 #define SQLITE_LIMIT_ATTACHED                  7
3291 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
3292 #define SQLITE_LIMIT_VARIABLE_NUMBER           9
3293 #define SQLITE_LIMIT_TRIGGER_DEPTH            10
3294
3295 /*
3296 ** CAPI3REF: Compiling An SQL Statement
3297 ** KEYWORDS: {SQL statement compiler}
3298 **
3299 ** To execute an SQL query, it must first be compiled into a byte-code
3300 ** program using one of these routines.
3301 **
3302 ** The first argument, "db", is a [database connection] obtained from a
3303 ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
3304 ** [sqlite3_open16()].  The database connection must not have been closed.
3305 **
3306 ** The second argument, "zSql", is the statement to be compiled, encoded
3307 ** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
3308 ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
3309 ** use UTF-16.
3310 **
3311 ** ^If the nByte argument is less than zero, then zSql is read up to the
3312 ** first zero terminator. ^If nByte is non-negative, then it is the maximum
3313 ** number of  bytes read from zSql.  ^When nByte is non-negative, the
3314 ** zSql string ends at either the first '\000' or '\u0000' character or
3315 ** the nByte-th byte, whichever comes first. If the caller knows
3316 ** that the supplied string is nul-terminated, then there is a small
3317 ** performance advantage to be gained by passing an nByte parameter that
3318 ** is equal to the number of bytes in the input string <i>including</i>
3319 ** the nul-terminator bytes.
3320 **
3321 ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
3322 ** past the end of the first SQL statement in zSql.  These routines only
3323 ** compile the first statement in zSql, so *pzTail is left pointing to
3324 ** what remains uncompiled.
3325 **
3326 ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
3327 ** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set
3328 ** to NULL.  ^If the input text contains no SQL (if the input is an empty
3329 ** string or a comment) then *ppStmt is set to NULL.
3330 ** The calling procedure is responsible for deleting the compiled
3331 ** SQL statement using [sqlite3_finalize()] after it has finished with it.
3332 ** ppStmt may not be NULL.
3333 **
3334 ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
3335 ** otherwise an [error code] is returned.
3336 **
3337 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
3338 ** recommended for all new programs. The two older interfaces are retained
3339 ** for backwards compatibility, but their use is discouraged.
3340 ** ^In the "v2" interfaces, the prepared statement
3341 ** that is returned (the [sqlite3_stmt] object) contains a copy of the
3342 ** original SQL text. This causes the [sqlite3_step()] interface to
3343 ** behave differently in three ways:
3344 **
3345 ** <ol>
3346 ** <li>
3347 ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
3348 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
3349 ** statement and try to run it again.
3350 ** </li>
3351 **
3352 ** <li>
3353 ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
3354 ** [error codes] or [extended error codes].  ^The legacy behavior was that
3355 ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
3356 ** and the application would have to make a second call to [sqlite3_reset()]
3357 ** in order to find the underlying cause of the problem. With the "v2" prepare
3358 ** interfaces, the underlying reason for the error is returned immediately.
3359 ** </li>
3360 **
3361 ** <li>
3362 ** ^If the specific value bound to [parameter | host parameter] in the 
3363 ** WHERE clause might influence the choice of query plan for a statement,
3364 ** then the statement will be automatically recompiled, as if there had been 
3365 ** a schema change, on the first  [sqlite3_step()] call following any change
3366 ** to the [sqlite3_bind_text | bindings] of that [parameter]. 
3367 ** ^The specific value of WHERE-clause [parameter] might influence the 
3368 ** choice of query plan if the parameter is the left-hand side of a [LIKE]
3369 ** or [GLOB] operator or if the parameter is compared to an indexed column
3370 ** and the [SQLITE_ENABLE_STAT2] compile-time option is enabled.
3371 ** the 
3372 ** </li>
3373 ** </ol>
3374 */
3375 SQLITE_API int sqlite3_prepare(
3376   sqlite3 *db,            /* Database handle */
3377   const char *zSql,       /* SQL statement, UTF-8 encoded */
3378   int nByte,              /* Maximum length of zSql in bytes. */
3379   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3380   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3381 );
3382 SQLITE_API int sqlite3_prepare_v2(
3383   sqlite3 *db,            /* Database handle */
3384   const char *zSql,       /* SQL statement, UTF-8 encoded */
3385   int nByte,              /* Maximum length of zSql in bytes. */
3386   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3387   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3388 );
3389 SQLITE_API int sqlite3_prepare16(
3390   sqlite3 *db,            /* Database handle */
3391   const void *zSql,       /* SQL statement, UTF-16 encoded */
3392   int nByte,              /* Maximum length of zSql in bytes. */
3393   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3394   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3395 );
3396 SQLITE_API int sqlite3_prepare16_v2(
3397   sqlite3 *db,            /* Database handle */
3398   const void *zSql,       /* SQL statement, UTF-16 encoded */
3399   int nByte,              /* Maximum length of zSql in bytes. */
3400   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3401   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3402 );
3403
3404 /*
3405 ** CAPI3REF: Retrieving Statement SQL
3406 **
3407 ** ^This interface can be used to retrieve a saved copy of the original
3408 ** SQL text used to create a [prepared statement] if that statement was
3409 ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
3410 */
3411 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
3412
3413 /*
3414 ** CAPI3REF: Determine If An SQL Statement Writes The Database
3415 **
3416 ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
3417 ** and only if the [prepared statement] X makes no direct changes to
3418 ** the content of the database file.
3419 **
3420 ** Note that [application-defined SQL functions] or
3421 ** [virtual tables] might change the database indirectly as a side effect.  
3422 ** ^(For example, if an application defines a function "eval()" that 
3423 ** calls [sqlite3_exec()], then the following SQL statement would
3424 ** change the database file through side-effects:
3425 **
3426 ** <blockquote><pre>
3427 **    SELECT eval('DELETE FROM t1') FROM t2;
3428 ** </pre></blockquote>
3429 **
3430 ** But because the [SELECT] statement does not change the database file
3431 ** directly, sqlite3_stmt_readonly() would still return true.)^
3432 **
3433 ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
3434 ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
3435 ** since the statements themselves do not actually modify the database but
3436 ** rather they control the timing of when other statements modify the 
3437 ** database.  ^The [ATTACH] and [DETACH] statements also cause
3438 ** sqlite3_stmt_readonly() to return true since, while those statements
3439 ** change the configuration of a database connection, they do not make 
3440 ** changes to the content of the database files on disk.
3441 */
3442 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
3443
3444 /*
3445 ** CAPI3REF: Dynamically Typed Value Object
3446 ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
3447 **
3448 ** SQLite uses the sqlite3_value object to represent all values
3449 ** that can be stored in a database table. SQLite uses dynamic typing
3450 ** for the values it stores.  ^Values stored in sqlite3_value objects
3451 ** can be integers, floating point values, strings, BLOBs, or NULL.
3452 **
3453 ** An sqlite3_value object may be either "protected" or "unprotected".
3454 ** Some interfaces require a protected sqlite3_value.  Other interfaces
3455 ** will accept either a protected or an unprotected sqlite3_value.
3456 ** Every interface that accepts sqlite3_value arguments specifies
3457 ** whether or not it requires a protected sqlite3_value.
3458 **
3459 ** The terms "protected" and "unprotected" refer to whether or not
3460 ** a mutex is held.  An internal mutex is held for a protected
3461 ** sqlite3_value object but no mutex is held for an unprotected
3462 ** sqlite3_value object.  If SQLite is compiled to be single-threaded
3463 ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
3464 ** or if SQLite is run in one of reduced mutex modes 
3465 ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
3466 ** then there is no distinction between protected and unprotected
3467 ** sqlite3_value objects and they can be used interchangeably.  However,
3468 ** for maximum code portability it is recommended that applications
3469 ** still make the distinction between protected and unprotected
3470 ** sqlite3_value objects even when not strictly required.
3471 **
3472 ** ^The sqlite3_value objects that are passed as parameters into the
3473 ** implementation of [application-defined SQL functions] are protected.
3474 ** ^The sqlite3_value object returned by
3475 ** [sqlite3_column_value()] is unprotected.
3476 ** Unprotected sqlite3_value objects may only be used with
3477 ** [sqlite3_result_value()] and [sqlite3_bind_value()].
3478 ** The [sqlite3_value_blob | sqlite3_value_type()] family of
3479 ** interfaces require protected sqlite3_value objects.
3480 */
3481 typedef struct Mem sqlite3_value;
3482
3483 /*
3484 ** CAPI3REF: SQL Function Context Object
3485 **
3486 ** The context in which an SQL function executes is stored in an
3487 ** sqlite3_context object.  ^A pointer to an sqlite3_context object
3488 ** is always first parameter to [application-defined SQL functions].
3489 ** The application-defined SQL function implementation will pass this
3490 ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
3491 ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
3492 ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
3493 ** and/or [sqlite3_set_auxdata()].
3494 */
3495 typedef struct sqlite3_context sqlite3_context;
3496
3497 /*
3498 ** CAPI3REF: Binding Values To Prepared Statements
3499 ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
3500 ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
3501 **
3502 ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
3503 ** literals may be replaced by a [parameter] that matches one of following
3504 ** templates:
3505 **
3506 ** <ul>
3507 ** <li>  ?
3508 ** <li>  ?NNN
3509 ** <li>  :VVV
3510 ** <li>  @VVV
3511 ** <li>  $VVV
3512 ** </ul>
3513 **
3514 ** In the templates above, NNN represents an integer literal,
3515 ** and VVV represents an alphanumeric identifier.)^  ^The values of these
3516 ** parameters (also called "host parameter names" or "SQL parameters")
3517 ** can be set using the sqlite3_bind_*() routines defined here.
3518 **
3519 ** ^The first argument to the sqlite3_bind_*() routines is always
3520 ** a pointer to the [sqlite3_stmt] object returned from
3521 ** [sqlite3_prepare_v2()] or its variants.
3522 **
3523 ** ^The second argument is the index of the SQL parameter to be set.
3524 ** ^The leftmost SQL parameter has an index of 1.  ^When the same named
3525 ** SQL parameter is used more than once, second and subsequent
3526 ** occurrences have the same index as the first occurrence.
3527 ** ^The index for named parameters can be looked up using the
3528 ** [sqlite3_bind_parameter_index()] API if desired.  ^The index
3529 ** for "?NNN" parameters is the value of NNN.
3530 ** ^The NNN value must be between 1 and the [sqlite3_limit()]
3531 ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
3532 **
3533 ** ^The third argument is the value to bind to the parameter.
3534 **
3535 ** ^(In those routines that have a fourth argument, its value is the
3536 ** number of bytes in the parameter.  To be clear: the value is the
3537 ** number of <u>bytes</u> in the value, not the number of characters.)^
3538 ** ^If the fourth parameter is negative, the length of the string is
3539 ** the number of bytes up to the first zero terminator.
3540 **
3541 ** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
3542 ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
3543 ** string after SQLite has finished with it.  ^The destructor is called
3544 ** to dispose of the BLOB or string even if the call to sqlite3_bind_blob(),
3545 ** sqlite3_bind_text(), or sqlite3_bind_text16() fails.  
3546 ** ^If the fifth argument is
3547 ** the special value [SQLITE_STATIC], then SQLite assumes that the
3548 ** information is in static, unmanaged space and does not need to be freed.
3549 ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
3550 ** SQLite makes its own private copy of the data immediately, before
3551 ** the sqlite3_bind_*() routine returns.
3552 **
3553 ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
3554 ** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory
3555 ** (just an integer to hold its size) while it is being processed.
3556 ** Zeroblobs are intended to serve as placeholders for BLOBs whose
3557 ** content is later written using
3558 ** [sqlite3_blob_open | incremental BLOB I/O] routines.
3559 ** ^A negative value for the zeroblob results in a zero-length BLOB.
3560 **
3561 ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
3562 ** for the [prepared statement] or with a prepared statement for which
3563 ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
3564 ** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()
3565 ** routine is passed a [prepared statement] that has been finalized, the
3566 ** result is undefined and probably harmful.
3567 **
3568 ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
3569 ** ^Unbound parameters are interpreted as NULL.
3570 **
3571 ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
3572 ** [error code] if anything goes wrong.
3573 ** ^[SQLITE_RANGE] is returned if the parameter
3574 ** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.
3575 **
3576 ** See also: [sqlite3_bind_parameter_count()],
3577 ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
3578 */
3579 SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
3580 SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
3581 SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
3582 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
3583 SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
3584 SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
3585 SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
3586 SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
3587 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
3588
3589 /*
3590 ** CAPI3REF: Number Of SQL Parameters
3591 **
3592 ** ^This routine can be used to find the number of [SQL parameters]
3593 ** in a [prepared statement].  SQL parameters are tokens of the
3594 ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
3595 ** placeholders for values that are [sqlite3_bind_blob | bound]
3596 ** to the parameters at a later time.
3597 **
3598 ** ^(This routine actually returns the index of the largest (rightmost)
3599 ** parameter. For all forms except ?NNN, this will correspond to the
3600 ** number of unique parameters.  If parameters of the ?NNN form are used,
3601 ** there may be gaps in the list.)^
3602 **
3603 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3604 ** [sqlite3_bind_parameter_name()], and
3605 ** [sqlite3_bind_parameter_index()].
3606 */
3607 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
3608
3609 /*
3610 ** CAPI3REF: Name Of A Host Parameter
3611 **
3612 ** ^The sqlite3_bind_parameter_name(P,N) interface returns
3613 ** the name of the N-th [SQL parameter] in the [prepared statement] P.
3614 ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
3615 ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
3616 ** respectively.
3617 ** In other words, the initial ":" or "$" or "@" or "?"
3618 ** is included as part of the name.)^
3619 ** ^Parameters of the form "?" without a following integer have no name
3620 ** and are referred to as "nameless" or "anonymous parameters".
3621 **
3622 ** ^The first host parameter has an index of 1, not 0.
3623 **
3624 ** ^If the value N is out of range or if the N-th parameter is
3625 ** nameless, then NULL is returned.  ^The returned string is
3626 ** always in UTF-8 encoding even if the named parameter was
3627 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
3628 ** [sqlite3_prepare16_v2()].
3629 **
3630 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3631 ** [sqlite3_bind_parameter_count()], and
3632 ** [sqlite3_bind_parameter_index()].
3633 */
3634 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
3635
3636 /*
3637 ** CAPI3REF: Index Of A Parameter With A Given Name
3638 **
3639 ** ^Return the index of an SQL parameter given its name.  ^The
3640 ** index value returned is suitable for use as the second
3641 ** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero
3642 ** is returned if no matching parameter is found.  ^The parameter
3643 ** name must be given in UTF-8 even if the original statement
3644 ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
3645 **
3646 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3647 ** [sqlite3_bind_parameter_count()], and
3648 ** [sqlite3_bind_parameter_index()].
3649 */
3650 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
3651
3652 /*
3653 ** CAPI3REF: Reset All Bindings On A Prepared Statement
3654 **
3655 ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
3656 ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
3657 ** ^Use this routine to reset all host parameters to NULL.
3658 */
3659 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
3660
3661 /*
3662 ** CAPI3REF: Number Of Columns In A Result Set
3663 **
3664 ** ^Return the number of columns in the result set returned by the
3665 ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
3666 ** statement that does not return data (for example an [UPDATE]).
3667 **
3668 ** See also: [sqlite3_data_count()]
3669 */
3670 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
3671
3672 /*
3673 ** CAPI3REF: Column Names In A Result Set
3674 **
3675 ** ^These routines return the name assigned to a particular column
3676 ** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()
3677 ** interface returns a pointer to a zero-terminated UTF-8 string
3678 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
3679 ** UTF-16 string.  ^The first parameter is the [prepared statement]
3680 ** that implements the [SELECT] statement. ^The second parameter is the
3681 ** column number.  ^The leftmost column is number 0.
3682 **
3683 ** ^The returned string pointer is valid until either the [prepared statement]
3684 ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
3685 ** reprepared by the first call to [sqlite3_step()] for a particular run
3686 ** or until the next call to
3687 ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
3688 **
3689 ** ^If sqlite3_malloc() fails during the processing of either routine
3690 ** (for example during a conversion from UTF-8 to UTF-16) then a
3691 ** NULL pointer is returned.
3692 **
3693 ** ^The name of a result column is the value of the "AS" clause for
3694 ** that column, if there is an AS clause.  If there is no AS clause
3695 ** then the name of the column is unspecified and may change from
3696 ** one release of SQLite to the next.
3697 */
3698 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
3699 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
3700
3701 /*
3702 ** CAPI3REF: Source Of Data In A Query Result
3703 **
3704 ** ^These routines provide a means to determine the database, table, and
3705 ** table column that is the origin of a particular result column in
3706 ** [SELECT] statement.
3707 ** ^The name of the database or table or column can be returned as
3708 ** either a UTF-8 or UTF-16 string.  ^The _database_ routines return
3709 ** the database name, the _table_ routines return the table name, and
3710 ** the origin_ routines return the column name.
3711 ** ^The returned string is valid until the [prepared statement] is destroyed
3712 ** using [sqlite3_finalize()] or until the statement is automatically
3713 ** reprepared by the first call to [sqlite3_step()] for a particular run
3714 ** or until the same information is requested
3715 ** again in a different encoding.
3716 **
3717 ** ^The names returned are the original un-aliased names of the
3718 ** database, table, and column.
3719 **
3720 ** ^The first argument to these interfaces is a [prepared statement].
3721 ** ^These functions return information about the Nth result column returned by
3722 ** the statement, where N is the second function argument.
3723 ** ^The left-most column is column 0 for these routines.
3724 **
3725 ** ^If the Nth column returned by the statement is an expression or
3726 ** subquery and is not a column value, then all of these functions return
3727 ** NULL.  ^These routine might also return NULL if a memory allocation error
3728 ** occurs.  ^Otherwise, they return the name of the attached database, table,
3729 ** or column that query result column was extracted from.
3730 **
3731 ** ^As with all other SQLite APIs, those whose names end with "16" return
3732 ** UTF-16 encoded strings and the other functions return UTF-8.
3733 **
3734 ** ^These APIs are only available if the library was compiled with the
3735 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
3736 **
3737 ** If two or more threads call one or more of these routines against the same
3738 ** prepared statement and column at the same time then the results are
3739 ** undefined.
3740 **
3741 ** If two or more threads call one or more
3742 ** [sqlite3_column_database_name | column metadata interfaces]
3743 ** for the same [prepared statement] and result column
3744 ** at the same time then the results are undefined.
3745 */
3746 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
3747 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
3748 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
3749 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
3750 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
3751 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
3752
3753 /*
3754 ** CAPI3REF: Declared Datatype Of A Query Result
3755 **
3756 ** ^(The first parameter is a [prepared statement].
3757 ** If this statement is a [SELECT] statement and the Nth column of the
3758 ** returned result set of that [SELECT] is a table column (not an
3759 ** expression or subquery) then the declared type of the table
3760 ** column is returned.)^  ^If the Nth column of the result set is an
3761 ** expression or subquery, then a NULL pointer is returned.
3762 ** ^The returned string is always UTF-8 encoded.
3763 **
3764 ** ^(For example, given the database schema:
3765 **
3766 ** CREATE TABLE t1(c1 VARIANT);
3767 **
3768 ** and the following statement to be compiled:
3769 **
3770 ** SELECT c1 + 1, c1 FROM t1;
3771 **
3772 ** this routine would return the string "VARIANT" for the second result
3773 ** column (i==1), and a NULL pointer for the first result column (i==0).)^
3774 **
3775 ** ^SQLite uses dynamic run-time typing.  ^So just because a column
3776 ** is declared to contain a particular type does not mean that the
3777 ** data stored in that column is of the declared type.  SQLite is
3778 ** strongly typed, but the typing is dynamic not static.  ^Type
3779 ** is associated with individual values, not with the containers
3780 ** used to hold those values.
3781 */
3782 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
3783 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
3784
3785 /*
3786 ** CAPI3REF: Evaluate An SQL Statement
3787 **
3788 ** After a [prepared statement] has been prepared using either
3789 ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
3790 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
3791 ** must be called one or more times to evaluate the statement.
3792 **
3793 ** The details of the behavior of the sqlite3_step() interface depend
3794 ** on whether the statement was prepared using the newer "v2" interface
3795 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
3796 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
3797 ** new "v2" interface is recommended for new applications but the legacy
3798 ** interface will continue to be supported.
3799 **
3800 ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
3801 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
3802 ** ^With the "v2" interface, any of the other [result codes] or
3803 ** [extended result codes] might be returned as well.
3804 **
3805 ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
3806 ** database locks it needs to do its job.  ^If the statement is a [COMMIT]
3807 ** or occurs outside of an explicit transaction, then you can retry the
3808 ** statement.  If the statement is not a [COMMIT] and occurs within an
3809 ** explicit transaction then you should rollback the transaction before
3810 ** continuing.
3811 **
3812 ** ^[SQLITE_DONE] means that the statement has finished executing
3813 ** successfully.  sqlite3_step() should not be called again on this virtual
3814 ** machine without first calling [sqlite3_reset()] to reset the virtual
3815 ** machine back to its initial state.
3816 **
3817 ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
3818 ** is returned each time a new row of data is ready for processing by the
3819 ** caller. The values may be accessed using the [column access functions].
3820 ** sqlite3_step() is called again to retrieve the next row of data.
3821 **
3822 ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
3823 ** violation) has occurred.  sqlite3_step() should not be called again on
3824 ** the VM. More information may be found by calling [sqlite3_errmsg()].
3825 ** ^With the legacy interface, a more specific error code (for example,
3826 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
3827 ** can be obtained by calling [sqlite3_reset()] on the
3828 ** [prepared statement].  ^In the "v2" interface,
3829 ** the more specific error code is returned directly by sqlite3_step().
3830 **
3831 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
3832 ** Perhaps it was called on a [prepared statement] that has
3833 ** already been [sqlite3_finalize | finalized] or on one that had
3834 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
3835 ** be the case that the same database connection is being used by two or
3836 ** more threads at the same moment in time.
3837 **
3838 ** For all versions of SQLite up to and including 3.6.23.1, a call to
3839 ** [sqlite3_reset()] was required after sqlite3_step() returned anything
3840 ** other than [SQLITE_ROW] before any subsequent invocation of
3841 ** sqlite3_step().  Failure to reset the prepared statement using 
3842 ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
3843 ** sqlite3_step().  But after version 3.6.23.1, sqlite3_step() began
3844 ** calling [sqlite3_reset()] automatically in this circumstance rather
3845 ** than returning [SQLITE_MISUSE].  This is not considered a compatibility
3846 ** break because any application that ever receives an SQLITE_MISUSE error
3847 ** is broken by definition.  The [SQLITE_OMIT_AUTORESET] compile-time option
3848 ** can be used to restore the legacy behavior.
3849 **
3850 ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
3851 ** API always returns a generic error code, [SQLITE_ERROR], following any
3852 ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
3853 ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
3854 ** specific [error codes] that better describes the error.
3855 ** We admit that this is a goofy design.  The problem has been fixed
3856 ** with the "v2" interface.  If you prepare all of your SQL statements
3857 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
3858 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
3859 ** then the more specific [error codes] are returned directly
3860 ** by sqlite3_step().  The use of the "v2" interface is recommended.
3861 */
3862 SQLITE_API int sqlite3_step(sqlite3_stmt*);
3863
3864 /*
3865 ** CAPI3REF: Number of columns in a result set
3866 **
3867 ** ^The sqlite3_data_count(P) interface returns the number of columns in the
3868 ** current row of the result set of [prepared statement] P.
3869 ** ^If prepared statement P does not have results ready to return
3870 ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
3871 ** interfaces) then sqlite3_data_count(P) returns 0.
3872 ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
3873 **
3874 ** See also: [sqlite3_column_count()]
3875 */
3876 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
3877
3878 /*
3879 ** CAPI3REF: Fundamental Datatypes
3880 ** KEYWORDS: SQLITE_TEXT
3881 **
3882 ** ^(Every value in SQLite has one of five fundamental datatypes:
3883 **
3884 ** <ul>
3885 ** <li> 64-bit signed integer
3886 ** <li> 64-bit IEEE floating point number
3887 ** <li> string
3888 ** <li> BLOB
3889 ** <li> NULL
3890 ** </ul>)^
3891 **
3892 ** These constants are codes for each of those types.
3893 **
3894 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
3895 ** for a completely different meaning.  Software that links against both
3896 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
3897 ** SQLITE_TEXT.
3898 */
3899 #define SQLITE_INTEGER  1
3900 #define SQLITE_FLOAT    2
3901 #define SQLITE_BLOB     4
3902 #define SQLITE_NULL     5
3903 #ifdef SQLITE_TEXT
3904 # undef SQLITE_TEXT
3905 #else
3906 # define SQLITE_TEXT     3
3907 #endif
3908 #define SQLITE3_TEXT     3
3909
3910 /*
3911 ** CAPI3REF: Result Values From A Query
3912 ** KEYWORDS: {column access functions}
3913 **
3914 ** These routines form the "result set" interface.
3915 **
3916 ** ^These routines return information about a single column of the current
3917 ** result row of a query.  ^In every case the first argument is a pointer
3918 ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
3919 ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
3920 ** and the second argument is the index of the column for which information
3921 ** should be returned. ^The leftmost column of the result set has the index 0.
3922 ** ^The number of columns in the result can be determined using
3923 ** [sqlite3_column_count()].
3924 **
3925 ** If the SQL statement does not currently point to a valid row, or if the
3926 ** column index is out of range, the result is undefined.
3927 ** These routines may only be called when the most recent call to
3928 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
3929 ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
3930 ** If any of these routines are called after [sqlite3_reset()] or
3931 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
3932 ** something other than [SQLITE_ROW], the results are undefined.
3933 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
3934 ** are called from a different thread while any of these routines
3935 ** are pending, then the results are undefined.
3936 **
3937 ** ^The sqlite3_column_type() routine returns the
3938 ** [SQLITE_INTEGER | datatype code] for the initial data type
3939 ** of the result column.  ^The returned value is one of [SQLITE_INTEGER],
3940 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
3941 ** returned by sqlite3_column_type() is only meaningful if no type
3942 ** conversions have occurred as described below.  After a type conversion,
3943 ** the value returned by sqlite3_column_type() is undefined.  Future
3944 ** versions of SQLite may change the behavior of sqlite3_column_type()
3945 ** following a type conversion.
3946 **
3947 ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
3948 ** routine returns the number of bytes in that BLOB or string.
3949 ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
3950 ** the string to UTF-8 and then returns the number of bytes.
3951 ** ^If the result is a numeric value then sqlite3_column_bytes() uses
3952 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
3953 ** the number of bytes in that string.
3954 ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
3955 **
3956 ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
3957 ** routine returns the number of bytes in that BLOB or string.
3958 ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
3959 ** the string to UTF-16 and then returns the number of bytes.
3960 ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
3961 ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
3962 ** the number of bytes in that string.
3963 ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
3964 **
3965 ** ^The values returned by [sqlite3_column_bytes()] and 
3966 ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
3967 ** of the string.  ^For clarity: the values returned by
3968 ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
3969 ** bytes in the string, not the number of characters.
3970 **
3971 ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
3972 ** even empty strings, are always zero terminated.  ^The return
3973 ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
3974 **
3975 ** ^The object returned by [sqlite3_column_value()] is an
3976 ** [unprotected sqlite3_value] object.  An unprotected sqlite3_value object
3977 ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
3978 ** If the [unprotected sqlite3_value] object returned by
3979 ** [sqlite3_column_value()] is used in any other way, including calls
3980 ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
3981 ** or [sqlite3_value_bytes()], then the behavior is undefined.
3982 **
3983 ** These routines attempt to convert the value where appropriate.  ^For
3984 ** example, if the internal representation is FLOAT and a text result
3985 ** is requested, [sqlite3_snprintf()] is used internally to perform the
3986 ** conversion automatically.  ^(The following table details the conversions
3987 ** that are applied:
3988 **
3989 ** <blockquote>
3990 ** <table border="1">
3991 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
3992 **
3993 ** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
3994 ** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
3995 ** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer
3996 ** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer
3997 ** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
3998 ** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
3999 ** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
4000 ** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer
4001 ** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
4002 ** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT
4003 ** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()
4004 ** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()
4005 ** <tr><td>  TEXT    <td>   BLOB    <td> No change
4006 ** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()
4007 ** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()
4008 ** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
4009 ** </table>
4010 ** </blockquote>)^
4011 **
4012 ** The table above makes reference to standard C library functions atoi()
4013 ** and atof().  SQLite does not really use these functions.  It has its
4014 ** own equivalent internal routines.  The atoi() and atof() names are
4015 ** used in the table for brevity and because they are familiar to most
4016 ** C programmers.
4017 **
4018 ** Note that when type conversions occur, pointers returned by prior
4019 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
4020 ** sqlite3_column_text16() may be invalidated.
4021 ** Type conversions and pointer invalidations might occur
4022 ** in the following cases:
4023 **
4024 ** <ul>
4025 ** <li> The initial content is a BLOB and sqlite3_column_text() or
4026 **      sqlite3_column_text16() is called.  A zero-terminator might
4027 **      need to be added to the string.</li>
4028 ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
4029 **      sqlite3_column_text16() is called.  The content must be converted
4030 **      to UTF-16.</li>
4031 ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
4032 **      sqlite3_column_text() is called.  The content must be converted
4033 **      to UTF-8.</li>
4034 ** </ul>
4035 **
4036 ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
4037 ** not invalidate a prior pointer, though of course the content of the buffer
4038 ** that the prior pointer references will have been modified.  Other kinds
4039 ** of conversion are done in place when it is possible, but sometimes they
4040 ** are not possible and in those cases prior pointers are invalidated.
4041 **
4042 ** The safest and easiest to remember policy is to invoke these routines
4043 ** in one of the following ways:
4044 **
4045 ** <ul>
4046 **  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
4047 **  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
4048 **  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
4049 ** </ul>
4050 **
4051 ** In other words, you should call sqlite3_column_text(),
4052 ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
4053 ** into the desired format, then invoke sqlite3_column_bytes() or
4054 ** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
4055 ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
4056 ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
4057 ** with calls to sqlite3_column_bytes().
4058 **
4059 ** ^The pointers returned are valid until a type conversion occurs as
4060 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
4061 ** [sqlite3_finalize()] is called.  ^The memory space used to hold strings
4062 ** and BLOBs is freed automatically.  Do <b>not</b> pass the pointers returned
4063 ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
4064 ** [sqlite3_free()].
4065 **
4066 ** ^(If a memory allocation error occurs during the evaluation of any
4067 ** of these routines, a default value is returned.  The default value
4068 ** is either the integer 0, the floating point number 0.0, or a NULL
4069 ** pointer.  Subsequent calls to [sqlite3_errcode()] will return
4070 ** [SQLITE_NOMEM].)^
4071 */
4072 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
4073 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
4074 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
4075 SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
4076 SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
4077 SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
4078 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
4079 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
4080 SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
4081 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
4082
4083 /*
4084 ** CAPI3REF: Destroy A Prepared Statement Object
4085 **
4086 ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
4087 ** ^If the most recent evaluation of the statement encountered no errors
4088 ** or if the statement is never been evaluated, then sqlite3_finalize() returns
4089 ** SQLITE_OK.  ^If the most recent evaluation of statement S failed, then
4090 ** sqlite3_finalize(S) returns the appropriate [error code] or
4091 ** [extended error code].
4092 **
4093 ** ^The sqlite3_finalize(S) routine can be called at any point during
4094 ** the life cycle of [prepared statement] S:
4095 ** before statement S is ever evaluated, after
4096 ** one or more calls to [sqlite3_reset()], or after any call
4097 ** to [sqlite3_step()] regardless of whether or not the statement has
4098 ** completed execution.
4099 **
4100 ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
4101 **
4102 ** The application must finalize every [prepared statement] in order to avoid
4103 ** resource leaks.  It is a grievous error for the application to try to use
4104 ** a prepared statement after it has been finalized.  Any use of a prepared
4105 ** statement after it has been finalized can result in undefined and
4106 ** undesirable behavior such as segfaults and heap corruption.
4107 */
4108 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
4109
4110 /*
4111 ** CAPI3REF: Reset A Prepared Statement Object
4112 **
4113 ** The sqlite3_reset() function is called to reset a [prepared statement]
4114 ** object back to its initial state, ready to be re-executed.
4115 ** ^Any SQL statement variables that had values bound to them using
4116 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
4117 ** Use [sqlite3_clear_bindings()] to reset the bindings.
4118 **
4119 ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
4120 ** back to the beginning of its program.
4121 **
4122 ** ^If the most recent call to [sqlite3_step(S)] for the
4123 ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
4124 ** or if [sqlite3_step(S)] has never before been called on S,
4125 ** then [sqlite3_reset(S)] returns [SQLITE_OK].
4126 **
4127 ** ^If the most recent call to [sqlite3_step(S)] for the
4128 ** [prepared statement] S indicated an error, then
4129 ** [sqlite3_reset(S)] returns an appropriate [error code].
4130 **
4131 ** ^The [sqlite3_reset(S)] interface does not change the values
4132 ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
4133 */
4134 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
4135
4136 /*
4137 ** CAPI3REF: Create Or Redefine SQL Functions
4138 ** KEYWORDS: {function creation routines}
4139 ** KEYWORDS: {application-defined SQL function}
4140 ** KEYWORDS: {application-defined SQL functions}
4141 **
4142 ** ^These functions (collectively known as "function creation routines")
4143 ** are used to add SQL functions or aggregates or to redefine the behavior
4144 ** of existing SQL functions or aggregates.  The only differences between
4145 ** these routines are the text encoding expected for
4146 ** the second parameter (the name of the function being created)
4147 ** and the presence or absence of a destructor callback for
4148 ** the application data pointer.
4149 **
4150 ** ^The first parameter is the [database connection] to which the SQL
4151 ** function is to be added.  ^If an application uses more than one database
4152 ** connection then application-defined SQL functions must be added
4153 ** to each database connection separately.
4154 **
4155 ** ^The second parameter is the name of the SQL function to be created or
4156 ** redefined.  ^The length of the name is limited to 255 bytes in a UTF-8
4157 ** representation, exclusive of the zero-terminator.  ^Note that the name
4158 ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.  
4159 ** ^Any attempt to create a function with a longer name
4160 ** will result in [SQLITE_MISUSE] being returned.
4161 **
4162 ** ^The third parameter (nArg)
4163 ** is the number of arguments that the SQL function or
4164 ** aggregate takes. ^If this parameter is -1, then the SQL function or
4165 ** aggregate may take any number of arguments between 0 and the limit
4166 ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third
4167 ** parameter is less than -1 or greater than 127 then the behavior is
4168 ** undefined.
4169 **
4170 ** ^The fourth parameter, eTextRep, specifies what
4171 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
4172 ** its parameters.  Every SQL function implementation must be able to work
4173 ** with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
4174 ** more efficient with one encoding than another.  ^An application may
4175 ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
4176 ** times with the same function but with different values of eTextRep.
4177 ** ^When multiple implementations of the same function are available, SQLite
4178 ** will pick the one that involves the least amount of data conversion.
4179 ** If there is only a single implementation which does not care what text
4180 ** encoding is used, then the fourth argument should be [SQLITE_ANY].
4181 **
4182 ** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
4183 ** function can gain access to this pointer using [sqlite3_user_data()].)^
4184 **
4185 ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
4186 ** pointers to C-language functions that implement the SQL function or
4187 ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
4188 ** callback only; NULL pointers must be passed as the xStep and xFinal
4189 ** parameters. ^An aggregate SQL function requires an implementation of xStep
4190 ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
4191 ** SQL function or aggregate, pass NULL pointers for all three function
4192 ** callbacks.
4193 **
4194 ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
4195 ** then it is destructor for the application data pointer. 
4196 ** The destructor is invoked when the function is deleted, either by being
4197 ** overloaded or when the database connection closes.)^
4198 ** ^The destructor is also invoked if the call to
4199 ** sqlite3_create_function_v2() fails.
4200 ** ^When the destructor callback of the tenth parameter is invoked, it
4201 ** is passed a single argument which is a copy of the application data 
4202 ** pointer which was the fifth parameter to sqlite3_create_function_v2().
4203 **
4204 ** ^It is permitted to register multiple implementations of the same
4205 ** functions with the same name but with either differing numbers of
4206 ** arguments or differing preferred text encodings.  ^SQLite will use
4207 ** the implementation that most closely matches the way in which the
4208 ** SQL function is used.  ^A function implementation with a non-negative
4209 ** nArg parameter is a better match than a function implementation with
4210 ** a negative nArg.  ^A function where the preferred text encoding
4211 ** matches the database encoding is a better
4212 ** match than a function where the encoding is different.  
4213 ** ^A function where the encoding difference is between UTF16le and UTF16be
4214 ** is a closer match than a function where the encoding difference is
4215 ** between UTF8 and UTF16.
4216 **
4217 ** ^Built-in functions may be overloaded by new application-defined functions.
4218 **
4219 ** ^An application-defined function is permitted to call other
4220 ** SQLite interfaces.  However, such calls must not
4221 ** close the database connection nor finalize or reset the prepared
4222 ** statement in which the function is running.
4223 */
4224 SQLITE_API int sqlite3_create_function(
4225   sqlite3 *db,
4226   const char *zFunctionName,
4227   int nArg,
4228   int eTextRep,
4229   void *pApp,
4230   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4231   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4232   void (*xFinal)(sqlite3_context*)
4233 );
4234 SQLITE_API int sqlite3_create_function16(
4235   sqlite3 *db,
4236   const void *zFunctionName,
4237   int nArg,
4238   int eTextRep,
4239   void *pApp,
4240   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4241   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4242   void (*xFinal)(sqlite3_context*)
4243 );
4244 SQLITE_API int sqlite3_create_function_v2(
4245   sqlite3 *db,
4246   const char *zFunctionName,
4247   int nArg,
4248   int eTextRep,
4249   void *pApp,
4250   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4251   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4252   void (*xFinal)(sqlite3_context*),
4253   void(*xDestroy)(void*)
4254 );
4255
4256 /*
4257 ** CAPI3REF: Text Encodings
4258 **
4259 ** These constant define integer codes that represent the various
4260 ** text encodings supported by SQLite.
4261 */
4262 #define SQLITE_UTF8           1
4263 #define SQLITE_UTF16LE        2
4264 #define SQLITE_UTF16BE        3
4265 #define SQLITE_UTF16          4    /* Use native byte order */
4266 #define SQLITE_ANY            5    /* sqlite3_create_function only */
4267 #define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
4268
4269 /*
4270 ** CAPI3REF: Deprecated Functions
4271 ** DEPRECATED
4272 **
4273 ** These functions are [deprecated].  In order to maintain
4274 ** backwards compatibility with older code, these functions continue 
4275 ** to be supported.  However, new applications should avoid
4276 ** the use of these functions.  To help encourage people to avoid
4277 ** using these functions, we are not going to tell you what they do.
4278 */
4279 #ifndef SQLITE_OMIT_DEPRECATED
4280 SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
4281 SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
4282 SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
4283 SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
4284 SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
4285 SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
4286 #endif
4287
4288 /*
4289 ** CAPI3REF: Obtaining SQL Function Parameter Values
4290 **
4291 ** The C-language implementation of SQL functions and aggregates uses
4292 ** this set of interface routines to access the parameter values on
4293 ** the function or aggregate.
4294 **
4295 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
4296 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
4297 ** define callbacks that implement the SQL functions and aggregates.
4298 ** The 3rd parameter to these callbacks is an array of pointers to
4299 ** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for
4300 ** each parameter to the SQL function.  These routines are used to
4301 ** extract values from the [sqlite3_value] objects.
4302 **
4303 ** These routines work only with [protected sqlite3_value] objects.
4304 ** Any attempt to use these routines on an [unprotected sqlite3_value]
4305 ** object results in undefined behavior.
4306 **
4307 ** ^These routines work just like the corresponding [column access functions]
4308 ** except that  these routines take a single [protected sqlite3_value] object
4309 ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
4310 **
4311 ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
4312 ** in the native byte-order of the host machine.  ^The
4313 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
4314 ** extract UTF-16 strings as big-endian and little-endian respectively.
4315 **
4316 ** ^(The sqlite3_value_numeric_type() interface attempts to apply
4317 ** numeric affinity to the value.  This means that an attempt is
4318 ** made to convert the value to an integer or floating point.  If
4319 ** such a conversion is possible without loss of information (in other
4320 ** words, if the value is a string that looks like a number)
4321 ** then the conversion is performed.  Otherwise no conversion occurs.
4322 ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
4323 **
4324 ** Please pay particular attention to the fact that the pointer returned
4325 ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
4326 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
4327 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
4328 ** or [sqlite3_value_text16()].
4329 **
4330 ** These routines must be called from the same thread as
4331 ** the SQL function that supplied the [sqlite3_value*] parameters.
4332 */
4333 SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
4334 SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
4335 SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
4336 SQLITE_API double sqlite3_value_double(sqlite3_value*);
4337 SQLITE_API int sqlite3_value_int(sqlite3_value*);
4338 SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
4339 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
4340 SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
4341 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
4342 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
4343 SQLITE_API int sqlite3_value_type(sqlite3_value*);
4344 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
4345
4346 /*
4347 ** CAPI3REF: Obtain Aggregate Function Context
4348 **
4349 ** Implementations of aggregate SQL functions use this
4350 ** routine to allocate memory for storing their state.
4351 **
4352 ** ^The first time the sqlite3_aggregate_context(C,N) routine is called 
4353 ** for a particular aggregate function, SQLite
4354 ** allocates N of memory, zeroes out that memory, and returns a pointer
4355 ** to the new memory. ^On second and subsequent calls to
4356 ** sqlite3_aggregate_context() for the same aggregate function instance,
4357 ** the same buffer is returned.  Sqlite3_aggregate_context() is normally
4358 ** called once for each invocation of the xStep callback and then one
4359 ** last time when the xFinal callback is invoked.  ^(When no rows match
4360 ** an aggregate query, the xStep() callback of the aggregate function
4361 ** implementation is never called and xFinal() is called exactly once.
4362 ** In those cases, sqlite3_aggregate_context() might be called for the
4363 ** first time from within xFinal().)^
4364 **
4365 ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer if N is
4366 ** less than or equal to zero or if a memory allocate error occurs.
4367 **
4368 ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
4369 ** determined by the N parameter on first successful call.  Changing the
4370 ** value of N in subsequent call to sqlite3_aggregate_context() within
4371 ** the same aggregate function instance will not resize the memory
4372 ** allocation.)^
4373 **
4374 ** ^SQLite automatically frees the memory allocated by 
4375 ** sqlite3_aggregate_context() when the aggregate query concludes.
4376 **
4377 ** The first parameter must be a copy of the
4378 ** [sqlite3_context | SQL function context] that is the first parameter
4379 ** to the xStep or xFinal callback routine that implements the aggregate
4380 ** function.
4381 **
4382 ** This routine must be called from the same thread in which
4383 ** the aggregate SQL function is running.
4384 */
4385 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
4386
4387 /*
4388 ** CAPI3REF: User Data For Functions
4389 **
4390 ** ^The sqlite3_user_data() interface returns a copy of
4391 ** the pointer that was the pUserData parameter (the 5th parameter)
4392 ** of the [sqlite3_create_function()]
4393 ** and [sqlite3_create_function16()] routines that originally
4394 ** registered the application defined function.
4395 **
4396 ** This routine must be called from the same thread in which
4397 ** the application-defined function is running.
4398 */
4399 SQLITE_API void *sqlite3_user_data(sqlite3_context*);
4400
4401 /*
4402 ** CAPI3REF: Database Connection For Functions
4403 **
4404 ** ^The sqlite3_context_db_handle() interface returns a copy of
4405 ** the pointer to the [database connection] (the 1st parameter)
4406 ** of the [sqlite3_create_function()]
4407 ** and [sqlite3_create_function16()] routines that originally
4408 ** registered the application defined function.
4409 */
4410 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
4411
4412 /*
4413 ** CAPI3REF: Function Auxiliary Data
4414 **
4415 ** The following two functions may be used by scalar SQL functions to
4416 ** associate metadata with argument values. If the same value is passed to
4417 ** multiple invocations of the same SQL function during query execution, under
4418 ** some circumstances the associated metadata may be preserved. This may
4419 ** be used, for example, to add a regular-expression matching scalar
4420 ** function. The compiled version of the regular expression is stored as
4421 ** metadata associated with the SQL value passed as the regular expression
4422 ** pattern.  The compiled regular expression can be reused on multiple
4423 ** invocations of the same function so that the original pattern string
4424 ** does not need to be recompiled on each invocation.
4425 **
4426 ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
4427 ** associated by the sqlite3_set_auxdata() function with the Nth argument
4428 ** value to the application-defined function. ^If no metadata has been ever
4429 ** been set for the Nth argument of the function, or if the corresponding
4430 ** function parameter has changed since the meta-data was set,
4431 ** then sqlite3_get_auxdata() returns a NULL pointer.
4432 **
4433 ** ^The sqlite3_set_auxdata() interface saves the metadata
4434 ** pointed to by its 3rd parameter as the metadata for the N-th
4435 ** argument of the application-defined function.  Subsequent
4436 ** calls to sqlite3_get_auxdata() might return this data, if it has
4437 ** not been destroyed.
4438 ** ^If it is not NULL, SQLite will invoke the destructor
4439 ** function given by the 4th parameter to sqlite3_set_auxdata() on
4440 ** the metadata when the corresponding function parameter changes
4441 ** or when the SQL statement completes, whichever comes first.
4442 **
4443 ** SQLite is free to call the destructor and drop metadata on any
4444 ** parameter of any function at any time.  ^The only guarantee is that
4445 ** the destructor will be called before the metadata is dropped.
4446 **
4447 ** ^(In practice, metadata is preserved between function calls for
4448 ** expressions that are constant at compile time. This includes literal
4449 ** values and [parameters].)^
4450 **
4451 ** These routines must be called from the same thread in which
4452 ** the SQL function is running.
4453 */
4454 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
4455 SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
4456
4457
4458 /*
4459 ** CAPI3REF: Constants Defining Special Destructor Behavior
4460 **
4461 ** These are special values for the destructor that is passed in as the
4462 ** final argument to routines like [sqlite3_result_blob()].  ^If the destructor
4463 ** argument is SQLITE_STATIC, it means that the content pointer is constant
4464 ** and will never change.  It does not need to be destroyed.  ^The
4465 ** SQLITE_TRANSIENT value means that the content will likely change in
4466 ** the near future and that SQLite should make its own private copy of
4467 ** the content before returning.
4468 **
4469 ** The typedef is necessary to work around problems in certain
4470 ** C++ compilers.  See ticket #2191.
4471 */
4472 typedef void (*sqlite3_destructor_type)(void*);
4473 #define SQLITE_STATIC      ((sqlite3_destructor_type)0)
4474 #define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
4475
4476 /*
4477 ** CAPI3REF: Setting The Result Of An SQL Function
4478 **
4479 ** These routines are used by the xFunc or xFinal callbacks that
4480 ** implement SQL functions and aggregates.  See
4481 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
4482 ** for additional information.
4483 **
4484 ** These functions work very much like the [parameter binding] family of
4485 ** functions used to bind values to host parameters in prepared statements.
4486 ** Refer to the [SQL parameter] documentation for additional information.
4487 **
4488 ** ^The sqlite3_result_blob() interface sets the result from
4489 ** an application-defined function to be the BLOB whose content is pointed
4490 ** to by the second parameter and which is N bytes long where N is the
4491 ** third parameter.
4492 **
4493 ** ^The sqlite3_result_zeroblob() interfaces set the result of
4494 ** the application-defined function to be a BLOB containing all zero
4495 ** bytes and N bytes in size, where N is the value of the 2nd parameter.
4496 **
4497 ** ^The sqlite3_result_double() interface sets the result from
4498 ** an application-defined function to be a floating point value specified
4499 ** by its 2nd argument.
4500 **
4501 ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
4502 ** cause the implemented SQL function to throw an exception.
4503 ** ^SQLite uses the string pointed to by the
4504 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
4505 ** as the text of an error message.  ^SQLite interprets the error
4506 ** message string from sqlite3_result_error() as UTF-8. ^SQLite
4507 ** interprets the string from sqlite3_result_error16() as UTF-16 in native
4508 ** byte order.  ^If the third parameter to sqlite3_result_error()
4509 ** or sqlite3_result_error16() is negative then SQLite takes as the error
4510 ** message all text up through the first zero character.
4511 ** ^If the third parameter to sqlite3_result_error() or
4512 ** sqlite3_result_error16() is non-negative then SQLite takes that many
4513 ** bytes (not characters) from the 2nd parameter as the error message.
4514 ** ^The sqlite3_result_error() and sqlite3_result_error16()
4515 ** routines make a private copy of the error message text before
4516 ** they return.  Hence, the calling function can deallocate or
4517 ** modify the text after they return without harm.
4518 ** ^The sqlite3_result_error_code() function changes the error code
4519 ** returned by SQLite as a result of an error in a function.  ^By default,
4520 ** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()
4521 ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
4522 **
4523 ** ^The sqlite3_result_toobig() interface causes SQLite to throw an error
4524 ** indicating that a string or BLOB is too long to represent.
4525 **
4526 ** ^The sqlite3_result_nomem() interface causes SQLite to throw an error
4527 ** indicating that a memory allocation failed.
4528 **
4529 ** ^The sqlite3_result_int() interface sets the return value
4530 ** of the application-defined function to be the 32-bit signed integer
4531 ** value given in the 2nd argument.
4532 ** ^The sqlite3_result_int64() interface sets the return value
4533 ** of the application-defined function to be the 64-bit signed integer
4534 ** value given in the 2nd argument.
4535 **
4536 ** ^The sqlite3_result_null() interface sets the return value
4537 ** of the application-defined function to be NULL.
4538 **
4539 ** ^The sqlite3_result_text(), sqlite3_result_text16(),
4540 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
4541 ** set the return value of the application-defined function to be
4542 ** a text string which is represented as UTF-8, UTF-16 native byte order,
4543 ** UTF-16 little endian, or UTF-16 big endian, respectively.
4544 ** ^SQLite takes the text result from the application from
4545 ** the 2nd parameter of the sqlite3_result_text* interfaces.
4546 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4547 ** is negative, then SQLite takes result text from the 2nd parameter
4548 ** through the first zero character.
4549 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4550 ** is non-negative, then as many bytes (not characters) of the text
4551 ** pointed to by the 2nd parameter are taken as the application-defined
4552 ** function result.
4553 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4554 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
4555 ** function as the destructor on the text or BLOB result when it has
4556 ** finished using that result.
4557 ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
4558 ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
4559 ** assumes that the text or BLOB result is in constant space and does not
4560 ** copy the content of the parameter nor call a destructor on the content
4561 ** when it has finished using that result.
4562 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4563 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
4564 ** then SQLite makes a copy of the result into space obtained from
4565 ** from [sqlite3_malloc()] before it returns.
4566 **
4567 ** ^The sqlite3_result_value() interface sets the result of
4568 ** the application-defined function to be a copy the
4569 ** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The
4570 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
4571 ** so that the [sqlite3_value] specified in the parameter may change or
4572 ** be deallocated after sqlite3_result_value() returns without harm.
4573 ** ^A [protected sqlite3_value] object may always be used where an
4574 ** [unprotected sqlite3_value] object is required, so either
4575 ** kind of [sqlite3_value] object can be used with this interface.
4576 **
4577 ** If these routines are called from within the different thread
4578 ** than the one containing the application-defined function that received
4579 ** the [sqlite3_context] pointer, the results are undefined.
4580 */
4581 SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
4582 SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
4583 SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
4584 SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
4585 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
4586 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
4587 SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
4588 SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
4589 SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
4590 SQLITE_API void sqlite3_result_null(sqlite3_context*);
4591 SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
4592 SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
4593 SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
4594 SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
4595 SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
4596 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
4597
4598 /*
4599 ** CAPI3REF: Define New Collating Sequences
4600 **
4601 ** ^These functions add, remove, or modify a [collation] associated
4602 ** with the [database connection] specified as the first argument.
4603 **
4604 ** ^The name of the collation is a UTF-8 string
4605 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
4606 ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
4607 ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
4608 ** considered to be the same name.
4609 **
4610 ** ^(The third argument (eTextRep) must be one of the constants:
4611 ** <ul>
4612 ** <li> [SQLITE_UTF8],
4613 ** <li> [SQLITE_UTF16LE],
4614 ** <li> [SQLITE_UTF16BE],
4615 ** <li> [SQLITE_UTF16], or
4616 ** <li> [SQLITE_UTF16_ALIGNED].
4617 ** </ul>)^
4618 ** ^The eTextRep argument determines the encoding of strings passed
4619 ** to the collating function callback, xCallback.
4620 ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
4621 ** force strings to be UTF16 with native byte order.
4622 ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
4623 ** on an even byte address.
4624 **
4625 ** ^The fourth argument, pArg, is an application data pointer that is passed
4626 ** through as the first argument to the collating function callback.
4627 **
4628 ** ^The fifth argument, xCallback, is a pointer to the collating function.
4629 ** ^Multiple collating functions can be registered using the same name but
4630 ** with different eTextRep parameters and SQLite will use whichever
4631 ** function requires the least amount of data transformation.
4632 ** ^If the xCallback argument is NULL then the collating function is
4633 ** deleted.  ^When all collating functions having the same name are deleted,
4634 ** that collation is no longer usable.
4635 **
4636 ** ^The collating function callback is invoked with a copy of the pArg 
4637 ** application data pointer and with two strings in the encoding specified
4638 ** by the eTextRep argument.  The collating function must return an
4639 ** integer that is negative, zero, or positive
4640 ** if the first string is less than, equal to, or greater than the second,
4641 ** respectively.  A collating function must always return the same answer
4642 ** given the same inputs.  If two or more collating functions are registered
4643 ** to the same collation name (using different eTextRep values) then all
4644 ** must give an equivalent answer when invoked with equivalent strings.
4645 ** The collating function must obey the following properties for all
4646 ** strings A, B, and C:
4647 **
4648 ** <ol>
4649 ** <li> If A==B then B==A.
4650 ** <li> If A==B and B==C then A==C.
4651 ** <li> If A&lt;B THEN B&gt;A.
4652 ** <li> If A&lt;B and B&lt;C then A&lt;C.
4653 ** </ol>
4654 **
4655 ** If a collating function fails any of the above constraints and that
4656 ** collating function is  registered and used, then the behavior of SQLite
4657 ** is undefined.
4658 **
4659 ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
4660 ** with the addition that the xDestroy callback is invoked on pArg when
4661 ** the collating function is deleted.
4662 ** ^Collating functions are deleted when they are overridden by later
4663 ** calls to the collation creation functions or when the
4664 ** [database connection] is closed using [sqlite3_close()].
4665 **
4666 ** ^The xDestroy callback is <u>not</u> called if the 
4667 ** sqlite3_create_collation_v2() function fails.  Applications that invoke
4668 ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should 
4669 ** check the return code and dispose of the application data pointer
4670 ** themselves rather than expecting SQLite to deal with it for them.
4671 ** This is different from every other SQLite interface.  The inconsistency 
4672 ** is unfortunate but cannot be changed without breaking backwards 
4673 ** compatibility.
4674 **
4675 ** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
4676 */
4677 SQLITE_API int sqlite3_create_collation(
4678   sqlite3*, 
4679   const char *zName, 
4680   int eTextRep, 
4681   void *pArg,
4682   int(*xCompare)(void*,int,const void*,int,const void*)
4683 );
4684 SQLITE_API int sqlite3_create_collation_v2(
4685   sqlite3*, 
4686   const char *zName, 
4687   int eTextRep, 
4688   void *pArg,
4689   int(*xCompare)(void*,int,const void*,int,const void*),
4690   void(*xDestroy)(void*)
4691 );
4692 SQLITE_API int sqlite3_create_collation16(
4693   sqlite3*, 
4694   const void *zName,
4695   int eTextRep, 
4696   void *pArg,
4697   int(*xCompare)(void*,int,const void*,int,const void*)
4698 );
4699
4700 /*
4701 ** CAPI3REF: Collation Needed Callbacks
4702 **
4703 ** ^To avoid having to register all collation sequences before a database
4704 ** can be used, a single callback function may be registered with the
4705 ** [database connection] to be invoked whenever an undefined collation
4706 ** sequence is required.
4707 **
4708 ** ^If the function is registered using the sqlite3_collation_needed() API,
4709 ** then it is passed the names of undefined collation sequences as strings
4710 ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
4711 ** the names are passed as UTF-16 in machine native byte order.
4712 ** ^A call to either function replaces the existing collation-needed callback.
4713 **
4714 ** ^(When the callback is invoked, the first argument passed is a copy
4715 ** of the second argument to sqlite3_collation_needed() or
4716 ** sqlite3_collation_needed16().  The second argument is the database
4717 ** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
4718 ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
4719 ** sequence function required.  The fourth parameter is the name of the
4720 ** required collation sequence.)^
4721 **
4722 ** The callback function should register the desired collation using
4723 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
4724 ** [sqlite3_create_collation_v2()].
4725 */
4726 SQLITE_API int sqlite3_collation_needed(
4727   sqlite3*, 
4728   void*, 
4729   void(*)(void*,sqlite3*,int eTextRep,const char*)
4730 );
4731 SQLITE_API int sqlite3_collation_needed16(
4732   sqlite3*, 
4733   void*,
4734   void(*)(void*,sqlite3*,int eTextRep,const void*)
4735 );
4736
4737 #ifdef SQLITE_HAS_CODEC
4738 /*
4739 ** Specify the key for an encrypted database.  This routine should be
4740 ** called right after sqlite3_open().
4741 **
4742 ** The code to implement this API is not available in the public release
4743 ** of SQLite.
4744 */
4745 SQLITE_API int sqlite3_key(
4746   sqlite3 *db,                   /* Database to be rekeyed */
4747   const void *pKey, int nKey     /* The key */
4748 );
4749
4750 /*
4751 ** Change the key on an open database.  If the current database is not
4752 ** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
4753 ** database is decrypted.
4754 **
4755 ** The code to implement this API is not available in the public release
4756 ** of SQLite.
4757 */
4758 SQLITE_API int sqlite3_rekey(
4759   sqlite3 *db,                   /* Database to be rekeyed */
4760   const void *pKey, int nKey     /* The new key */
4761 );
4762
4763 /*
4764 ** Specify the activation key for a SEE database.  Unless 
4765 ** activated, none of the SEE routines will work.
4766 */
4767 SQLITE_API void sqlite3_activate_see(
4768   const char *zPassPhrase        /* Activation phrase */
4769 );
4770 #endif
4771
4772 #ifdef SQLITE_ENABLE_CEROD
4773 /*
4774 ** Specify the activation key for a CEROD database.  Unless 
4775 ** activated, none of the CEROD routines will work.
4776 */
4777 SQLITE_API void sqlite3_activate_cerod(
4778   const char *zPassPhrase        /* Activation phrase */
4779 );
4780 #endif
4781
4782 /*
4783 ** CAPI3REF: Suspend Execution For A Short Time
4784 **
4785 ** The sqlite3_sleep() function causes the current thread to suspend execution
4786 ** for at least a number of milliseconds specified in its parameter.
4787 **
4788 ** If the operating system does not support sleep requests with
4789 ** millisecond time resolution, then the time will be rounded up to
4790 ** the nearest second. The number of milliseconds of sleep actually
4791 ** requested from the operating system is returned.
4792 **
4793 ** ^SQLite implements this interface by calling the xSleep()
4794 ** method of the default [sqlite3_vfs] object.  If the xSleep() method
4795 ** of the default VFS is not implemented correctly, or not implemented at
4796 ** all, then the behavior of sqlite3_sleep() may deviate from the description
4797 ** in the previous paragraphs.
4798 */
4799 SQLITE_API int sqlite3_sleep(int);
4800
4801 /*
4802 ** CAPI3REF: Name Of The Folder Holding Temporary Files
4803 **
4804 ** ^(If this global variable is made to point to a string which is
4805 ** the name of a folder (a.k.a. directory), then all temporary files
4806 ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
4807 ** will be placed in that directory.)^  ^If this variable
4808 ** is a NULL pointer, then SQLite performs a search for an appropriate
4809 ** temporary file directory.
4810 **
4811 ** It is not safe to read or modify this variable in more than one
4812 ** thread at a time.  It is not safe to read or modify this variable
4813 ** if a [database connection] is being used at the same time in a separate
4814 ** thread.
4815 ** It is intended that this variable be set once
4816 ** as part of process initialization and before any SQLite interface
4817 ** routines have been called and that this variable remain unchanged
4818 ** thereafter.
4819 **
4820 ** ^The [temp_store_directory pragma] may modify this variable and cause
4821 ** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
4822 ** the [temp_store_directory pragma] always assumes that any string
4823 ** that this variable points to is held in memory obtained from 
4824 ** [sqlite3_malloc] and the pragma may attempt to free that memory
4825 ** using [sqlite3_free].
4826 ** Hence, if this variable is modified directly, either it should be
4827 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
4828 ** or else the use of the [temp_store_directory pragma] should be avoided.
4829 */
4830 SQLITE_API char *sqlite3_temp_directory;
4831
4832 /*
4833 ** CAPI3REF: Test For Auto-Commit Mode
4834 ** KEYWORDS: {autocommit mode}
4835 **
4836 ** ^The sqlite3_get_autocommit() interface returns non-zero or
4837 ** zero if the given database connection is or is not in autocommit mode,
4838 ** respectively.  ^Autocommit mode is on by default.
4839 ** ^Autocommit mode is disabled by a [BEGIN] statement.
4840 ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
4841 **
4842 ** If certain kinds of errors occur on a statement within a multi-statement
4843 ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
4844 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
4845 ** transaction might be rolled back automatically.  The only way to
4846 ** find out whether SQLite automatically rolled back the transaction after
4847 ** an error is to use this function.
4848 **
4849 ** If another thread changes the autocommit status of the database
4850 ** connection while this routine is running, then the return value
4851 ** is undefined.
4852 */
4853 SQLITE_API int sqlite3_get_autocommit(sqlite3*);
4854
4855 /*
4856 ** CAPI3REF: Find The Database Handle Of A Prepared Statement
4857 **
4858 ** ^The sqlite3_db_handle interface returns the [database connection] handle
4859 ** to which a [prepared statement] belongs.  ^The [database connection]
4860 ** returned by sqlite3_db_handle is the same [database connection]
4861 ** that was the first argument
4862 ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
4863 ** create the statement in the first place.
4864 */
4865 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
4866
4867 /*
4868 ** CAPI3REF: Find the next prepared statement
4869 **
4870 ** ^This interface returns a pointer to the next [prepared statement] after
4871 ** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL
4872 ** then this interface returns a pointer to the first prepared statement
4873 ** associated with the database connection pDb.  ^If no prepared statement
4874 ** satisfies the conditions of this routine, it returns NULL.
4875 **
4876 ** The [database connection] pointer D in a call to
4877 ** [sqlite3_next_stmt(D,S)] must refer to an open database
4878 ** connection and in particular must not be a NULL pointer.
4879 */
4880 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
4881
4882 /*
4883 ** CAPI3REF: Commit And Rollback Notification Callbacks
4884 **
4885 ** ^The sqlite3_commit_hook() interface registers a callback
4886 ** function to be invoked whenever a transaction is [COMMIT | committed].
4887 ** ^Any callback set by a previous call to sqlite3_commit_hook()
4888 ** for the same database connection is overridden.
4889 ** ^The sqlite3_rollback_hook() interface registers a callback
4890 ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
4891 ** ^Any callback set by a previous call to sqlite3_rollback_hook()
4892 ** for the same database connection is overridden.
4893 ** ^The pArg argument is passed through to the callback.
4894 ** ^If the callback on a commit hook function returns non-zero,
4895 ** then the commit is converted into a rollback.
4896 **
4897 ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
4898 ** return the P argument from the previous call of the same function
4899 ** on the same [database connection] D, or NULL for
4900 ** the first call for each function on D.
4901 **
4902 ** The callback implementation must not do anything that will modify
4903 ** the database connection that invoked the callback.  Any actions
4904 ** to modify the database connection must be deferred until after the
4905 ** completion of the [sqlite3_step()] call that triggered the commit
4906 ** or rollback hook in the first place.
4907 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
4908 ** database connections for the meaning of "modify" in this paragraph.
4909 **
4910 ** ^Registering a NULL function disables the callback.
4911 **
4912 ** ^When the commit hook callback routine returns zero, the [COMMIT]
4913 ** operation is allowed to continue normally.  ^If the commit hook
4914 ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
4915 ** ^The rollback hook is invoked on a rollback that results from a commit
4916 ** hook returning non-zero, just as it would be with any other rollback.
4917 **
4918 ** ^For the purposes of this API, a transaction is said to have been
4919 ** rolled back if an explicit "ROLLBACK" statement is executed, or
4920 ** an error or constraint causes an implicit rollback to occur.
4921 ** ^The rollback callback is not invoked if a transaction is
4922 ** automatically rolled back because the database connection is closed.
4923 **
4924 ** See also the [sqlite3_update_hook()] interface.
4925 */
4926 SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
4927 SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
4928
4929 /*
4930 ** CAPI3REF: Data Change Notification Callbacks
4931 **
4932 ** ^The sqlite3_update_hook() interface registers a callback function
4933 ** with the [database connection] identified by the first argument
4934 ** to be invoked whenever a row is updated, inserted or deleted.
4935 ** ^Any callback set by a previous call to this function
4936 ** for the same database connection is overridden.
4937 **
4938 ** ^The second argument is a pointer to the function to invoke when a
4939 ** row is updated, inserted or deleted.
4940 ** ^The first argument to the callback is a copy of the third argument
4941 ** to sqlite3_update_hook().
4942 ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
4943 ** or [SQLITE_UPDATE], depending on the operation that caused the callback
4944 ** to be invoked.
4945 ** ^The third and fourth arguments to the callback contain pointers to the
4946 ** database and table name containing the affected row.
4947 ** ^The final callback parameter is the [rowid] of the row.
4948 ** ^In the case of an update, this is the [rowid] after the update takes place.
4949 **
4950 ** ^(The update hook is not invoked when internal system tables are
4951 ** modified (i.e. sqlite_master and sqlite_sequence).)^
4952 **
4953 ** ^In the current implementation, the update hook
4954 ** is not invoked when duplication rows are deleted because of an
4955 ** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook
4956 ** invoked when rows are deleted using the [truncate optimization].
4957 ** The exceptions defined in this paragraph might change in a future
4958 ** release of SQLite.
4959 **
4960 ** The update hook implementation must not do anything that will modify
4961 ** the database connection that invoked the update hook.  Any actions
4962 ** to modify the database connection must be deferred until after the
4963 ** completion of the [sqlite3_step()] call that triggered the update hook.
4964 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
4965 ** database connections for the meaning of "modify" in this paragraph.
4966 **
4967 ** ^The sqlite3_update_hook(D,C,P) function
4968 ** returns the P argument from the previous call
4969 ** on the same [database connection] D, or NULL for
4970 ** the first call on D.
4971 **
4972 ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
4973 ** interfaces.
4974 */
4975 SQLITE_API void *sqlite3_update_hook(
4976   sqlite3*, 
4977   void(*)(void *,int ,char const *,char const *,sqlite3_int64),
4978   void*
4979 );
4980
4981 /*
4982 ** CAPI3REF: Enable Or Disable Shared Pager Cache
4983 ** KEYWORDS: {shared cache}
4984 **
4985 ** ^(This routine enables or disables the sharing of the database cache
4986 ** and schema data structures between [database connection | connections]
4987 ** to the same database. Sharing is enabled if the argument is true
4988 ** and disabled if the argument is false.)^
4989 **
4990 ** ^Cache sharing is enabled and disabled for an entire process.
4991 ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
4992 ** sharing was enabled or disabled for each thread separately.
4993 **
4994 ** ^(The cache sharing mode set by this interface effects all subsequent
4995 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
4996 ** Existing database connections continue use the sharing mode
4997 ** that was in effect at the time they were opened.)^
4998 **
4999 ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
5000 ** successfully.  An [error code] is returned otherwise.)^
5001 **
5002 ** ^Shared cache is disabled by default. But this might change in
5003 ** future releases of SQLite.  Applications that care about shared
5004 ** cache setting should set it explicitly.
5005 **
5006 ** See Also:  [SQLite Shared-Cache Mode]
5007 */
5008 SQLITE_API int sqlite3_enable_shared_cache(int);
5009
5010 /*
5011 ** CAPI3REF: Attempt To Free Heap Memory
5012 **
5013 ** ^The sqlite3_release_memory() interface attempts to free N bytes
5014 ** of heap memory by deallocating non-essential memory allocations
5015 ** held by the database library.   Memory used to cache database
5016 ** pages to improve performance is an example of non-essential memory.
5017 ** ^sqlite3_release_memory() returns the number of bytes actually freed,
5018 ** which might be more or less than the amount requested.
5019 ** ^The sqlite3_release_memory() routine is a no-op returning zero
5020 ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5021 */
5022 SQLITE_API int sqlite3_release_memory(int);
5023
5024 /*
5025 ** CAPI3REF: Impose A Limit On Heap Size
5026 **
5027 ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
5028 ** soft limit on the amount of heap memory that may be allocated by SQLite.
5029 ** ^SQLite strives to keep heap memory utilization below the soft heap
5030 ** limit by reducing the number of pages held in the page cache
5031 ** as heap memory usages approaches the limit.
5032 ** ^The soft heap limit is "soft" because even though SQLite strives to stay
5033 ** below the limit, it will exceed the limit rather than generate
5034 ** an [SQLITE_NOMEM] error.  In other words, the soft heap limit 
5035 ** is advisory only.
5036 **
5037 ** ^The return value from sqlite3_soft_heap_limit64() is the size of
5038 ** the soft heap limit prior to the call.  ^If the argument N is negative
5039 ** then no change is made to the soft heap limit.  Hence, the current
5040 ** size of the soft heap limit can be determined by invoking
5041 ** sqlite3_soft_heap_limit64() with a negative argument.
5042 **
5043 ** ^If the argument N is zero then the soft heap limit is disabled.
5044 **
5045 ** ^(The soft heap limit is not enforced in the current implementation
5046 ** if one or more of following conditions are true:
5047 **
5048 ** <ul>
5049 ** <li> The soft heap limit is set to zero.
5050 ** <li> Memory accounting is disabled using a combination of the
5051 **      [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
5052 **      the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
5053 ** <li> An alternative page cache implementation is specified using
5054 **      [sqlite3_config]([SQLITE_CONFIG_PCACHE],...).
5055 ** <li> The page cache allocates from its own memory pool supplied
5056 **      by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
5057 **      from the heap.
5058 ** </ul>)^
5059 **
5060 ** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
5061 ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
5062 ** compile-time option is invoked.  With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
5063 ** the soft heap limit is enforced on every memory allocation.  Without
5064 ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
5065 ** when memory is allocated by the page cache.  Testing suggests that because
5066 ** the page cache is the predominate memory user in SQLite, most
5067 ** applications will achieve adequate soft heap limit enforcement without
5068 ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5069 **
5070 ** The circumstances under which SQLite will enforce the soft heap limit may
5071 ** changes in future releases of SQLite.
5072 */
5073 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
5074
5075 /*
5076 ** CAPI3REF: Deprecated Soft Heap Limit Interface
5077 ** DEPRECATED
5078 **
5079 ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
5080 ** interface.  This routine is provided for historical compatibility
5081 ** only.  All new applications should use the
5082 ** [sqlite3_soft_heap_limit64()] interface rather than this one.
5083 */
5084 SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
5085
5086
5087 /*
5088 ** CAPI3REF: Extract Metadata About A Column Of A Table
5089 **
5090 ** ^This routine returns metadata about a specific column of a specific
5091 ** database table accessible using the [database connection] handle
5092 ** passed as the first function argument.
5093 **
5094 ** ^The column is identified by the second, third and fourth parameters to
5095 ** this function. ^The second parameter is either the name of the database
5096 ** (i.e. "main", "temp", or an attached database) containing the specified
5097 ** table or NULL. ^If it is NULL, then all attached databases are searched
5098 ** for the table using the same algorithm used by the database engine to
5099 ** resolve unqualified table references.
5100 **
5101 ** ^The third and fourth parameters to this function are the table and column
5102 ** name of the desired column, respectively. Neither of these parameters
5103 ** may be NULL.
5104 **
5105 ** ^Metadata is returned by writing to the memory locations passed as the 5th
5106 ** and subsequent parameters to this function. ^Any of these arguments may be
5107 ** NULL, in which case the corresponding element of metadata is omitted.
5108 **
5109 ** ^(<blockquote>
5110 ** <table border="1">
5111 ** <tr><th> Parameter <th> Output<br>Type <th>  Description
5112 **
5113 ** <tr><td> 5th <td> const char* <td> Data type
5114 ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
5115 ** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
5116 ** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
5117 ** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]
5118 ** </table>
5119 ** </blockquote>)^
5120 **
5121 ** ^The memory pointed to by the character pointers returned for the
5122 ** declaration type and collation sequence is valid only until the next
5123 ** call to any SQLite API function.
5124 **
5125 ** ^If the specified table is actually a view, an [error code] is returned.
5126 **
5127 ** ^If the specified column is "rowid", "oid" or "_rowid_" and an
5128 ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
5129 ** parameters are set for the explicitly declared column. ^(If there is no
5130 ** explicitly declared [INTEGER PRIMARY KEY] column, then the output
5131 ** parameters are set as follows:
5132 **
5133 ** <pre>
5134 **     data type: "INTEGER"
5135 **     collation sequence: "BINARY"
5136 **     not null: 0
5137 **     primary key: 1
5138 **     auto increment: 0
5139 ** </pre>)^
5140 **
5141 ** ^(This function may load one or more schemas from database files. If an
5142 ** error occurs during this process, or if the requested table or column
5143 ** cannot be found, an [error code] is returned and an error message left
5144 ** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
5145 **
5146 ** ^This API is only available if the library was compiled with the
5147 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
5148 */
5149 SQLITE_API int sqlite3_table_column_metadata(
5150   sqlite3 *db,                /* Connection handle */
5151   const char *zDbName,        /* Database name or NULL */
5152   const char *zTableName,     /* Table name */
5153   const char *zColumnName,    /* Column name */
5154   char const **pzDataType,    /* OUTPUT: Declared data type */
5155   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
5156   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
5157   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
5158   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
5159 );
5160
5161 /*
5162 ** CAPI3REF: Load An Extension
5163 **
5164 ** ^This interface loads an SQLite extension library from the named file.
5165 **
5166 ** ^The sqlite3_load_extension() interface attempts to load an
5167 ** SQLite extension library contained in the file zFile.
5168 **
5169 ** ^The entry point is zProc.
5170 ** ^zProc may be 0, in which case the name of the entry point
5171 ** defaults to "sqlite3_extension_init".
5172 ** ^The sqlite3_load_extension() interface returns
5173 ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
5174 ** ^If an error occurs and pzErrMsg is not 0, then the
5175 ** [sqlite3_load_extension()] interface shall attempt to
5176 ** fill *pzErrMsg with error message text stored in memory
5177 ** obtained from [sqlite3_malloc()]. The calling function
5178 ** should free this memory by calling [sqlite3_free()].
5179 **
5180 ** ^Extension loading must be enabled using
5181 ** [sqlite3_enable_load_extension()] prior to calling this API,
5182 ** otherwise an error will be returned.
5183 **
5184 ** See also the [load_extension() SQL function].
5185 */
5186 SQLITE_API int sqlite3_load_extension(
5187   sqlite3 *db,          /* Load the extension into this database connection */
5188   const char *zFile,    /* Name of the shared library containing extension */
5189   const char *zProc,    /* Entry point.  Derived from zFile if 0 */
5190   char **pzErrMsg       /* Put error message here if not 0 */
5191 );
5192
5193 /*
5194 ** CAPI3REF: Enable Or Disable Extension Loading
5195 **
5196 ** ^So as not to open security holes in older applications that are
5197 ** unprepared to deal with extension loading, and as a means of disabling
5198 ** extension loading while evaluating user-entered SQL, the following API
5199 ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
5200 **
5201 ** ^Extension loading is off by default. See ticket #1863.
5202 ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
5203 ** to turn extension loading on and call it with onoff==0 to turn
5204 ** it back off again.
5205 */
5206 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
5207
5208 /*
5209 ** CAPI3REF: Automatically Load Statically Linked Extensions
5210 **
5211 ** ^This interface causes the xEntryPoint() function to be invoked for
5212 ** each new [database connection] that is created.  The idea here is that
5213 ** xEntryPoint() is the entry point for a statically linked SQLite extension
5214 ** that is to be automatically loaded into all new database connections.
5215 **
5216 ** ^(Even though the function prototype shows that xEntryPoint() takes
5217 ** no arguments and returns void, SQLite invokes xEntryPoint() with three
5218 ** arguments and expects and integer result as if the signature of the
5219 ** entry point where as follows:
5220 **
5221 ** <blockquote><pre>
5222 ** &nbsp;  int xEntryPoint(
5223 ** &nbsp;    sqlite3 *db,
5224 ** &nbsp;    const char **pzErrMsg,
5225 ** &nbsp;    const struct sqlite3_api_routines *pThunk
5226 ** &nbsp;  );
5227 ** </pre></blockquote>)^
5228 **
5229 ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
5230 ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
5231 ** and return an appropriate [error code].  ^SQLite ensures that *pzErrMsg
5232 ** is NULL before calling the xEntryPoint().  ^SQLite will invoke
5233 ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns.  ^If any
5234 ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
5235 ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
5236 **
5237 ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
5238 ** on the list of automatic extensions is a harmless no-op. ^No entry point
5239 ** will be called more than once for each database connection that is opened.
5240 **
5241 ** See also: [sqlite3_reset_auto_extension()].
5242 */
5243 SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
5244
5245 /*
5246 ** CAPI3REF: Reset Automatic Extension Loading
5247 **
5248 ** ^This interface disables all automatic extensions previously
5249 ** registered using [sqlite3_auto_extension()].
5250 */
5251 SQLITE_API void sqlite3_reset_auto_extension(void);
5252
5253 /*
5254 ** The interface to the virtual-table mechanism is currently considered
5255 ** to be experimental.  The interface might change in incompatible ways.
5256 ** If this is a problem for you, do not use the interface at this time.
5257 **
5258 ** When the virtual-table mechanism stabilizes, we will declare the
5259 ** interface fixed, support it indefinitely, and remove this comment.
5260 */
5261
5262 /*
5263 ** Structures used by the virtual table interface
5264 */
5265 typedef struct sqlite3_vtab sqlite3_vtab;
5266 typedef struct sqlite3_index_info sqlite3_index_info;
5267 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
5268 typedef struct sqlite3_module sqlite3_module;
5269
5270 /*
5271 ** CAPI3REF: Virtual Table Object
5272 ** KEYWORDS: sqlite3_module {virtual table module}
5273 **
5274 ** This structure, sometimes called a "virtual table module", 
5275 ** defines the implementation of a [virtual tables].  
5276 ** This structure consists mostly of methods for the module.
5277 **
5278 ** ^A virtual table module is created by filling in a persistent
5279 ** instance of this structure and passing a pointer to that instance
5280 ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
5281 ** ^The registration remains valid until it is replaced by a different
5282 ** module or until the [database connection] closes.  The content
5283 ** of this structure must not change while it is registered with
5284 ** any database connection.
5285 */
5286 struct sqlite3_module {
5287   int iVersion;
5288   int (*xCreate)(sqlite3*, void *pAux,
5289                int argc, const char *const*argv,
5290                sqlite3_vtab **ppVTab, char**);
5291   int (*xConnect)(sqlite3*, void *pAux,
5292                int argc, const char *const*argv,
5293                sqlite3_vtab **ppVTab, char**);
5294   int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
5295   int (*xDisconnect)(sqlite3_vtab *pVTab);
5296   int (*xDestroy)(sqlite3_vtab *pVTab);
5297   int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
5298   int (*xClose)(sqlite3_vtab_cursor*);
5299   int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
5300                 int argc, sqlite3_value **argv);
5301   int (*xNext)(sqlite3_vtab_cursor*);
5302   int (*xEof)(sqlite3_vtab_cursor*);
5303   int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
5304   int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
5305   int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
5306   int (*xBegin)(sqlite3_vtab *pVTab);
5307   int (*xSync)(sqlite3_vtab *pVTab);
5308   int (*xCommit)(sqlite3_vtab *pVTab);
5309   int (*xRollback)(sqlite3_vtab *pVTab);
5310   int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
5311                        void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
5312                        void **ppArg);
5313   int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
5314   /* The methods above are in version 1 of the sqlite_module object. Those 
5315   ** below are for version 2 and greater. */
5316   int (*xSavepoint)(sqlite3_vtab *pVTab, int);
5317   int (*xRelease)(sqlite3_vtab *pVTab, int);
5318   int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
5319 };
5320
5321 /*
5322 ** CAPI3REF: Virtual Table Indexing Information
5323 ** KEYWORDS: sqlite3_index_info
5324 **
5325 ** The sqlite3_index_info structure and its substructures is used as part
5326 ** of the [virtual table] interface to
5327 ** pass information into and receive the reply from the [xBestIndex]
5328 ** method of a [virtual table module].  The fields under **Inputs** are the
5329 ** inputs to xBestIndex and are read-only.  xBestIndex inserts its
5330 ** results into the **Outputs** fields.
5331 **
5332 ** ^(The aConstraint[] array records WHERE clause constraints of the form:
5333 **
5334 ** <blockquote>column OP expr</blockquote>
5335 **
5336 ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
5337 ** stored in aConstraint[].op using one of the
5338 ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
5339 ** ^(The index of the column is stored in
5340 ** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
5341 ** expr on the right-hand side can be evaluated (and thus the constraint
5342 ** is usable) and false if it cannot.)^
5343 **
5344 ** ^The optimizer automatically inverts terms of the form "expr OP column"
5345 ** and makes other simplifications to the WHERE clause in an attempt to
5346 ** get as many WHERE clause terms into the form shown above as possible.
5347 ** ^The aConstraint[] array only reports WHERE clause terms that are
5348 ** relevant to the particular virtual table being queried.
5349 **
5350 ** ^Information about the ORDER BY clause is stored in aOrderBy[].
5351 ** ^Each term of aOrderBy records a column of the ORDER BY clause.
5352 **
5353 ** The [xBestIndex] method must fill aConstraintUsage[] with information
5354 ** about what parameters to pass to xFilter.  ^If argvIndex>0 then
5355 ** the right-hand side of the corresponding aConstraint[] is evaluated
5356 ** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit
5357 ** is true, then the constraint is assumed to be fully handled by the
5358 ** virtual table and is not checked again by SQLite.)^
5359 **
5360 ** ^The idxNum and idxPtr values are recorded and passed into the
5361 ** [xFilter] method.
5362 ** ^[sqlite3_free()] is used to free idxPtr if and only if
5363 ** needToFreeIdxPtr is true.
5364 **
5365 ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
5366 ** the correct order to satisfy the ORDER BY clause so that no separate
5367 ** sorting step is required.
5368 **
5369 ** ^The estimatedCost value is an estimate of the cost of doing the
5370 ** particular lookup.  A full scan of a table with N entries should have
5371 ** a cost of N.  A binary search of a table of N entries should have a
5372 ** cost of approximately log(N).
5373 */
5374 struct sqlite3_index_info {
5375   /* Inputs */
5376   int nConstraint;           /* Number of entries in aConstraint */
5377   struct sqlite3_index_constraint {
5378      int iColumn;              /* Column on left-hand side of constraint */
5379      unsigned char op;         /* Constraint operator */
5380      unsigned char usable;     /* True if this constraint is usable */
5381      int iTermOffset;          /* Used internally - xBestIndex should ignore */
5382   } *aConstraint;            /* Table of WHERE clause constraints */
5383   int nOrderBy;              /* Number of terms in the ORDER BY clause */
5384   struct sqlite3_index_orderby {
5385      int iColumn;              /* Column number */
5386      unsigned char desc;       /* True for DESC.  False for ASC. */
5387   } *aOrderBy;               /* The ORDER BY clause */
5388   /* Outputs */
5389   struct sqlite3_index_constraint_usage {
5390     int argvIndex;           /* if >0, constraint is part of argv to xFilter */
5391     unsigned char omit;      /* Do not code a test for this constraint */
5392   } *aConstraintUsage;
5393   int idxNum;                /* Number used to identify the index */
5394   char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
5395   int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
5396   int orderByConsumed;       /* True if output is already ordered */
5397   double estimatedCost;      /* Estimated cost of using this index */
5398 };
5399
5400 /*
5401 ** CAPI3REF: Virtual Table Constraint Operator Codes
5402 **
5403 ** These macros defined the allowed values for the
5404 ** [sqlite3_index_info].aConstraint[].op field.  Each value represents
5405 ** an operator that is part of a constraint term in the wHERE clause of
5406 ** a query that uses a [virtual table].
5407 */
5408 #define SQLITE_INDEX_CONSTRAINT_EQ    2
5409 #define SQLITE_INDEX_CONSTRAINT_GT    4
5410 #define SQLITE_INDEX_CONSTRAINT_LE    8
5411 #define SQLITE_INDEX_CONSTRAINT_LT    16
5412 #define SQLITE_INDEX_CONSTRAINT_GE    32
5413 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
5414
5415 /*
5416 ** CAPI3REF: Register A Virtual Table Implementation
5417 **
5418 ** ^These routines are used to register a new [virtual table module] name.
5419 ** ^Module names must be registered before
5420 ** creating a new [virtual table] using the module and before using a
5421 ** preexisting [virtual table] for the module.
5422 **
5423 ** ^The module name is registered on the [database connection] specified
5424 ** by the first parameter.  ^The name of the module is given by the 
5425 ** second parameter.  ^The third parameter is a pointer to
5426 ** the implementation of the [virtual table module].   ^The fourth
5427 ** parameter is an arbitrary client data pointer that is passed through
5428 ** into the [xCreate] and [xConnect] methods of the virtual table module
5429 ** when a new virtual table is be being created or reinitialized.
5430 **
5431 ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
5432 ** is a pointer to a destructor for the pClientData.  ^SQLite will
5433 ** invoke the destructor function (if it is not NULL) when SQLite
5434 ** no longer needs the pClientData pointer.  ^The destructor will also
5435 ** be invoked if the call to sqlite3_create_module_v2() fails.
5436 ** ^The sqlite3_create_module()
5437 ** interface is equivalent to sqlite3_create_module_v2() with a NULL
5438 ** destructor.
5439 */
5440 SQLITE_API int sqlite3_create_module(
5441   sqlite3 *db,               /* SQLite connection to register module with */
5442   const char *zName,         /* Name of the module */
5443   const sqlite3_module *p,   /* Methods for the module */
5444   void *pClientData          /* Client data for xCreate/xConnect */
5445 );
5446 SQLITE_API int sqlite3_create_module_v2(
5447   sqlite3 *db,               /* SQLite connection to register module with */
5448   const char *zName,         /* Name of the module */
5449   const sqlite3_module *p,   /* Methods for the module */
5450   void *pClientData,         /* Client data for xCreate/xConnect */
5451   void(*xDestroy)(void*)     /* Module destructor function */
5452 );
5453
5454 /*
5455 ** CAPI3REF: Virtual Table Instance Object
5456 ** KEYWORDS: sqlite3_vtab
5457 **
5458 ** Every [virtual table module] implementation uses a subclass
5459 ** of this object to describe a particular instance
5460 ** of the [virtual table].  Each subclass will
5461 ** be tailored to the specific needs of the module implementation.
5462 ** The purpose of this superclass is to define certain fields that are
5463 ** common to all module implementations.
5464 **
5465 ** ^Virtual tables methods can set an error message by assigning a
5466 ** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
5467 ** take care that any prior string is freed by a call to [sqlite3_free()]
5468 ** prior to assigning a new string to zErrMsg.  ^After the error message
5469 ** is delivered up to the client application, the string will be automatically
5470 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
5471 */
5472 struct sqlite3_vtab {
5473   const sqlite3_module *pModule;  /* The module for this virtual table */
5474   int nRef;                       /* NO LONGER USED */
5475   char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
5476   /* Virtual table implementations will typically add additional fields */
5477 };
5478
5479 /*
5480 ** CAPI3REF: Virtual Table Cursor Object
5481 ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
5482 **
5483 ** Every [virtual table module] implementation uses a subclass of the
5484 ** following structure to describe cursors that point into the
5485 ** [virtual table] and are used
5486 ** to loop through the virtual table.  Cursors are created using the
5487 ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
5488 ** by the [sqlite3_module.xClose | xClose] method.  Cursors are used
5489 ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
5490 ** of the module.  Each module implementation will define
5491 ** the content of a cursor structure to suit its own needs.
5492 **
5493 ** This superclass exists in order to define fields of the cursor that
5494 ** are common to all implementations.
5495 */
5496 struct sqlite3_vtab_cursor {
5497   sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
5498   /* Virtual table implementations will typically add additional fields */
5499 };
5500
5501 /*
5502 ** CAPI3REF: Declare The Schema Of A Virtual Table
5503 **
5504 ** ^The [xCreate] and [xConnect] methods of a
5505 ** [virtual table module] call this interface
5506 ** to declare the format (the names and datatypes of the columns) of
5507 ** the virtual tables they implement.
5508 */
5509 SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
5510
5511 /*
5512 ** CAPI3REF: Overload A Function For A Virtual Table
5513 **
5514 ** ^(Virtual tables can provide alternative implementations of functions
5515 ** using the [xFindFunction] method of the [virtual table module].  
5516 ** But global versions of those functions
5517 ** must exist in order to be overloaded.)^
5518 **
5519 ** ^(This API makes sure a global version of a function with a particular
5520 ** name and number of parameters exists.  If no such function exists
5521 ** before this API is called, a new function is created.)^  ^The implementation
5522 ** of the new function always causes an exception to be thrown.  So
5523 ** the new function is not good for anything by itself.  Its only
5524 ** purpose is to be a placeholder function that can be overloaded
5525 ** by a [virtual table].
5526 */
5527 SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
5528
5529 /*
5530 ** The interface to the virtual-table mechanism defined above (back up
5531 ** to a comment remarkably similar to this one) is currently considered
5532 ** to be experimental.  The interface might change in incompatible ways.
5533 ** If this is a problem for you, do not use the interface at this time.
5534 **
5535 ** When the virtual-table mechanism stabilizes, we will declare the
5536 ** interface fixed, support it indefinitely, and remove this comment.
5537 */
5538
5539 /*
5540 ** CAPI3REF: A Handle To An Open BLOB
5541 ** KEYWORDS: {BLOB handle} {BLOB handles}
5542 **
5543 ** An instance of this object represents an open BLOB on which
5544 ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
5545 ** ^Objects of this type are created by [sqlite3_blob_open()]
5546 ** and destroyed by [sqlite3_blob_close()].
5547 ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
5548 ** can be used to read or write small subsections of the BLOB.
5549 ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
5550 */
5551 typedef struct sqlite3_blob sqlite3_blob;
5552
5553 /*
5554 ** CAPI3REF: Open A BLOB For Incremental I/O
5555 **
5556 ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
5557 ** in row iRow, column zColumn, table zTable in database zDb;
5558 ** in other words, the same BLOB that would be selected by:
5559 **
5560 ** <pre>
5561 **     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
5562 ** </pre>)^
5563 **
5564 ** ^If the flags parameter is non-zero, then the BLOB is opened for read
5565 ** and write access. ^If it is zero, the BLOB is opened for read access.
5566 ** ^It is not possible to open a column that is part of an index or primary 
5567 ** key for writing. ^If [foreign key constraints] are enabled, it is 
5568 ** not possible to open a column that is part of a [child key] for writing.
5569 **
5570 ** ^Note that the database name is not the filename that contains
5571 ** the database but rather the symbolic name of the database that
5572 ** appears after the AS keyword when the database is connected using [ATTACH].
5573 ** ^For the main database file, the database name is "main".
5574 ** ^For TEMP tables, the database name is "temp".
5575 **
5576 ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
5577 ** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
5578 ** to be a null pointer.)^
5579 ** ^This function sets the [database connection] error code and message
5580 ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
5581 ** functions. ^Note that the *ppBlob variable is always initialized in a
5582 ** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
5583 ** regardless of the success or failure of this routine.
5584 **
5585 ** ^(If the row that a BLOB handle points to is modified by an
5586 ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
5587 ** then the BLOB handle is marked as "expired".
5588 ** This is true if any column of the row is changed, even a column
5589 ** other than the one the BLOB handle is open on.)^
5590 ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
5591 ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
5592 ** ^(Changes written into a BLOB prior to the BLOB expiring are not
5593 ** rolled back by the expiration of the BLOB.  Such changes will eventually
5594 ** commit if the transaction continues to completion.)^
5595 **
5596 ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
5597 ** the opened blob.  ^The size of a blob may not be changed by this
5598 ** interface.  Use the [UPDATE] SQL command to change the size of a
5599 ** blob.
5600 **
5601 ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
5602 ** and the built-in [zeroblob] SQL function can be used, if desired,
5603 ** to create an empty, zero-filled blob in which to read or write using
5604 ** this interface.
5605 **
5606 ** To avoid a resource leak, every open [BLOB handle] should eventually
5607 ** be released by a call to [sqlite3_blob_close()].
5608 */
5609 SQLITE_API int sqlite3_blob_open(
5610   sqlite3*,
5611   const char *zDb,
5612   const char *zTable,
5613   const char *zColumn,
5614   sqlite3_int64 iRow,
5615   int flags,
5616   sqlite3_blob **ppBlob
5617 );
5618
5619 /*
5620 ** CAPI3REF: Move a BLOB Handle to a New Row
5621 **
5622 ** ^This function is used to move an existing blob handle so that it points
5623 ** to a different row of the same database table. ^The new row is identified
5624 ** by the rowid value passed as the second argument. Only the row can be
5625 ** changed. ^The database, table and column on which the blob handle is open
5626 ** remain the same. Moving an existing blob handle to a new row can be
5627 ** faster than closing the existing handle and opening a new one.
5628 **
5629 ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
5630 ** it must exist and there must be either a blob or text value stored in
5631 ** the nominated column.)^ ^If the new row is not present in the table, or if
5632 ** it does not contain a blob or text value, or if another error occurs, an
5633 ** SQLite error code is returned and the blob handle is considered aborted.
5634 ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
5635 ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
5636 ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
5637 ** always returns zero.
5638 **
5639 ** ^This function sets the database handle error code and message.
5640 */
5641 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
5642
5643 /*
5644 ** CAPI3REF: Close A BLOB Handle
5645 **
5646 ** ^Closes an open [BLOB handle].
5647 **
5648 ** ^Closing a BLOB shall cause the current transaction to commit
5649 ** if there are no other BLOBs, no pending prepared statements, and the
5650 ** database connection is in [autocommit mode].
5651 ** ^If any writes were made to the BLOB, they might be held in cache
5652 ** until the close operation if they will fit.
5653 **
5654 ** ^(Closing the BLOB often forces the changes
5655 ** out to disk and so if any I/O errors occur, they will likely occur
5656 ** at the time when the BLOB is closed.  Any errors that occur during
5657 ** closing are reported as a non-zero return value.)^
5658 **
5659 ** ^(The BLOB is closed unconditionally.  Even if this routine returns
5660 ** an error code, the BLOB is still closed.)^
5661 **
5662 ** ^Calling this routine with a null pointer (such as would be returned
5663 ** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
5664 */
5665 SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
5666
5667 /*
5668 ** CAPI3REF: Return The Size Of An Open BLOB
5669 **
5670 ** ^Returns the size in bytes of the BLOB accessible via the 
5671 ** successfully opened [BLOB handle] in its only argument.  ^The
5672 ** incremental blob I/O routines can only read or overwriting existing
5673 ** blob content; they cannot change the size of a blob.
5674 **
5675 ** This routine only works on a [BLOB handle] which has been created
5676 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5677 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5678 ** to this routine results in undefined and probably undesirable behavior.
5679 */
5680 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
5681
5682 /*
5683 ** CAPI3REF: Read Data From A BLOB Incrementally
5684 **
5685 ** ^(This function is used to read data from an open [BLOB handle] into a
5686 ** caller-supplied buffer. N bytes of data are copied into buffer Z
5687 ** from the open BLOB, starting at offset iOffset.)^
5688 **
5689 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
5690 ** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is
5691 ** less than zero, [SQLITE_ERROR] is returned and no data is read.
5692 ** ^The size of the blob (and hence the maximum value of N+iOffset)
5693 ** can be determined using the [sqlite3_blob_bytes()] interface.
5694 **
5695 ** ^An attempt to read from an expired [BLOB handle] fails with an
5696 ** error code of [SQLITE_ABORT].
5697 **
5698 ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
5699 ** Otherwise, an [error code] or an [extended error code] is returned.)^
5700 **
5701 ** This routine only works on a [BLOB handle] which has been created
5702 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5703 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5704 ** to this routine results in undefined and probably undesirable behavior.
5705 **
5706 ** See also: [sqlite3_blob_write()].
5707 */
5708 SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
5709
5710 /*
5711 ** CAPI3REF: Write Data Into A BLOB Incrementally
5712 **
5713 ** ^This function is used to write data into an open [BLOB handle] from a
5714 ** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
5715 ** into the open BLOB, starting at offset iOffset.
5716 **
5717 ** ^If the [BLOB handle] passed as the first argument was not opened for
5718 ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
5719 ** this function returns [SQLITE_READONLY].
5720 **
5721 ** ^This function may only modify the contents of the BLOB; it is
5722 ** not possible to increase the size of a BLOB using this API.
5723 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
5724 ** [SQLITE_ERROR] is returned and no data is written.  ^If N is
5725 ** less than zero [SQLITE_ERROR] is returned and no data is written.
5726 ** The size of the BLOB (and hence the maximum value of N+iOffset)
5727 ** can be determined using the [sqlite3_blob_bytes()] interface.
5728 **
5729 ** ^An attempt to write to an expired [BLOB handle] fails with an
5730 ** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred
5731 ** before the [BLOB handle] expired are not rolled back by the
5732 ** expiration of the handle, though of course those changes might
5733 ** have been overwritten by the statement that expired the BLOB handle
5734 ** or by other independent statements.
5735 **
5736 ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
5737 ** Otherwise, an  [error code] or an [extended error code] is returned.)^
5738 **
5739 ** This routine only works on a [BLOB handle] which has been created
5740 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5741 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5742 ** to this routine results in undefined and probably undesirable behavior.
5743 **
5744 ** See also: [sqlite3_blob_read()].
5745 */
5746 SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
5747
5748 /*
5749 ** CAPI3REF: Virtual File System Objects
5750 **
5751 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
5752 ** that SQLite uses to interact
5753 ** with the underlying operating system.  Most SQLite builds come with a
5754 ** single default VFS that is appropriate for the host computer.
5755 ** New VFSes can be registered and existing VFSes can be unregistered.
5756 ** The following interfaces are provided.
5757 **
5758 ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
5759 ** ^Names are case sensitive.
5760 ** ^Names are zero-terminated UTF-8 strings.
5761 ** ^If there is no match, a NULL pointer is returned.
5762 ** ^If zVfsName is NULL then the default VFS is returned.
5763 **
5764 ** ^New VFSes are registered with sqlite3_vfs_register().
5765 ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
5766 ** ^The same VFS can be registered multiple times without injury.
5767 ** ^To make an existing VFS into the default VFS, register it again
5768 ** with the makeDflt flag set.  If two different VFSes with the
5769 ** same name are registered, the behavior is undefined.  If a
5770 ** VFS is registered with a name that is NULL or an empty string,
5771 ** then the behavior is undefined.
5772 **
5773 ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
5774 ** ^(If the default VFS is unregistered, another VFS is chosen as
5775 ** the default.  The choice for the new VFS is arbitrary.)^
5776 */
5777 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
5778 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
5779 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
5780
5781 /*
5782 ** CAPI3REF: Mutexes
5783 **
5784 ** The SQLite core uses these routines for thread
5785 ** synchronization. Though they are intended for internal
5786 ** use by SQLite, code that links against SQLite is
5787 ** permitted to use any of these routines.
5788 **
5789 ** The SQLite source code contains multiple implementations
5790 ** of these mutex routines.  An appropriate implementation
5791 ** is selected automatically at compile-time.  ^(The following
5792 ** implementations are available in the SQLite core:
5793 **
5794 ** <ul>
5795 ** <li>   SQLITE_MUTEX_OS2
5796 ** <li>   SQLITE_MUTEX_PTHREAD
5797 ** <li>   SQLITE_MUTEX_W32
5798 ** <li>   SQLITE_MUTEX_NOOP
5799 ** </ul>)^
5800 **
5801 ** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
5802 ** that does no real locking and is appropriate for use in
5803 ** a single-threaded application.  ^The SQLITE_MUTEX_OS2,
5804 ** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations
5805 ** are appropriate for use on OS/2, Unix, and Windows.
5806 **
5807 ** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
5808 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
5809 ** implementation is included with the library. In this case the
5810 ** application must supply a custom mutex implementation using the
5811 ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
5812 ** before calling sqlite3_initialize() or any other public sqlite3_
5813 ** function that calls sqlite3_initialize().)^
5814 **
5815 ** ^The sqlite3_mutex_alloc() routine allocates a new
5816 ** mutex and returns a pointer to it. ^If it returns NULL
5817 ** that means that a mutex could not be allocated.  ^SQLite
5818 ** will unwind its stack and return an error.  ^(The argument
5819 ** to sqlite3_mutex_alloc() is one of these integer constants:
5820 **
5821 ** <ul>
5822 ** <li>  SQLITE_MUTEX_FAST
5823 ** <li>  SQLITE_MUTEX_RECURSIVE
5824 ** <li>  SQLITE_MUTEX_STATIC_MASTER
5825 ** <li>  SQLITE_MUTEX_STATIC_MEM
5826 ** <li>  SQLITE_MUTEX_STATIC_MEM2
5827 ** <li>  SQLITE_MUTEX_STATIC_PRNG
5828 ** <li>  SQLITE_MUTEX_STATIC_LRU
5829 ** <li>  SQLITE_MUTEX_STATIC_LRU2
5830 ** </ul>)^
5831 **
5832 ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
5833 ** cause sqlite3_mutex_alloc() to create
5834 ** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
5835 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
5836 ** The mutex implementation does not need to make a distinction
5837 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
5838 ** not want to.  ^SQLite will only request a recursive mutex in
5839 ** cases where it really needs one.  ^If a faster non-recursive mutex
5840 ** implementation is available on the host platform, the mutex subsystem
5841 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
5842 **
5843 ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
5844 ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
5845 ** a pointer to a static preexisting mutex.  ^Six static mutexes are
5846 ** used by the current version of SQLite.  Future versions of SQLite
5847 ** may add additional static mutexes.  Static mutexes are for internal
5848 ** use by SQLite only.  Applications that use SQLite mutexes should
5849 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
5850 ** SQLITE_MUTEX_RECURSIVE.
5851 **
5852 ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
5853 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
5854 ** returns a different mutex on every call.  ^But for the static
5855 ** mutex types, the same mutex is returned on every call that has
5856 ** the same type number.
5857 **
5858 ** ^The sqlite3_mutex_free() routine deallocates a previously
5859 ** allocated dynamic mutex.  ^SQLite is careful to deallocate every
5860 ** dynamic mutex that it allocates.  The dynamic mutexes must not be in
5861 ** use when they are deallocated.  Attempting to deallocate a static
5862 ** mutex results in undefined behavior.  ^SQLite never deallocates
5863 ** a static mutex.
5864 **
5865 ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
5866 ** to enter a mutex.  ^If another thread is already within the mutex,
5867 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
5868 ** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
5869 ** upon successful entry.  ^(Mutexes created using
5870 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
5871 ** In such cases the,
5872 ** mutex must be exited an equal number of times before another thread
5873 ** can enter.)^  ^(If the same thread tries to enter any other
5874 ** kind of mutex more than once, the behavior is undefined.
5875 ** SQLite will never exhibit
5876 ** such behavior in its own use of mutexes.)^
5877 **
5878 ** ^(Some systems (for example, Windows 95) do not support the operation
5879 ** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
5880 ** will always return SQLITE_BUSY.  The SQLite core only ever uses
5881 ** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
5882 **
5883 ** ^The sqlite3_mutex_leave() routine exits a mutex that was
5884 ** previously entered by the same thread.   ^(The behavior
5885 ** is undefined if the mutex is not currently entered by the
5886 ** calling thread or is not currently allocated.  SQLite will
5887 ** never do either.)^
5888 **
5889 ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
5890 ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
5891 ** behave as no-ops.
5892 **
5893 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
5894 */
5895 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
5896 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
5897 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
5898 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
5899 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
5900
5901 /*
5902 ** CAPI3REF: Mutex Methods Object
5903 **
5904 ** An instance of this structure defines the low-level routines
5905 ** used to allocate and use mutexes.
5906 **
5907 ** Usually, the default mutex implementations provided by SQLite are
5908 ** sufficient, however the user has the option of substituting a custom
5909 ** implementation for specialized deployments or systems for which SQLite
5910 ** does not provide a suitable implementation. In this case, the user
5911 ** creates and populates an instance of this structure to pass
5912 ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
5913 ** Additionally, an instance of this structure can be used as an
5914 ** output variable when querying the system for the current mutex
5915 ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
5916 **
5917 ** ^The xMutexInit method defined by this structure is invoked as
5918 ** part of system initialization by the sqlite3_initialize() function.
5919 ** ^The xMutexInit routine is called by SQLite exactly once for each
5920 ** effective call to [sqlite3_initialize()].
5921 **
5922 ** ^The xMutexEnd method defined by this structure is invoked as
5923 ** part of system shutdown by the sqlite3_shutdown() function. The
5924 ** implementation of this method is expected to release all outstanding
5925 ** resources obtained by the mutex methods implementation, especially
5926 ** those obtained by the xMutexInit method.  ^The xMutexEnd()
5927 ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
5928 **
5929 ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
5930 ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
5931 ** xMutexNotheld) implement the following interfaces (respectively):
5932 **
5933 ** <ul>
5934 **   <li>  [sqlite3_mutex_alloc()] </li>
5935 **   <li>  [sqlite3_mutex_free()] </li>
5936 **   <li>  [sqlite3_mutex_enter()] </li>
5937 **   <li>  [sqlite3_mutex_try()] </li>
5938 **   <li>  [sqlite3_mutex_leave()] </li>
5939 **   <li>  [sqlite3_mutex_held()] </li>
5940 **   <li>  [sqlite3_mutex_notheld()] </li>
5941 ** </ul>)^
5942 **
5943 ** The only difference is that the public sqlite3_XXX functions enumerated
5944 ** above silently ignore any invocations that pass a NULL pointer instead
5945 ** of a valid mutex handle. The implementations of the methods defined
5946 ** by this structure are not required to handle this case, the results
5947 ** of passing a NULL pointer instead of a valid mutex handle are undefined
5948 ** (i.e. it is acceptable to provide an implementation that segfaults if
5949 ** it is passed a NULL pointer).
5950 **
5951 ** The xMutexInit() method must be threadsafe.  ^It must be harmless to
5952 ** invoke xMutexInit() multiple times within the same process and without
5953 ** intervening calls to xMutexEnd().  Second and subsequent calls to
5954 ** xMutexInit() must be no-ops.
5955 **
5956 ** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
5957 ** and its associates).  ^Similarly, xMutexAlloc() must not use SQLite memory
5958 ** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite
5959 ** memory allocation for a fast or recursive mutex.
5960 **
5961 ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
5962 ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
5963 ** If xMutexInit fails in any way, it is expected to clean up after itself
5964 ** prior to returning.
5965 */
5966 typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
5967 struct sqlite3_mutex_methods {
5968   int (*xMutexInit)(void);
5969   int (*xMutexEnd)(void);
5970   sqlite3_mutex *(*xMutexAlloc)(int);
5971   void (*xMutexFree)(sqlite3_mutex *);
5972   void (*xMutexEnter)(sqlite3_mutex *);
5973   int (*xMutexTry)(sqlite3_mutex *);
5974   void (*xMutexLeave)(sqlite3_mutex *);
5975   int (*xMutexHeld)(sqlite3_mutex *);
5976   int (*xMutexNotheld)(sqlite3_mutex *);
5977 };
5978
5979 /*
5980 ** CAPI3REF: Mutex Verification Routines
5981 **
5982 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
5983 ** are intended for use inside assert() statements.  ^The SQLite core
5984 ** never uses these routines except inside an assert() and applications
5985 ** are advised to follow the lead of the core.  ^The SQLite core only
5986 ** provides implementations for these routines when it is compiled
5987 ** with the SQLITE_DEBUG flag.  ^External mutex implementations
5988 ** are only required to provide these routines if SQLITE_DEBUG is
5989 ** defined and if NDEBUG is not defined.
5990 **
5991 ** ^These routines should return true if the mutex in their argument
5992 ** is held or not held, respectively, by the calling thread.
5993 **
5994 ** ^The implementation is not required to provided versions of these
5995 ** routines that actually work. If the implementation does not provide working
5996 ** versions of these routines, it should at least provide stubs that always
5997 ** return true so that one does not get spurious assertion failures.
5998 **
5999 ** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
6000 ** the routine should return 1.   This seems counter-intuitive since
6001 ** clearly the mutex cannot be held if it does not exist.  But
6002 ** the reason the mutex does not exist is because the build is not
6003 ** using mutexes.  And we do not want the assert() containing the
6004 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
6005 ** the appropriate thing to do.  ^The sqlite3_mutex_notheld()
6006 ** interface should also return 1 when given a NULL pointer.
6007 */
6008 #ifndef NDEBUG
6009 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
6010 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
6011 #endif
6012
6013 /*
6014 ** CAPI3REF: Mutex Types
6015 **
6016 ** The [sqlite3_mutex_alloc()] interface takes a single argument
6017 ** which is one of these integer constants.
6018 **
6019 ** The set of static mutexes may change from one SQLite release to the
6020 ** next.  Applications that override the built-in mutex logic must be
6021 ** prepared to accommodate additional static mutexes.
6022 */
6023 #define SQLITE_MUTEX_FAST             0
6024 #define SQLITE_MUTEX_RECURSIVE        1
6025 #define SQLITE_MUTEX_STATIC_MASTER    2
6026 #define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
6027 #define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */
6028 #define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */
6029 #define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
6030 #define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
6031 #define SQLITE_MUTEX_STATIC_LRU2      7  /* NOT USED */
6032 #define SQLITE_MUTEX_STATIC_PMEM      7  /* sqlite3PageMalloc() */
6033
6034 /*
6035 ** CAPI3REF: Retrieve the mutex for a database connection
6036 **
6037 ** ^This interface returns a pointer the [sqlite3_mutex] object that 
6038 ** serializes access to the [database connection] given in the argument
6039 ** when the [threading mode] is Serialized.
6040 ** ^If the [threading mode] is Single-thread or Multi-thread then this
6041 ** routine returns a NULL pointer.
6042 */
6043 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
6044
6045 /*
6046 ** CAPI3REF: Low-Level Control Of Database Files
6047 **
6048 ** ^The [sqlite3_file_control()] interface makes a direct call to the
6049 ** xFileControl method for the [sqlite3_io_methods] object associated
6050 ** with a particular database identified by the second argument. ^The
6051 ** name of the database is "main" for the main database or "temp" for the
6052 ** TEMP database, or the name that appears after the AS keyword for
6053 ** databases that are added using the [ATTACH] SQL command.
6054 ** ^A NULL pointer can be used in place of "main" to refer to the
6055 ** main database file.
6056 ** ^The third and fourth parameters to this routine
6057 ** are passed directly through to the second and third parameters of
6058 ** the xFileControl method.  ^The return value of the xFileControl
6059 ** method becomes the return value of this routine.
6060 **
6061 ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
6062 ** a pointer to the underlying [sqlite3_file] object to be written into
6063 ** the space pointed to by the 4th parameter.  ^The SQLITE_FCNTL_FILE_POINTER
6064 ** case is a short-circuit path which does not actually invoke the
6065 ** underlying sqlite3_io_methods.xFileControl method.
6066 **
6067 ** ^If the second parameter (zDbName) does not match the name of any
6068 ** open database file, then SQLITE_ERROR is returned.  ^This error
6069 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
6070 ** or [sqlite3_errmsg()].  The underlying xFileControl method might
6071 ** also return SQLITE_ERROR.  There is no way to distinguish between
6072 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
6073 ** xFileControl method.
6074 **
6075 ** See also: [SQLITE_FCNTL_LOCKSTATE]
6076 */
6077 SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
6078
6079 /*
6080 ** CAPI3REF: Testing Interface
6081 **
6082 ** ^The sqlite3_test_control() interface is used to read out internal
6083 ** state of SQLite and to inject faults into SQLite for testing
6084 ** purposes.  ^The first parameter is an operation code that determines
6085 ** the number, meaning, and operation of all subsequent parameters.
6086 **
6087 ** This interface is not for use by applications.  It exists solely
6088 ** for verifying the correct operation of the SQLite library.  Depending
6089 ** on how the SQLite library is compiled, this interface might not exist.
6090 **
6091 ** The details of the operation codes, their meanings, the parameters
6092 ** they take, and what they do are all subject to change without notice.
6093 ** Unlike most of the SQLite API, this function is not guaranteed to
6094 ** operate consistently from one release to the next.
6095 */
6096 SQLITE_API int sqlite3_test_control(int op, ...);
6097
6098 /*
6099 ** CAPI3REF: Testing Interface Operation Codes
6100 **
6101 ** These constants are the valid operation code parameters used
6102 ** as the first argument to [sqlite3_test_control()].
6103 **
6104 ** These parameters and their meanings are subject to change
6105 ** without notice.  These values are for testing purposes only.
6106 ** Applications should not use any of these parameters or the
6107 ** [sqlite3_test_control()] interface.
6108 */
6109 #define SQLITE_TESTCTRL_FIRST                    5
6110 #define SQLITE_TESTCTRL_PRNG_SAVE                5
6111 #define SQLITE_TESTCTRL_PRNG_RESTORE             6
6112 #define SQLITE_TESTCTRL_PRNG_RESET               7
6113 #define SQLITE_TESTCTRL_BITVEC_TEST              8
6114 #define SQLITE_TESTCTRL_FAULT_INSTALL            9
6115 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
6116 #define SQLITE_TESTCTRL_PENDING_BYTE            11
6117 #define SQLITE_TESTCTRL_ASSERT                  12
6118 #define SQLITE_TESTCTRL_ALWAYS                  13
6119 #define SQLITE_TESTCTRL_RESERVE                 14
6120 #define SQLITE_TESTCTRL_OPTIMIZATIONS           15
6121 #define SQLITE_TESTCTRL_ISKEYWORD               16
6122 #define SQLITE_TESTCTRL_PGHDRSZ                 17
6123 #define SQLITE_TESTCTRL_SCRATCHMALLOC           18
6124 #define SQLITE_TESTCTRL_LOCALTIME_FAULT         19
6125 #define SQLITE_TESTCTRL_LAST                    19
6126
6127 /*
6128 ** CAPI3REF: SQLite Runtime Status
6129 **
6130 ** ^This interface is used to retrieve runtime status information
6131 ** about the performance of SQLite, and optionally to reset various
6132 ** highwater marks.  ^The first argument is an integer code for
6133 ** the specific parameter to measure.  ^(Recognized integer codes
6134 ** are of the form [status parameters | SQLITE_STATUS_...].)^
6135 ** ^The current value of the parameter is returned into *pCurrent.
6136 ** ^The highest recorded value is returned in *pHighwater.  ^If the
6137 ** resetFlag is true, then the highest record value is reset after
6138 ** *pHighwater is written.  ^(Some parameters do not record the highest
6139 ** value.  For those parameters
6140 ** nothing is written into *pHighwater and the resetFlag is ignored.)^
6141 ** ^(Other parameters record only the highwater mark and not the current
6142 ** value.  For these latter parameters nothing is written into *pCurrent.)^
6143 **
6144 ** ^The sqlite3_status() routine returns SQLITE_OK on success and a
6145 ** non-zero [error code] on failure.
6146 **
6147 ** This routine is threadsafe but is not atomic.  This routine can be
6148 ** called while other threads are running the same or different SQLite
6149 ** interfaces.  However the values returned in *pCurrent and
6150 ** *pHighwater reflect the status of SQLite at different points in time
6151 ** and it is possible that another thread might change the parameter
6152 ** in between the times when *pCurrent and *pHighwater are written.
6153 **
6154 ** See also: [sqlite3_db_status()]
6155 */
6156 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
6157
6158
6159 /*
6160 ** CAPI3REF: Status Parameters
6161 ** KEYWORDS: {status parameters}
6162 **
6163 ** These integer constants designate various run-time status parameters
6164 ** that can be returned by [sqlite3_status()].
6165 **
6166 ** <dl>
6167 ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
6168 ** <dd>This parameter is the current amount of memory checked out
6169 ** using [sqlite3_malloc()], either directly or indirectly.  The
6170 ** figure includes calls made to [sqlite3_malloc()] by the application
6171 ** and internal memory usage by the SQLite library.  Scratch memory
6172 ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
6173 ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
6174 ** this parameter.  The amount returned is the sum of the allocation
6175 ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
6176 **
6177 ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
6178 ** <dd>This parameter records the largest memory allocation request
6179 ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
6180 ** internal equivalents).  Only the value returned in the
6181 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
6182 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6183 **
6184 ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
6185 ** <dd>This parameter records the number of separate memory allocations
6186 ** currently checked out.</dd>)^
6187 **
6188 ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
6189 ** <dd>This parameter returns the number of pages used out of the
6190 ** [pagecache memory allocator] that was configured using 
6191 ** [SQLITE_CONFIG_PAGECACHE].  The
6192 ** value returned is in pages, not in bytes.</dd>)^
6193 **
6194 ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]] 
6195 ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
6196 ** <dd>This parameter returns the number of bytes of page cache
6197 ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
6198 ** buffer and where forced to overflow to [sqlite3_malloc()].  The
6199 ** returned value includes allocations that overflowed because they
6200 ** where too large (they were larger than the "sz" parameter to
6201 ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
6202 ** no space was left in the page cache.</dd>)^
6203 **
6204 ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
6205 ** <dd>This parameter records the largest memory allocation request
6206 ** handed to [pagecache memory allocator].  Only the value returned in the
6207 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
6208 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6209 **
6210 ** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
6211 ** <dd>This parameter returns the number of allocations used out of the
6212 ** [scratch memory allocator] configured using
6213 ** [SQLITE_CONFIG_SCRATCH].  The value returned is in allocations, not
6214 ** in bytes.  Since a single thread may only have one scratch allocation
6215 ** outstanding at time, this parameter also reports the number of threads
6216 ** using scratch memory at the same time.</dd>)^
6217 **
6218 ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
6219 ** <dd>This parameter returns the number of bytes of scratch memory
6220 ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
6221 ** buffer and where forced to overflow to [sqlite3_malloc()].  The values
6222 ** returned include overflows because the requested allocation was too
6223 ** larger (that is, because the requested allocation was larger than the
6224 ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
6225 ** slots were available.
6226 ** </dd>)^
6227 **
6228 ** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
6229 ** <dd>This parameter records the largest memory allocation request
6230 ** handed to [scratch memory allocator].  Only the value returned in the
6231 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
6232 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6233 **
6234 ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
6235 ** <dd>This parameter records the deepest parser stack.  It is only
6236 ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
6237 ** </dl>
6238 **
6239 ** New status parameters may be added from time to time.
6240 */
6241 #define SQLITE_STATUS_MEMORY_USED          0
6242 #define SQLITE_STATUS_PAGECACHE_USED       1
6243 #define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
6244 #define SQLITE_STATUS_SCRATCH_USED         3
6245 #define SQLITE_STATUS_SCRATCH_OVERFLOW     4
6246 #define SQLITE_STATUS_MALLOC_SIZE          5
6247 #define SQLITE_STATUS_PARSER_STACK         6
6248 #define SQLITE_STATUS_PAGECACHE_SIZE       7
6249 #define SQLITE_STATUS_SCRATCH_SIZE         8
6250 #define SQLITE_STATUS_MALLOC_COUNT         9
6251
6252 /*
6253 ** CAPI3REF: Database Connection Status
6254 **
6255 ** ^This interface is used to retrieve runtime status information 
6256 ** about a single [database connection].  ^The first argument is the
6257 ** database connection object to be interrogated.  ^The second argument
6258 ** is an integer constant, taken from the set of
6259 ** [SQLITE_DBSTATUS options], that
6260 ** determines the parameter to interrogate.  The set of 
6261 ** [SQLITE_DBSTATUS options] is likely
6262 ** to grow in future releases of SQLite.
6263 **
6264 ** ^The current value of the requested parameter is written into *pCur
6265 ** and the highest instantaneous value is written into *pHiwtr.  ^If
6266 ** the resetFlg is true, then the highest instantaneous value is
6267 ** reset back down to the current value.
6268 **
6269 ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
6270 ** non-zero [error code] on failure.
6271 **
6272 ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
6273 */
6274 SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
6275
6276 /*
6277 ** CAPI3REF: Status Parameters for database connections
6278 ** KEYWORDS: {SQLITE_DBSTATUS options}
6279 **
6280 ** These constants are the available integer "verbs" that can be passed as
6281 ** the second argument to the [sqlite3_db_status()] interface.
6282 **
6283 ** New verbs may be added in future releases of SQLite. Existing verbs
6284 ** might be discontinued. Applications should check the return code from
6285 ** [sqlite3_db_status()] to make sure that the call worked.
6286 ** The [sqlite3_db_status()] interface will return a non-zero error code
6287 ** if a discontinued or unsupported verb is invoked.
6288 **
6289 ** <dl>
6290 ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
6291 ** <dd>This parameter returns the number of lookaside memory slots currently
6292 ** checked out.</dd>)^
6293 **
6294 ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
6295 ** <dd>This parameter returns the number malloc attempts that were 
6296 ** satisfied using lookaside memory. Only the high-water value is meaningful;
6297 ** the current value is always zero.)^
6298 **
6299 ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
6300 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
6301 ** <dd>This parameter returns the number malloc attempts that might have
6302 ** been satisfied using lookaside memory but failed due to the amount of
6303 ** memory requested being larger than the lookaside slot size.
6304 ** Only the high-water value is meaningful;
6305 ** the current value is always zero.)^
6306 **
6307 ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
6308 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
6309 ** <dd>This parameter returns the number malloc attempts that might have
6310 ** been satisfied using lookaside memory but failed due to all lookaside
6311 ** memory already being in use.
6312 ** Only the high-water value is meaningful;
6313 ** the current value is always zero.)^
6314 **
6315 ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
6316 ** <dd>This parameter returns the approximate number of of bytes of heap
6317 ** memory used by all pager caches associated with the database connection.)^
6318 ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
6319 **
6320 ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
6321 ** <dd>This parameter returns the approximate number of of bytes of heap
6322 ** memory used to store the schema for all databases associated
6323 ** with the connection - main, temp, and any [ATTACH]-ed databases.)^ 
6324 ** ^The full amount of memory used by the schemas is reported, even if the
6325 ** schema memory is shared with other database connections due to
6326 ** [shared cache mode] being enabled.
6327 ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
6328 **
6329 ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
6330 ** <dd>This parameter returns the approximate number of of bytes of heap
6331 ** and lookaside memory used by all prepared statements associated with
6332 ** the database connection.)^
6333 ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
6334 ** </dd>
6335 ** </dl>
6336 */
6337 #define SQLITE_DBSTATUS_LOOKASIDE_USED       0
6338 #define SQLITE_DBSTATUS_CACHE_USED           1
6339 #define SQLITE_DBSTATUS_SCHEMA_USED          2
6340 #define SQLITE_DBSTATUS_STMT_USED            3
6341 #define SQLITE_DBSTATUS_LOOKASIDE_HIT        4
6342 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE  5
6343 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL  6
6344 #define SQLITE_DBSTATUS_MAX                  6   /* Largest defined DBSTATUS */
6345
6346
6347 /*
6348 ** CAPI3REF: Prepared Statement Status
6349 **
6350 ** ^(Each prepared statement maintains various
6351 ** [SQLITE_STMTSTATUS counters] that measure the number
6352 ** of times it has performed specific operations.)^  These counters can
6353 ** be used to monitor the performance characteristics of the prepared
6354 ** statements.  For example, if the number of table steps greatly exceeds
6355 ** the number of table searches or result rows, that would tend to indicate
6356 ** that the prepared statement is using a full table scan rather than
6357 ** an index.  
6358 **
6359 ** ^(This interface is used to retrieve and reset counter values from
6360 ** a [prepared statement].  The first argument is the prepared statement
6361 ** object to be interrogated.  The second argument
6362 ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
6363 ** to be interrogated.)^
6364 ** ^The current value of the requested counter is returned.
6365 ** ^If the resetFlg is true, then the counter is reset to zero after this
6366 ** interface call returns.
6367 **
6368 ** See also: [sqlite3_status()] and [sqlite3_db_status()].
6369 */
6370 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
6371
6372 /*
6373 ** CAPI3REF: Status Parameters for prepared statements
6374 ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
6375 **
6376 ** These preprocessor macros define integer codes that name counter
6377 ** values associated with the [sqlite3_stmt_status()] interface.
6378 ** The meanings of the various counters are as follows:
6379 **
6380 ** <dl>
6381 ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
6382 ** <dd>^This is the number of times that SQLite has stepped forward in
6383 ** a table as part of a full table scan.  Large numbers for this counter
6384 ** may indicate opportunities for performance improvement through 
6385 ** careful use of indices.</dd>
6386 **
6387 ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
6388 ** <dd>^This is the number of sort operations that have occurred.
6389 ** A non-zero value in this counter may indicate an opportunity to
6390 ** improvement performance through careful use of indices.</dd>
6391 **
6392 ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
6393 ** <dd>^This is the number of rows inserted into transient indices that
6394 ** were created automatically in order to help joins run faster.
6395 ** A non-zero value in this counter may indicate an opportunity to
6396 ** improvement performance by adding permanent indices that do not
6397 ** need to be reinitialized each time the statement is run.</dd>
6398 **
6399 ** </dl>
6400 */
6401 #define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
6402 #define SQLITE_STMTSTATUS_SORT              2
6403 #define SQLITE_STMTSTATUS_AUTOINDEX         3
6404
6405 /*
6406 ** CAPI3REF: Custom Page Cache Object
6407 **
6408 ** The sqlite3_pcache type is opaque.  It is implemented by
6409 ** the pluggable module.  The SQLite core has no knowledge of
6410 ** its size or internal structure and never deals with the
6411 ** sqlite3_pcache object except by holding and passing pointers
6412 ** to the object.
6413 **
6414 ** See [sqlite3_pcache_methods] for additional information.
6415 */
6416 typedef struct sqlite3_pcache sqlite3_pcache;
6417
6418 /*
6419 ** CAPI3REF: Application Defined Page Cache.
6420 ** KEYWORDS: {page cache}
6421 **
6422 ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE], ...) interface can
6423 ** register an alternative page cache implementation by passing in an 
6424 ** instance of the sqlite3_pcache_methods structure.)^
6425 ** In many applications, most of the heap memory allocated by 
6426 ** SQLite is used for the page cache.
6427 ** By implementing a 
6428 ** custom page cache using this API, an application can better control
6429 ** the amount of memory consumed by SQLite, the way in which 
6430 ** that memory is allocated and released, and the policies used to 
6431 ** determine exactly which parts of a database file are cached and for 
6432 ** how long.
6433 **
6434 ** The alternative page cache mechanism is an
6435 ** extreme measure that is only needed by the most demanding applications.
6436 ** The built-in page cache is recommended for most uses.
6437 **
6438 ** ^(The contents of the sqlite3_pcache_methods structure are copied to an
6439 ** internal buffer by SQLite within the call to [sqlite3_config].  Hence
6440 ** the application may discard the parameter after the call to
6441 ** [sqlite3_config()] returns.)^
6442 **
6443 ** [[the xInit() page cache method]]
6444 ** ^(The xInit() method is called once for each effective 
6445 ** call to [sqlite3_initialize()])^
6446 ** (usually only once during the lifetime of the process). ^(The xInit()
6447 ** method is passed a copy of the sqlite3_pcache_methods.pArg value.)^
6448 ** The intent of the xInit() method is to set up global data structures 
6449 ** required by the custom page cache implementation. 
6450 ** ^(If the xInit() method is NULL, then the 
6451 ** built-in default page cache is used instead of the application defined
6452 ** page cache.)^
6453 **
6454 ** [[the xShutdown() page cache method]]
6455 ** ^The xShutdown() method is called by [sqlite3_shutdown()].
6456 ** It can be used to clean up 
6457 ** any outstanding resources before process shutdown, if required.
6458 ** ^The xShutdown() method may be NULL.
6459 **
6460 ** ^SQLite automatically serializes calls to the xInit method,
6461 ** so the xInit method need not be threadsafe.  ^The
6462 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
6463 ** not need to be threadsafe either.  All other methods must be threadsafe
6464 ** in multithreaded applications.
6465 **
6466 ** ^SQLite will never invoke xInit() more than once without an intervening
6467 ** call to xShutdown().
6468 **
6469 ** [[the xCreate() page cache methods]]
6470 ** ^SQLite invokes the xCreate() method to construct a new cache instance.
6471 ** SQLite will typically create one cache instance for each open database file,
6472 ** though this is not guaranteed. ^The
6473 ** first parameter, szPage, is the size in bytes of the pages that must
6474 ** be allocated by the cache.  ^szPage will not be a power of two.  ^szPage
6475 ** will the page size of the database file that is to be cached plus an
6476 ** increment (here called "R") of less than 250.  SQLite will use the
6477 ** extra R bytes on each page to store metadata about the underlying
6478 ** database page on disk.  The value of R depends
6479 ** on the SQLite version, the target platform, and how SQLite was compiled.
6480 ** ^(R is constant for a particular build of SQLite. Except, there are two
6481 ** distinct values of R when SQLite is compiled with the proprietary
6482 ** ZIPVFS extension.)^  ^The second argument to
6483 ** xCreate(), bPurgeable, is true if the cache being created will
6484 ** be used to cache database pages of a file stored on disk, or
6485 ** false if it is used for an in-memory database. The cache implementation
6486 ** does not have to do anything special based with the value of bPurgeable;
6487 ** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
6488 ** never invoke xUnpin() except to deliberately delete a page.
6489 ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
6490 ** false will always have the "discard" flag set to true.  
6491 ** ^Hence, a cache created with bPurgeable false will
6492 ** never contain any unpinned pages.
6493 **
6494 ** [[the xCachesize() page cache method]]
6495 ** ^(The xCachesize() method may be called at any time by SQLite to set the
6496 ** suggested maximum cache-size (number of pages stored by) the cache
6497 ** instance passed as the first argument. This is the value configured using
6498 ** the SQLite "[PRAGMA cache_size]" command.)^  As with the bPurgeable
6499 ** parameter, the implementation is not required to do anything with this
6500 ** value; it is advisory only.
6501 **
6502 ** [[the xPagecount() page cache methods]]
6503 ** The xPagecount() method must return the number of pages currently
6504 ** stored in the cache, both pinned and unpinned.
6505 ** 
6506 ** [[the xFetch() page cache methods]]
6507 ** The xFetch() method locates a page in the cache and returns a pointer to 
6508 ** the page, or a NULL pointer.
6509 ** A "page", in this context, means a buffer of szPage bytes aligned at an
6510 ** 8-byte boundary. The page to be fetched is determined by the key. ^The
6511 ** minimum key value is 1.  After it has been retrieved using xFetch, the page 
6512 ** is considered to be "pinned".
6513 **
6514 ** If the requested page is already in the page cache, then the page cache
6515 ** implementation must return a pointer to the page buffer with its content
6516 ** intact.  If the requested page is not already in the cache, then the
6517 ** cache implementation should use the value of the createFlag
6518 ** parameter to help it determined what action to take:
6519 **
6520 ** <table border=1 width=85% align=center>
6521 ** <tr><th> createFlag <th> Behaviour when page is not already in cache
6522 ** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.
6523 ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
6524 **                 Otherwise return NULL.
6525 ** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return
6526 **                 NULL if allocating a new page is effectively impossible.
6527 ** </table>
6528 **
6529 ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  SQLite
6530 ** will only use a createFlag of 2 after a prior call with a createFlag of 1
6531 ** failed.)^  In between the to xFetch() calls, SQLite may
6532 ** attempt to unpin one or more cache pages by spilling the content of
6533 ** pinned pages to disk and synching the operating system disk cache.
6534 **
6535 ** [[the xUnpin() page cache method]]
6536 ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
6537 ** as its second argument.  If the third parameter, discard, is non-zero,
6538 ** then the page must be evicted from the cache.
6539 ** ^If the discard parameter is
6540 ** zero, then the page may be discarded or retained at the discretion of
6541 ** page cache implementation. ^The page cache implementation
6542 ** may choose to evict unpinned pages at any time.
6543 **
6544 ** The cache must not perform any reference counting. A single 
6545 ** call to xUnpin() unpins the page regardless of the number of prior calls 
6546 ** to xFetch().
6547 **
6548 ** [[the xRekey() page cache methods]]
6549 ** The xRekey() method is used to change the key value associated with the
6550 ** page passed as the second argument. If the cache
6551 ** previously contains an entry associated with newKey, it must be
6552 ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
6553 ** to be pinned.
6554 **
6555 ** When SQLite calls the xTruncate() method, the cache must discard all
6556 ** existing cache entries with page numbers (keys) greater than or equal
6557 ** to the value of the iLimit parameter passed to xTruncate(). If any
6558 ** of these pages are pinned, they are implicitly unpinned, meaning that
6559 ** they can be safely discarded.
6560 **
6561 ** [[the xDestroy() page cache method]]
6562 ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
6563 ** All resources associated with the specified cache should be freed. ^After
6564 ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
6565 ** handle invalid, and will not use it with any other sqlite3_pcache_methods
6566 ** functions.
6567 */
6568 typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
6569 struct sqlite3_pcache_methods {
6570   void *pArg;
6571   int (*xInit)(void*);
6572   void (*xShutdown)(void*);
6573   sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
6574   void (*xCachesize)(sqlite3_pcache*, int nCachesize);
6575   int (*xPagecount)(sqlite3_pcache*);
6576   void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
6577   void (*xUnpin)(sqlite3_pcache*, void*, int discard);
6578   void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
6579   void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
6580   void (*xDestroy)(sqlite3_pcache*);
6581 };
6582
6583 /*
6584 ** CAPI3REF: Online Backup Object
6585 **
6586 ** The sqlite3_backup object records state information about an ongoing
6587 ** online backup operation.  ^The sqlite3_backup object is created by
6588 ** a call to [sqlite3_backup_init()] and is destroyed by a call to
6589 ** [sqlite3_backup_finish()].
6590 **
6591 ** See Also: [Using the SQLite Online Backup API]
6592 */
6593 typedef struct sqlite3_backup sqlite3_backup;
6594
6595 /*
6596 ** CAPI3REF: Online Backup API.
6597 **
6598 ** The backup API copies the content of one database into another.
6599 ** It is useful either for creating backups of databases or
6600 ** for copying in-memory databases to or from persistent files. 
6601 **
6602 ** See Also: [Using the SQLite Online Backup API]
6603 **
6604 ** ^SQLite holds a write transaction open on the destination database file
6605 ** for the duration of the backup operation.
6606 ** ^The source database is read-locked only while it is being read;
6607 ** it is not locked continuously for the entire backup operation.
6608 ** ^Thus, the backup may be performed on a live source database without
6609 ** preventing other database connections from
6610 ** reading or writing to the source database while the backup is underway.
6611 ** 
6612 ** ^(To perform a backup operation: 
6613 **   <ol>
6614 **     <li><b>sqlite3_backup_init()</b> is called once to initialize the
6615 **         backup, 
6616 **     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer 
6617 **         the data between the two databases, and finally
6618 **     <li><b>sqlite3_backup_finish()</b> is called to release all resources 
6619 **         associated with the backup operation. 
6620 **   </ol>)^
6621 ** There should be exactly one call to sqlite3_backup_finish() for each
6622 ** successful call to sqlite3_backup_init().
6623 **
6624 ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
6625 **
6626 ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the 
6627 ** [database connection] associated with the destination database 
6628 ** and the database name, respectively.
6629 ** ^The database name is "main" for the main database, "temp" for the
6630 ** temporary database, or the name specified after the AS keyword in
6631 ** an [ATTACH] statement for an attached database.
6632 ** ^The S and M arguments passed to 
6633 ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
6634 ** and database name of the source database, respectively.
6635 ** ^The source and destination [database connections] (parameters S and D)
6636 ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
6637 ** an error.
6638 **
6639 ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
6640 ** returned and an error code and error message are stored in the
6641 ** destination [database connection] D.
6642 ** ^The error code and message for the failed call to sqlite3_backup_init()
6643 ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
6644 ** [sqlite3_errmsg16()] functions.
6645 ** ^A successful call to sqlite3_backup_init() returns a pointer to an
6646 ** [sqlite3_backup] object.
6647 ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
6648 ** sqlite3_backup_finish() functions to perform the specified backup 
6649 ** operation.
6650 **
6651 ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
6652 **
6653 ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between 
6654 ** the source and destination databases specified by [sqlite3_backup] object B.
6655 ** ^If N is negative, all remaining source pages are copied. 
6656 ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
6657 ** are still more pages to be copied, then the function returns [SQLITE_OK].
6658 ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
6659 ** from source to destination, then it returns [SQLITE_DONE].
6660 ** ^If an error occurs while running sqlite3_backup_step(B,N),
6661 ** then an [error code] is returned. ^As well as [SQLITE_OK] and
6662 ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
6663 ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
6664 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
6665 **
6666 ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
6667 ** <ol>
6668 ** <li> the destination database was opened read-only, or
6669 ** <li> the destination database is using write-ahead-log journaling
6670 ** and the destination and source page sizes differ, or
6671 ** <li> the destination database is an in-memory database and the
6672 ** destination and source page sizes differ.
6673 ** </ol>)^
6674 **
6675 ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
6676 ** the [sqlite3_busy_handler | busy-handler function]
6677 ** is invoked (if one is specified). ^If the 
6678 ** busy-handler returns non-zero before the lock is available, then 
6679 ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
6680 ** sqlite3_backup_step() can be retried later. ^If the source
6681 ** [database connection]
6682 ** is being used to write to the source database when sqlite3_backup_step()
6683 ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
6684 ** case the call to sqlite3_backup_step() can be retried later on. ^(If
6685 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
6686 ** [SQLITE_READONLY] is returned, then 
6687 ** there is no point in retrying the call to sqlite3_backup_step(). These 
6688 ** errors are considered fatal.)^  The application must accept 
6689 ** that the backup operation has failed and pass the backup operation handle 
6690 ** to the sqlite3_backup_finish() to release associated resources.
6691 **
6692 ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
6693 ** on the destination file. ^The exclusive lock is not released until either 
6694 ** sqlite3_backup_finish() is called or the backup operation is complete 
6695 ** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to
6696 ** sqlite3_backup_step() obtains a [shared lock] on the source database that
6697 ** lasts for the duration of the sqlite3_backup_step() call.
6698 ** ^Because the source database is not locked between calls to
6699 ** sqlite3_backup_step(), the source database may be modified mid-way
6700 ** through the backup process.  ^If the source database is modified by an
6701 ** external process or via a database connection other than the one being
6702 ** used by the backup operation, then the backup will be automatically
6703 ** restarted by the next call to sqlite3_backup_step(). ^If the source 
6704 ** database is modified by the using the same database connection as is used
6705 ** by the backup operation, then the backup database is automatically
6706 ** updated at the same time.
6707 **
6708 ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
6709 **
6710 ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the 
6711 ** application wishes to abandon the backup operation, the application
6712 ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
6713 ** ^The sqlite3_backup_finish() interfaces releases all
6714 ** resources associated with the [sqlite3_backup] object. 
6715 ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
6716 ** active write-transaction on the destination database is rolled back.
6717 ** The [sqlite3_backup] object is invalid
6718 ** and may not be used following a call to sqlite3_backup_finish().
6719 **
6720 ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
6721 ** sqlite3_backup_step() errors occurred, regardless or whether or not
6722 ** sqlite3_backup_step() completed.
6723 ** ^If an out-of-memory condition or IO error occurred during any prior
6724 ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
6725 ** sqlite3_backup_finish() returns the corresponding [error code].
6726 **
6727 ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
6728 ** is not a permanent error and does not affect the return value of
6729 ** sqlite3_backup_finish().
6730 **
6731 ** [[sqlite3_backup__remaining()]] [[sqlite3_backup_pagecount()]]
6732 ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
6733 **
6734 ** ^Each call to sqlite3_backup_step() sets two values inside
6735 ** the [sqlite3_backup] object: the number of pages still to be backed
6736 ** up and the total number of pages in the source database file.
6737 ** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
6738 ** retrieve these two values, respectively.
6739 **
6740 ** ^The values returned by these functions are only updated by
6741 ** sqlite3_backup_step(). ^If the source database is modified during a backup
6742 ** operation, then the values are not updated to account for any extra
6743 ** pages that need to be updated or the size of the source database file
6744 ** changing.
6745 **
6746 ** <b>Concurrent Usage of Database Handles</b>
6747 **
6748 ** ^The source [database connection] may be used by the application for other
6749 ** purposes while a backup operation is underway or being initialized.
6750 ** ^If SQLite is compiled and configured to support threadsafe database
6751 ** connections, then the source database connection may be used concurrently
6752 ** from within other threads.
6753 **
6754 ** However, the application must guarantee that the destination 
6755 ** [database connection] is not passed to any other API (by any thread) after 
6756 ** sqlite3_backup_init() is called and before the corresponding call to
6757 ** sqlite3_backup_finish().  SQLite does not currently check to see
6758 ** if the application incorrectly accesses the destination [database connection]
6759 ** and so no error code is reported, but the operations may malfunction
6760 ** nevertheless.  Use of the destination database connection while a
6761 ** backup is in progress might also also cause a mutex deadlock.
6762 **
6763 ** If running in [shared cache mode], the application must
6764 ** guarantee that the shared cache used by the destination database
6765 ** is not accessed while the backup is running. In practice this means
6766 ** that the application must guarantee that the disk file being 
6767 ** backed up to is not accessed by any connection within the process,
6768 ** not just the specific connection that was passed to sqlite3_backup_init().
6769 **
6770 ** The [sqlite3_backup] object itself is partially threadsafe. Multiple 
6771 ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
6772 ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
6773 ** APIs are not strictly speaking threadsafe. If they are invoked at the
6774 ** same time as another thread is invoking sqlite3_backup_step() it is
6775 ** possible that they return invalid values.
6776 */
6777 SQLITE_API sqlite3_backup *sqlite3_backup_init(
6778   sqlite3 *pDest,                        /* Destination database handle */
6779   const char *zDestName,                 /* Destination database name */
6780   sqlite3 *pSource,                      /* Source database handle */
6781   const char *zSourceName                /* Source database name */
6782 );
6783 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
6784 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
6785 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
6786 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
6787
6788 /*
6789 ** CAPI3REF: Unlock Notification
6790 **
6791 ** ^When running in shared-cache mode, a database operation may fail with
6792 ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
6793 ** individual tables within the shared-cache cannot be obtained. See
6794 ** [SQLite Shared-Cache Mode] for a description of shared-cache locking. 
6795 ** ^This API may be used to register a callback that SQLite will invoke 
6796 ** when the connection currently holding the required lock relinquishes it.
6797 ** ^This API is only available if the library was compiled with the
6798 ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
6799 **
6800 ** See Also: [Using the SQLite Unlock Notification Feature].
6801 **
6802 ** ^Shared-cache locks are released when a database connection concludes
6803 ** its current transaction, either by committing it or rolling it back. 
6804 **
6805 ** ^When a connection (known as the blocked connection) fails to obtain a
6806 ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
6807 ** identity of the database connection (the blocking connection) that
6808 ** has locked the required resource is stored internally. ^After an 
6809 ** application receives an SQLITE_LOCKED error, it may call the
6810 ** sqlite3_unlock_notify() method with the blocked connection handle as 
6811 ** the first argument to register for a callback that will be invoked
6812 ** when the blocking connections current transaction is concluded. ^The
6813 ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
6814 ** call that concludes the blocking connections transaction.
6815 **
6816 ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
6817 ** there is a chance that the blocking connection will have already
6818 ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
6819 ** If this happens, then the specified callback is invoked immediately,
6820 ** from within the call to sqlite3_unlock_notify().)^
6821 **
6822 ** ^If the blocked connection is attempting to obtain a write-lock on a
6823 ** shared-cache table, and more than one other connection currently holds
6824 ** a read-lock on the same table, then SQLite arbitrarily selects one of 
6825 ** the other connections to use as the blocking connection.
6826 **
6827 ** ^(There may be at most one unlock-notify callback registered by a 
6828 ** blocked connection. If sqlite3_unlock_notify() is called when the
6829 ** blocked connection already has a registered unlock-notify callback,
6830 ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
6831 ** called with a NULL pointer as its second argument, then any existing
6832 ** unlock-notify callback is canceled. ^The blocked connections 
6833 ** unlock-notify callback may also be canceled by closing the blocked
6834 ** connection using [sqlite3_close()].
6835 **
6836 ** The unlock-notify callback is not reentrant. If an application invokes
6837 ** any sqlite3_xxx API functions from within an unlock-notify callback, a
6838 ** crash or deadlock may be the result.
6839 **
6840 ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
6841 ** returns SQLITE_OK.
6842 **
6843 ** <b>Callback Invocation Details</b>
6844 **
6845 ** When an unlock-notify callback is registered, the application provides a 
6846 ** single void* pointer that is passed to the callback when it is invoked.
6847 ** However, the signature of the callback function allows SQLite to pass
6848 ** it an array of void* context pointers. The first argument passed to
6849 ** an unlock-notify callback is a pointer to an array of void* pointers,
6850 ** and the second is the number of entries in the array.
6851 **
6852 ** When a blocking connections transaction is concluded, there may be
6853 ** more than one blocked connection that has registered for an unlock-notify
6854 ** callback. ^If two or more such blocked connections have specified the
6855 ** same callback function, then instead of invoking the callback function
6856 ** multiple times, it is invoked once with the set of void* context pointers
6857 ** specified by the blocked connections bundled together into an array.
6858 ** This gives the application an opportunity to prioritize any actions 
6859 ** related to the set of unblocked database connections.
6860 **
6861 ** <b>Deadlock Detection</b>
6862 **
6863 ** Assuming that after registering for an unlock-notify callback a 
6864 ** database waits for the callback to be issued before taking any further
6865 ** action (a reasonable assumption), then using this API may cause the
6866 ** application to deadlock. For example, if connection X is waiting for
6867 ** connection Y's transaction to be concluded, and similarly connection
6868 ** Y is waiting on connection X's transaction, then neither connection
6869 ** will proceed and the system may remain deadlocked indefinitely.
6870 **
6871 ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
6872 ** detection. ^If a given call to sqlite3_unlock_notify() would put the
6873 ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
6874 ** unlock-notify callback is registered. The system is said to be in
6875 ** a deadlocked state if connection A has registered for an unlock-notify
6876 ** callback on the conclusion of connection B's transaction, and connection
6877 ** B has itself registered for an unlock-notify callback when connection
6878 ** A's transaction is concluded. ^Indirect deadlock is also detected, so
6879 ** the system is also considered to be deadlocked if connection B has
6880 ** registered for an unlock-notify callback on the conclusion of connection
6881 ** C's transaction, where connection C is waiting on connection A. ^Any
6882 ** number of levels of indirection are allowed.
6883 **
6884 ** <b>The "DROP TABLE" Exception</b>
6885 **
6886 ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost 
6887 ** always appropriate to call sqlite3_unlock_notify(). There is however,
6888 ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
6889 ** SQLite checks if there are any currently executing SELECT statements
6890 ** that belong to the same connection. If there are, SQLITE_LOCKED is
6891 ** returned. In this case there is no "blocking connection", so invoking
6892 ** sqlite3_unlock_notify() results in the unlock-notify callback being
6893 ** invoked immediately. If the application then re-attempts the "DROP TABLE"
6894 ** or "DROP INDEX" query, an infinite loop might be the result.
6895 **
6896 ** One way around this problem is to check the extended error code returned
6897 ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
6898 ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
6899 ** the special "DROP TABLE/INDEX" case, the extended error code is just 
6900 ** SQLITE_LOCKED.)^
6901 */
6902 SQLITE_API int sqlite3_unlock_notify(
6903   sqlite3 *pBlocked,                          /* Waiting connection */
6904   void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */
6905   void *pNotifyArg                            /* Argument to pass to xNotify */
6906 );
6907
6908
6909 /*
6910 ** CAPI3REF: String Comparison
6911 **
6912 ** ^The [sqlite3_strnicmp()] API allows applications and extensions to
6913 ** compare the contents of two buffers containing UTF-8 strings in a
6914 ** case-independent fashion, using the same definition of case independence 
6915 ** that SQLite uses internally when comparing identifiers.
6916 */
6917 SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
6918
6919 /*
6920 ** CAPI3REF: Error Logging Interface
6921 **
6922 ** ^The [sqlite3_log()] interface writes a message into the error log
6923 ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
6924 ** ^If logging is enabled, the zFormat string and subsequent arguments are
6925 ** used with [sqlite3_snprintf()] to generate the final output string.
6926 **
6927 ** The sqlite3_log() interface is intended for use by extensions such as
6928 ** virtual tables, collating functions, and SQL functions.  While there is
6929 ** nothing to prevent an application from calling sqlite3_log(), doing so
6930 ** is considered bad form.
6931 **
6932 ** The zFormat string must not be NULL.
6933 **
6934 ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
6935 ** will not use dynamically allocated memory.  The log message is stored in
6936 ** a fixed-length buffer on the stack.  If the log message is longer than
6937 ** a few hundred characters, it will be truncated to the length of the
6938 ** buffer.
6939 */
6940 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
6941
6942 /*
6943 ** CAPI3REF: Write-Ahead Log Commit Hook
6944 **
6945 ** ^The [sqlite3_wal_hook()] function is used to register a callback that
6946 ** will be invoked each time a database connection commits data to a
6947 ** [write-ahead log] (i.e. whenever a transaction is committed in
6948 ** [journal_mode | journal_mode=WAL mode]). 
6949 **
6950 ** ^The callback is invoked by SQLite after the commit has taken place and 
6951 ** the associated write-lock on the database released, so the implementation 
6952 ** may read, write or [checkpoint] the database as required.
6953 **
6954 ** ^The first parameter passed to the callback function when it is invoked
6955 ** is a copy of the third parameter passed to sqlite3_wal_hook() when
6956 ** registering the callback. ^The second is a copy of the database handle.
6957 ** ^The third parameter is the name of the database that was written to -
6958 ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
6959 ** is the number of pages currently in the write-ahead log file,
6960 ** including those that were just committed.
6961 **
6962 ** The callback function should normally return [SQLITE_OK].  ^If an error
6963 ** code is returned, that error will propagate back up through the
6964 ** SQLite code base to cause the statement that provoked the callback
6965 ** to report an error, though the commit will have still occurred. If the
6966 ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
6967 ** that does not correspond to any valid SQLite error code, the results
6968 ** are undefined.
6969 **
6970 ** A single database handle may have at most a single write-ahead log callback 
6971 ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
6972 ** previously registered write-ahead log callback. ^Note that the
6973 ** [sqlite3_wal_autocheckpoint()] interface and the
6974 ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
6975 ** those overwrite any prior [sqlite3_wal_hook()] settings.
6976 */
6977 SQLITE_API void *sqlite3_wal_hook(
6978   sqlite3*, 
6979   int(*)(void *,sqlite3*,const char*,int),
6980   void*
6981 );
6982
6983 /*
6984 ** CAPI3REF: Configure an auto-checkpoint
6985 **
6986 ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
6987 ** [sqlite3_wal_hook()] that causes any database on [database connection] D
6988 ** to automatically [checkpoint]
6989 ** after committing a transaction if there are N or
6990 ** more frames in the [write-ahead log] file.  ^Passing zero or 
6991 ** a negative value as the nFrame parameter disables automatic
6992 ** checkpoints entirely.
6993 **
6994 ** ^The callback registered by this function replaces any existing callback
6995 ** registered using [sqlite3_wal_hook()].  ^Likewise, registering a callback
6996 ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
6997 ** configured by this function.
6998 **
6999 ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
7000 ** from SQL.
7001 **
7002 ** ^Every new [database connection] defaults to having the auto-checkpoint
7003 ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
7004 ** pages.  The use of this interface
7005 ** is only necessary if the default setting is found to be suboptimal
7006 ** for a particular application.
7007 */
7008 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
7009
7010 /*
7011 ** CAPI3REF: Checkpoint a database
7012 **
7013 ** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X
7014 ** on [database connection] D to be [checkpointed].  ^If X is NULL or an
7015 ** empty string, then a checkpoint is run on all databases of
7016 ** connection D.  ^If the database connection D is not in
7017 ** [WAL | write-ahead log mode] then this interface is a harmless no-op.
7018 **
7019 ** ^The [wal_checkpoint pragma] can be used to invoke this interface
7020 ** from SQL.  ^The [sqlite3_wal_autocheckpoint()] interface and the
7021 ** [wal_autocheckpoint pragma] can be used to cause this interface to be
7022 ** run whenever the WAL reaches a certain size threshold.
7023 **
7024 ** See also: [sqlite3_wal_checkpoint_v2()]
7025 */
7026 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
7027
7028 /*
7029 ** CAPI3REF: Checkpoint a database
7030 **
7031 ** Run a checkpoint operation on WAL database zDb attached to database 
7032 ** handle db. The specific operation is determined by the value of the 
7033 ** eMode parameter:
7034 **
7035 ** <dl>
7036 ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
7037 **   Checkpoint as many frames as possible without waiting for any database 
7038 **   readers or writers to finish. Sync the db file if all frames in the log
7039 **   are checkpointed. This mode is the same as calling 
7040 **   sqlite3_wal_checkpoint(). The busy-handler callback is never invoked.
7041 **
7042 ** <dt>SQLITE_CHECKPOINT_FULL<dd>
7043 **   This mode blocks (calls the busy-handler callback) until there is no
7044 **   database writer and all readers are reading from the most recent database
7045 **   snapshot. It then checkpoints all frames in the log file and syncs the
7046 **   database file. This call blocks database writers while it is running,
7047 **   but not database readers.
7048 **
7049 ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
7050 **   This mode works the same way as SQLITE_CHECKPOINT_FULL, except after 
7051 **   checkpointing the log file it blocks (calls the busy-handler callback)
7052 **   until all readers are reading from the database file only. This ensures 
7053 **   that the next client to write to the database file restarts the log file 
7054 **   from the beginning. This call blocks database writers while it is running,
7055 **   but not database readers.
7056 ** </dl>
7057 **
7058 ** If pnLog is not NULL, then *pnLog is set to the total number of frames in
7059 ** the log file before returning. If pnCkpt is not NULL, then *pnCkpt is set to
7060 ** the total number of checkpointed frames (including any that were already
7061 ** checkpointed when this function is called). *pnLog and *pnCkpt may be
7062 ** populated even if sqlite3_wal_checkpoint_v2() returns other than SQLITE_OK.
7063 ** If no values are available because of an error, they are both set to -1
7064 ** before returning to communicate this to the caller.
7065 **
7066 ** All calls obtain an exclusive "checkpoint" lock on the database file. If
7067 ** any other process is running a checkpoint operation at the same time, the 
7068 ** lock cannot be obtained and SQLITE_BUSY is returned. Even if there is a 
7069 ** busy-handler configured, it will not be invoked in this case.
7070 **
7071 ** The SQLITE_CHECKPOINT_FULL and RESTART modes also obtain the exclusive 
7072 ** "writer" lock on the database file. If the writer lock cannot be obtained
7073 ** immediately, and a busy-handler is configured, it is invoked and the writer
7074 ** lock retried until either the busy-handler returns 0 or the lock is
7075 ** successfully obtained. The busy-handler is also invoked while waiting for
7076 ** database readers as described above. If the busy-handler returns 0 before
7077 ** the writer lock is obtained or while waiting for database readers, the
7078 ** checkpoint operation proceeds from that point in the same way as 
7079 ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible 
7080 ** without blocking any further. SQLITE_BUSY is returned in this case.
7081 **
7082 ** If parameter zDb is NULL or points to a zero length string, then the
7083 ** specified operation is attempted on all WAL databases. In this case the
7084 ** values written to output parameters *pnLog and *pnCkpt are undefined. If 
7085 ** an SQLITE_BUSY error is encountered when processing one or more of the 
7086 ** attached WAL databases, the operation is still attempted on any remaining 
7087 ** attached databases and SQLITE_BUSY is returned to the caller. If any other 
7088 ** error occurs while processing an attached database, processing is abandoned 
7089 ** and the error code returned to the caller immediately. If no error 
7090 ** (SQLITE_BUSY or otherwise) is encountered while processing the attached 
7091 ** databases, SQLITE_OK is returned.
7092 **
7093 ** If database zDb is the name of an attached database that is not in WAL
7094 ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. If
7095 ** zDb is not NULL (or a zero length string) and is not the name of any
7096 ** attached database, SQLITE_ERROR is returned to the caller.
7097 */
7098 SQLITE_API int sqlite3_wal_checkpoint_v2(
7099   sqlite3 *db,                    /* Database handle */
7100   const char *zDb,                /* Name of attached database (or NULL) */
7101   int eMode,                      /* SQLITE_CHECKPOINT_* value */
7102   int *pnLog,                     /* OUT: Size of WAL log in frames */
7103   int *pnCkpt                     /* OUT: Total number of frames checkpointed */
7104 );
7105
7106 /*
7107 ** CAPI3REF: Checkpoint operation parameters
7108 **
7109 ** These constants can be used as the 3rd parameter to
7110 ** [sqlite3_wal_checkpoint_v2()].  See the [sqlite3_wal_checkpoint_v2()]
7111 ** documentation for additional information about the meaning and use of
7112 ** each of these values.
7113 */
7114 #define SQLITE_CHECKPOINT_PASSIVE 0
7115 #define SQLITE_CHECKPOINT_FULL    1
7116 #define SQLITE_CHECKPOINT_RESTART 2
7117
7118 /*
7119 ** CAPI3REF: Virtual Table Interface Configuration
7120 **
7121 ** This function may be called by either the [xConnect] or [xCreate] method
7122 ** of a [virtual table] implementation to configure
7123 ** various facets of the virtual table interface.
7124 **
7125 ** If this interface is invoked outside the context of an xConnect or
7126 ** xCreate virtual table method then the behavior is undefined.
7127 **
7128 ** At present, there is only one option that may be configured using
7129 ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].)  Further options
7130 ** may be added in the future.
7131 */
7132 SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
7133
7134 /*
7135 ** CAPI3REF: Virtual Table Configuration Options
7136 **
7137 ** These macros define the various options to the
7138 ** [sqlite3_vtab_config()] interface that [virtual table] implementations
7139 ** can use to customize and optimize their behavior.
7140 **
7141 ** <dl>
7142 ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
7143 ** <dd>Calls of the form
7144 ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
7145 ** where X is an integer.  If X is zero, then the [virtual table] whose
7146 ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
7147 ** support constraints.  In this configuration (which is the default) if
7148 ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
7149 ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
7150 ** specified as part of the users SQL statement, regardless of the actual
7151 ** ON CONFLICT mode specified.
7152 **
7153 ** If X is non-zero, then the virtual table implementation guarantees
7154 ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
7155 ** any modifications to internal or persistent data structures have been made.
7156 ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite 
7157 ** is able to roll back a statement or database transaction, and abandon
7158 ** or continue processing the current SQL statement as appropriate. 
7159 ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
7160 ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
7161 ** had been ABORT.
7162 **
7163 ** Virtual table implementations that are required to handle OR REPLACE
7164 ** must do so within the [xUpdate] method. If a call to the 
7165 ** [sqlite3_vtab_on_conflict()] function indicates that the current ON 
7166 ** CONFLICT policy is REPLACE, the virtual table implementation should 
7167 ** silently replace the appropriate rows within the xUpdate callback and
7168 ** return SQLITE_OK. Or, if this is not possible, it may return
7169 ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT 
7170 ** constraint handling.
7171 ** </dl>
7172 */
7173 #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
7174
7175 /*
7176 ** CAPI3REF: Determine The Virtual Table Conflict Policy
7177 **
7178 ** This function may only be called from within a call to the [xUpdate] method
7179 ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
7180 ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
7181 ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
7182 ** of the SQL statement that triggered the call to the [xUpdate] method of the
7183 ** [virtual table].
7184 */
7185 SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
7186
7187 /*
7188 ** CAPI3REF: Conflict resolution modes
7189 **
7190 ** These constants are returned by [sqlite3_vtab_on_conflict()] to
7191 ** inform a [virtual table] implementation what the [ON CONFLICT] mode
7192 ** is for the SQL statement being evaluated.
7193 **
7194 ** Note that the [SQLITE_IGNORE] constant is also used as a potential
7195 ** return value from the [sqlite3_set_authorizer()] callback and that
7196 ** [SQLITE_ABORT] is also a [result code].
7197 */
7198 #define SQLITE_ROLLBACK 1
7199 /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
7200 #define SQLITE_FAIL     3
7201 /* #define SQLITE_ABORT 4  // Also an error code */
7202 #define SQLITE_REPLACE  5
7203
7204
7205
7206 /*
7207 ** Undo the hack that converts floating point types to integer for
7208 ** builds on processors without floating point support.
7209 */
7210 #ifdef SQLITE_OMIT_FLOATING_POINT
7211 # undef double
7212 #endif
7213
7214 #if 0
7215 }  /* End of the 'extern "C"' block */
7216 #endif
7217 #endif
7218
7219 /*
7220 ** 2010 August 30
7221 **
7222 ** The author disclaims copyright to this source code.  In place of
7223 ** a legal notice, here is a blessing:
7224 **
7225 **    May you do good and not evil.
7226 **    May you find forgiveness for yourself and forgive others.
7227 **    May you share freely, never taking more than you give.
7228 **
7229 *************************************************************************
7230 */
7231
7232 #ifndef _SQLITE3RTREE_H_
7233 #define _SQLITE3RTREE_H_
7234
7235
7236 #if 0
7237 extern "C" {
7238 #endif
7239
7240 typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
7241
7242 /*
7243 ** Register a geometry callback named zGeom that can be used as part of an
7244 ** R-Tree geometry query as follows:
7245 **
7246 **   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
7247 */
7248 SQLITE_API int sqlite3_rtree_geometry_callback(
7249   sqlite3 *db,
7250   const char *zGeom,
7251   int (*xGeom)(sqlite3_rtree_geometry *, int nCoord, double *aCoord, int *pRes),
7252   void *pContext
7253 );
7254
7255
7256 /*
7257 ** A pointer to a structure of the following type is passed as the first
7258 ** argument to callbacks registered using rtree_geometry_callback().
7259 */
7260 struct sqlite3_rtree_geometry {
7261   void *pContext;                 /* Copy of pContext passed to s_r_g_c() */
7262   int nParam;                     /* Size of array aParam[] */
7263   double *aParam;                 /* Parameters passed to SQL geom function */
7264   void *pUser;                    /* Callback implementation user data */
7265   void (*xDelUser)(void *);       /* Called by SQLite to clean up pUser */
7266 };
7267
7268
7269 #if 0
7270 }  /* end of the 'extern "C"' block */
7271 #endif
7272
7273 #endif  /* ifndef _SQLITE3RTREE_H_ */
7274
7275
7276 /************** End of sqlite3.h *********************************************/
7277 /************** Continuing where we left off in sqliteInt.h ******************/
7278 /************** Include hash.h in the middle of sqliteInt.h ******************/
7279 /************** Begin file hash.h ********************************************/
7280 /*
7281 ** 2001 September 22
7282 **
7283 ** The author disclaims copyright to this source code.  In place of
7284 ** a legal notice, here is a blessing:
7285 **
7286 **    May you do good and not evil.
7287 **    May you find forgiveness for yourself and forgive others.
7288 **    May you share freely, never taking more than you give.
7289 **
7290 *************************************************************************
7291 ** This is the header file for the generic hash-table implemenation
7292 ** used in SQLite.
7293 */
7294 #ifndef _SQLITE_HASH_H_
7295 #define _SQLITE_HASH_H_
7296
7297 /* Forward declarations of structures. */
7298 typedef struct Hash Hash;
7299 typedef struct HashElem HashElem;
7300
7301 /* A complete hash table is an instance of the following structure.
7302 ** The internals of this structure are intended to be opaque -- client
7303 ** code should not attempt to access or modify the fields of this structure
7304 ** directly.  Change this structure only by using the routines below.
7305 ** However, some of the "procedures" and "functions" for modifying and
7306 ** accessing this structure are really macros, so we can't really make
7307 ** this structure opaque.
7308 **
7309 ** All elements of the hash table are on a single doubly-linked list.
7310 ** Hash.first points to the head of this list.
7311 **
7312 ** There are Hash.htsize buckets.  Each bucket points to a spot in
7313 ** the global doubly-linked list.  The contents of the bucket are the
7314 ** element pointed to plus the next _ht.count-1 elements in the list.
7315 **
7316 ** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
7317 ** by a linear search of the global list.  For small tables, the 
7318 ** Hash.ht table is never allocated because if there are few elements
7319 ** in the table, it is faster to do a linear search than to manage
7320 ** the hash table.
7321 */
7322 struct Hash {
7323   unsigned int htsize;      /* Number of buckets in the hash table */
7324   unsigned int count;       /* Number of entries in this table */
7325   HashElem *first;          /* The first element of the array */
7326   struct _ht {              /* the hash table */
7327     int count;                 /* Number of entries with this hash */
7328     HashElem *chain;           /* Pointer to first entry with this hash */
7329   } *ht;
7330 };
7331
7332 /* Each element in the hash table is an instance of the following 
7333 ** structure.  All elements are stored on a single doubly-linked list.
7334 **
7335 ** Again, this structure is intended to be opaque, but it can't really
7336 ** be opaque because it is used by macros.
7337 */
7338 struct HashElem {
7339   HashElem *next, *prev;       /* Next and previous elements in the table */
7340   void *data;                  /* Data associated with this element */
7341   const char *pKey; int nKey;  /* Key associated with this element */
7342 };
7343
7344 /*
7345 ** Access routines.  To delete, insert a NULL pointer.
7346 */
7347 SQLITE_PRIVATE void sqlite3HashInit(Hash*);
7348 SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
7349 SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
7350 SQLITE_PRIVATE void sqlite3HashClear(Hash*);
7351
7352 /*
7353 ** Macros for looping over all elements of a hash table.  The idiom is
7354 ** like this:
7355 **
7356 **   Hash h;
7357 **   HashElem *p;
7358 **   ...
7359 **   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
7360 **     SomeStructure *pData = sqliteHashData(p);
7361 **     // do something with pData
7362 **   }
7363 */
7364 #define sqliteHashFirst(H)  ((H)->first)
7365 #define sqliteHashNext(E)   ((E)->next)
7366 #define sqliteHashData(E)   ((E)->data)
7367 /* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */
7368 /* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */
7369
7370 /*
7371 ** Number of entries in a hash table
7372 */
7373 /* #define sqliteHashCount(H)  ((H)->count) // NOT USED */
7374
7375 #endif /* _SQLITE_HASH_H_ */
7376
7377 /************** End of hash.h ************************************************/
7378 /************** Continuing where we left off in sqliteInt.h ******************/
7379 /************** Include parse.h in the middle of sqliteInt.h *****************/
7380 /************** Begin file parse.h *******************************************/
7381 #define TK_SEMI                            1
7382 #define TK_EXPLAIN                         2
7383 #define TK_QUERY                           3
7384 #define TK_PLAN                            4
7385 #define TK_BEGIN                           5
7386 #define TK_TRANSACTION                     6
7387 #define TK_DEFERRED                        7
7388 #define TK_IMMEDIATE                       8
7389 #define TK_EXCLUSIVE                       9
7390 #define TK_COMMIT                         10
7391 #define TK_END                            11
7392 #define TK_ROLLBACK                       12
7393 #define TK_SAVEPOINT                      13
7394 #define TK_RELEASE                        14
7395 #define TK_TO                             15
7396 #define TK_TABLE                          16
7397 #define TK_CREATE                         17
7398 #define TK_IF                             18
7399 #define TK_NOT                            19
7400 #define TK_EXISTS                         20
7401 #define TK_TEMP                           21
7402 #define TK_LP                             22
7403 #define TK_RP                             23
7404 #define TK_AS                             24
7405 #define TK_COMMA                          25
7406 #define TK_ID                             26
7407 #define TK_INDEXED                        27
7408 #define TK_ABORT                          28
7409 #define TK_ACTION                         29
7410 #define TK_AFTER                          30
7411 #define TK_ANALYZE                        31
7412 #define TK_ASC                            32
7413 #define TK_ATTACH                         33
7414 #define TK_BEFORE                         34
7415 #define TK_BY                             35
7416 #define TK_CASCADE                        36
7417 #define TK_CAST                           37
7418 #define TK_COLUMNKW                       38
7419 #define TK_CONFLICT                       39
7420 #define TK_DATABASE                       40
7421 #define TK_DESC                           41
7422 #define TK_DETACH                         42
7423 #define TK_EACH                           43
7424 #define TK_FAIL                           44
7425 #define TK_FOR                            45
7426 #define TK_IGNORE                         46
7427 #define TK_INITIALLY                      47
7428 #define TK_INSTEAD                        48
7429 #define TK_LIKE_KW                        49
7430 #define TK_MATCH                          50
7431 #define TK_NO                             51
7432 #define TK_KEY                            52
7433 #define TK_OF                             53
7434 #define TK_OFFSET                         54
7435 #define TK_PRAGMA                         55
7436 #define TK_RAISE                          56
7437 #define TK_REPLACE                        57
7438 #define TK_RESTRICT                       58
7439 #define TK_ROW                            59
7440 #define TK_TRIGGER                        60
7441 #define TK_VACUUM                         61
7442 #define TK_VIEW                           62
7443 #define TK_VIRTUAL                        63
7444 #define TK_REINDEX                        64
7445 #define TK_RENAME                         65
7446 #define TK_CTIME_KW                       66
7447 #define TK_ANY                            67
7448 #define TK_OR                             68
7449 #define TK_AND                            69
7450 #define TK_IS                             70
7451 #define TK_BETWEEN                        71
7452 #define TK_IN                             72
7453 #define TK_ISNULL                         73
7454 #define TK_NOTNULL                        74
7455 #define TK_NE                             75
7456 #define TK_EQ                             76
7457 #define TK_GT                             77
7458 #define TK_LE                             78
7459 #define TK_LT                             79
7460 #define TK_GE                             80
7461 #define TK_ESCAPE                         81
7462 #define TK_BITAND                         82
7463 #define TK_BITOR                          83
7464 #define TK_LSHIFT                         84
7465 #define TK_RSHIFT                         85
7466 #define TK_PLUS                           86
7467 #define TK_MINUS                          87
7468 #define TK_STAR                           88
7469 #define TK_SLASH                          89
7470 #define TK_REM                            90
7471 #define TK_CONCAT                         91
7472 #define TK_COLLATE                        92
7473 #define TK_BITNOT                         93
7474 #define TK_STRING                         94
7475 #define TK_JOIN_KW                        95
7476 #define TK_CONSTRAINT                     96
7477 #define TK_DEFAULT                        97
7478 #define TK_NULL                           98
7479 #define TK_PRIMARY                        99
7480 #define TK_UNIQUE                         100
7481 #define TK_CHECK                          101
7482 #define TK_REFERENCES                     102
7483 #define TK_AUTOINCR                       103
7484 #define TK_ON                             104
7485 #define TK_INSERT                         105
7486 #define TK_DELETE                         106
7487 #define TK_UPDATE                         107
7488 #define TK_SET                            108
7489 #define TK_DEFERRABLE                     109
7490 #define TK_FOREIGN                        110
7491 #define TK_DROP                           111
7492 #define TK_UNION                          112
7493 #define TK_ALL                            113
7494 #define TK_EXCEPT                         114
7495 #define TK_INTERSECT                      115
7496 #define TK_SELECT                         116
7497 #define TK_DISTINCT                       117
7498 #define TK_DOT                            118
7499 #define TK_FROM                           119
7500 #define TK_JOIN                           120
7501 #define TK_USING                          121
7502 #define TK_ORDER                          122
7503 #define TK_GROUP                          123
7504 #define TK_HAVING                         124
7505 #define TK_LIMIT                          125
7506 #define TK_WHERE                          126
7507 #define TK_INTO                           127
7508 #define TK_VALUES                         128
7509 #define TK_INTEGER                        129
7510 #define TK_FLOAT                          130
7511 #define TK_BLOB                           131
7512 #define TK_REGISTER                       132
7513 #define TK_VARIABLE                       133
7514 #define TK_CASE                           134
7515 #define TK_WHEN                           135
7516 #define TK_THEN                           136
7517 #define TK_ELSE                           137
7518 #define TK_INDEX                          138
7519 #define TK_ALTER                          139
7520 #define TK_ADD                            140
7521 #define TK_TO_TEXT                        141
7522 #define TK_TO_BLOB                        142
7523 #define TK_TO_NUMERIC                     143
7524 #define TK_TO_INT                         144
7525 #define TK_TO_REAL                        145
7526 #define TK_ISNOT                          146
7527 #define TK_END_OF_FILE                    147
7528 #define TK_ILLEGAL                        148
7529 #define TK_SPACE                          149
7530 #define TK_UNCLOSED_STRING                150
7531 #define TK_FUNCTION                       151
7532 #define TK_COLUMN                         152
7533 #define TK_AGG_FUNCTION                   153
7534 #define TK_AGG_COLUMN                     154
7535 #define TK_CONST_FUNC                     155
7536 #define TK_UMINUS                         156
7537 #define TK_UPLUS                          157
7538
7539 /************** End of parse.h ***********************************************/
7540 /************** Continuing where we left off in sqliteInt.h ******************/
7541 #include <stdio.h>
7542 #include <stdlib.h>
7543 #include <string.h>
7544 #include <assert.h>
7545 #include <stddef.h>
7546
7547 /*
7548 ** If compiling for a processor that lacks floating point support,
7549 ** substitute integer for floating-point
7550 */
7551 #ifdef SQLITE_OMIT_FLOATING_POINT
7552 # define double sqlite_int64
7553 # define float sqlite_int64
7554 # define LONGDOUBLE_TYPE sqlite_int64
7555 # ifndef SQLITE_BIG_DBL
7556 #   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
7557 # endif
7558 # define SQLITE_OMIT_DATETIME_FUNCS 1
7559 # define SQLITE_OMIT_TRACE 1
7560 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
7561 # undef SQLITE_HAVE_ISNAN
7562 #endif
7563 #ifndef SQLITE_BIG_DBL
7564 # define SQLITE_BIG_DBL (1e99)
7565 #endif
7566
7567 /*
7568 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
7569 ** afterward. Having this macro allows us to cause the C compiler 
7570 ** to omit code used by TEMP tables without messy #ifndef statements.
7571 */
7572 #ifdef SQLITE_OMIT_TEMPDB
7573 #define OMIT_TEMPDB 1
7574 #else
7575 #define OMIT_TEMPDB 0
7576 #endif
7577
7578 /*
7579 ** The "file format" number is an integer that is incremented whenever
7580 ** the VDBE-level file format changes.  The following macros define the
7581 ** the default file format for new databases and the maximum file format
7582 ** that the library can read.
7583 */
7584 #define SQLITE_MAX_FILE_FORMAT 4
7585 #ifndef SQLITE_DEFAULT_FILE_FORMAT
7586 # define SQLITE_DEFAULT_FILE_FORMAT 1
7587 #endif
7588
7589 /*
7590 ** Determine whether triggers are recursive by default.  This can be
7591 ** changed at run-time using a pragma.
7592 */
7593 #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
7594 # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
7595 #endif
7596
7597 /*
7598 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
7599 ** on the command-line
7600 */
7601 #ifndef SQLITE_TEMP_STORE
7602 # define SQLITE_TEMP_STORE 1
7603 #endif
7604
7605 /*
7606 ** GCC does not define the offsetof() macro so we'll have to do it
7607 ** ourselves.
7608 */
7609 #ifndef offsetof
7610 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
7611 #endif
7612
7613 /*
7614 ** Check to see if this machine uses EBCDIC.  (Yes, believe it or
7615 ** not, there are still machines out there that use EBCDIC.)
7616 */
7617 #if 'A' == '\301'
7618 # define SQLITE_EBCDIC 1
7619 #else
7620 # define SQLITE_ASCII 1
7621 #endif
7622
7623 /*
7624 ** Integers of known sizes.  These typedefs might change for architectures
7625 ** where the sizes very.  Preprocessor macros are available so that the
7626 ** types can be conveniently redefined at compile-type.  Like this:
7627 **
7628 **         cc '-DUINTPTR_TYPE=long long int' ...
7629 */
7630 #ifndef UINT32_TYPE
7631 # ifdef HAVE_UINT32_T
7632 #  define UINT32_TYPE uint32_t
7633 # else
7634 #  define UINT32_TYPE unsigned int
7635 # endif
7636 #endif
7637 #ifndef UINT16_TYPE
7638 # ifdef HAVE_UINT16_T
7639 #  define UINT16_TYPE uint16_t
7640 # else
7641 #  define UINT16_TYPE unsigned short int
7642 # endif
7643 #endif
7644 #ifndef INT16_TYPE
7645 # ifdef HAVE_INT16_T
7646 #  define INT16_TYPE int16_t
7647 # else
7648 #  define INT16_TYPE short int
7649 # endif
7650 #endif
7651 #ifndef UINT8_TYPE
7652 # ifdef HAVE_UINT8_T
7653 #  define UINT8_TYPE uint8_t
7654 # else
7655 #  define UINT8_TYPE unsigned char
7656 # endif
7657 #endif
7658 #ifndef INT8_TYPE
7659 # ifdef HAVE_INT8_T
7660 #  define INT8_TYPE int8_t
7661 # else
7662 #  define INT8_TYPE signed char
7663 # endif
7664 #endif
7665 #ifndef LONGDOUBLE_TYPE
7666 # define LONGDOUBLE_TYPE long double
7667 #endif
7668 typedef sqlite_int64 i64;          /* 8-byte signed integer */
7669 typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
7670 typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
7671 typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
7672 typedef INT16_TYPE i16;            /* 2-byte signed integer */
7673 typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
7674 typedef INT8_TYPE i8;              /* 1-byte signed integer */
7675
7676 /*
7677 ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
7678 ** that can be stored in a u32 without loss of data.  The value
7679 ** is 0x00000000ffffffff.  But because of quirks of some compilers, we
7680 ** have to specify the value in the less intuitive manner shown:
7681 */
7682 #define SQLITE_MAX_U32  ((((u64)1)<<32)-1)
7683
7684 /*
7685 ** Macros to determine whether the machine is big or little endian,
7686 ** evaluated at runtime.
7687 */
7688 #ifdef SQLITE_AMALGAMATION
7689 SQLITE_PRIVATE const int sqlite3one = 1;
7690 #else
7691 SQLITE_PRIVATE const int sqlite3one;
7692 #endif
7693 #if defined(i386) || defined(__i386__) || defined(_M_IX86)\
7694                              || defined(__x86_64) || defined(__x86_64__)
7695 # define SQLITE_BIGENDIAN    0
7696 # define SQLITE_LITTLEENDIAN 1
7697 # define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
7698 #else
7699 # define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
7700 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
7701 # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
7702 #endif
7703
7704 /*
7705 ** Constants for the largest and smallest possible 64-bit signed integers.
7706 ** These macros are designed to work correctly on both 32-bit and 64-bit
7707 ** compilers.
7708 */
7709 #define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
7710 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
7711
7712 /* 
7713 ** Round up a number to the next larger multiple of 8.  This is used
7714 ** to force 8-byte alignment on 64-bit architectures.
7715 */
7716 #define ROUND8(x)     (((x)+7)&~7)
7717
7718 /*
7719 ** Round down to the nearest multiple of 8
7720 */
7721 #define ROUNDDOWN8(x) ((x)&~7)
7722
7723 /*
7724 ** Assert that the pointer X is aligned to an 8-byte boundary.  This
7725 ** macro is used only within assert() to verify that the code gets
7726 ** all alignment restrictions correct.
7727 **
7728 ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
7729 ** underlying malloc() implemention might return us 4-byte aligned
7730 ** pointers.  In that case, only verify 4-byte alignment.
7731 */
7732 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
7733 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)
7734 #else
7735 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)
7736 #endif
7737
7738
7739 /*
7740 ** An instance of the following structure is used to store the busy-handler
7741 ** callback for a given sqlite handle. 
7742 **
7743 ** The sqlite.busyHandler member of the sqlite struct contains the busy
7744 ** callback for the database handle. Each pager opened via the sqlite
7745 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
7746 ** callback is currently invoked only from within pager.c.
7747 */
7748 typedef struct BusyHandler BusyHandler;
7749 struct BusyHandler {
7750   int (*xFunc)(void *,int);  /* The busy callback */
7751   void *pArg;                /* First arg to busy callback */
7752   int nBusy;                 /* Incremented with each busy call */
7753 };
7754
7755 /*
7756 ** Name of the master database table.  The master database table
7757 ** is a special table that holds the names and attributes of all
7758 ** user tables and indices.
7759 */
7760 #define MASTER_NAME       "sqlite_master"
7761 #define TEMP_MASTER_NAME  "sqlite_temp_master"
7762
7763 /*
7764 ** The root-page of the master database table.
7765 */
7766 #define MASTER_ROOT       1
7767
7768 /*
7769 ** The name of the schema table.
7770 */
7771 #define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
7772
7773 /*
7774 ** A convenience macro that returns the number of elements in
7775 ** an array.
7776 */
7777 #define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
7778
7779 /*
7780 ** The following value as a destructor means to use sqlite3DbFree().
7781 ** This is an internal extension to SQLITE_STATIC and SQLITE_TRANSIENT.
7782 */
7783 #define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3DbFree)
7784
7785 /*
7786 ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
7787 ** not support Writable Static Data (WSD) such as global and static variables.
7788 ** All variables must either be on the stack or dynamically allocated from
7789 ** the heap.  When WSD is unsupported, the variable declarations scattered
7790 ** throughout the SQLite code must become constants instead.  The SQLITE_WSD
7791 ** macro is used for this purpose.  And instead of referencing the variable
7792 ** directly, we use its constant as a key to lookup the run-time allocated
7793 ** buffer that holds real variable.  The constant is also the initializer
7794 ** for the run-time allocated buffer.
7795 **
7796 ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
7797 ** macros become no-ops and have zero performance impact.
7798 */
7799 #ifdef SQLITE_OMIT_WSD
7800   #define SQLITE_WSD const
7801   #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
7802   #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
7803 SQLITE_API   int sqlite3_wsd_init(int N, int J);
7804 SQLITE_API   void *sqlite3_wsd_find(void *K, int L);
7805 #else
7806   #define SQLITE_WSD 
7807   #define GLOBAL(t,v) v
7808   #define sqlite3GlobalConfig sqlite3Config
7809 #endif
7810
7811 /*
7812 ** The following macros are used to suppress compiler warnings and to
7813 ** make it clear to human readers when a function parameter is deliberately 
7814 ** left unused within the body of a function. This usually happens when
7815 ** a function is called via a function pointer. For example the 
7816 ** implementation of an SQL aggregate step callback may not use the
7817 ** parameter indicating the number of arguments passed to the aggregate,
7818 ** if it knows that this is enforced elsewhere.
7819 **
7820 ** When a function parameter is not used at all within the body of a function,
7821 ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
7822 ** However, these macros may also be used to suppress warnings related to
7823 ** parameters that may or may not be used depending on compilation options.
7824 ** For example those parameters only used in assert() statements. In these
7825 ** cases the parameters are named as per the usual conventions.
7826 */
7827 #define UNUSED_PARAMETER(x) (void)(x)
7828 #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
7829
7830 /*
7831 ** Forward references to structures
7832 */
7833 typedef struct AggInfo AggInfo;
7834 typedef struct AuthContext AuthContext;
7835 typedef struct AutoincInfo AutoincInfo;
7836 typedef struct Bitvec Bitvec;
7837 typedef struct CollSeq CollSeq;
7838 typedef struct Column Column;
7839 typedef struct Db Db;
7840 typedef struct Schema Schema;
7841 typedef struct Expr Expr;
7842 typedef struct ExprList ExprList;
7843 typedef struct ExprSpan ExprSpan;
7844 typedef struct FKey FKey;
7845 typedef struct FuncDestructor FuncDestructor;
7846 typedef struct FuncDef FuncDef;
7847 typedef struct FuncDefHash FuncDefHash;
7848 typedef struct IdList IdList;
7849 typedef struct Index Index;
7850 typedef struct IndexSample IndexSample;
7851 typedef struct KeyClass KeyClass;
7852 typedef struct KeyInfo KeyInfo;
7853 typedef struct Lookaside Lookaside;
7854 typedef struct LookasideSlot LookasideSlot;
7855 typedef struct Module Module;
7856 typedef struct NameContext NameContext;
7857 typedef struct Parse Parse;
7858 typedef struct RowSet RowSet;
7859 typedef struct Savepoint Savepoint;
7860 typedef struct Select Select;
7861 typedef struct SrcList SrcList;
7862 typedef struct StrAccum StrAccum;
7863 typedef struct Table Table;
7864 typedef struct TableLock TableLock;
7865 typedef struct Token Token;
7866 typedef struct Trigger Trigger;
7867 typedef struct TriggerPrg TriggerPrg;
7868 typedef struct TriggerStep TriggerStep;
7869 typedef struct UnpackedRecord UnpackedRecord;
7870 typedef struct VTable VTable;
7871 typedef struct VtabCtx VtabCtx;
7872 typedef struct Walker Walker;
7873 typedef struct WherePlan WherePlan;
7874 typedef struct WhereInfo WhereInfo;
7875 typedef struct WhereLevel WhereLevel;
7876
7877 /*
7878 ** Defer sourcing vdbe.h and btree.h until after the "u8" and 
7879 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
7880 ** pointer types (i.e. FuncDef) defined above.
7881 */
7882 /************** Include btree.h in the middle of sqliteInt.h *****************/
7883 /************** Begin file btree.h *******************************************/
7884 /*
7885 ** 2001 September 15
7886 **
7887 ** The author disclaims copyright to this source code.  In place of
7888 ** a legal notice, here is a blessing:
7889 **
7890 **    May you do good and not evil.
7891 **    May you find forgiveness for yourself and forgive others.
7892 **    May you share freely, never taking more than you give.
7893 **
7894 *************************************************************************
7895 ** This header file defines the interface that the sqlite B-Tree file
7896 ** subsystem.  See comments in the source code for a detailed description
7897 ** of what each interface routine does.
7898 */
7899 #ifndef _BTREE_H_
7900 #define _BTREE_H_
7901
7902 /* TODO: This definition is just included so other modules compile. It
7903 ** needs to be revisited.
7904 */
7905 #define SQLITE_N_BTREE_META 10
7906
7907 /*
7908 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
7909 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
7910 */
7911 #ifndef SQLITE_DEFAULT_AUTOVACUUM
7912   #define SQLITE_DEFAULT_AUTOVACUUM 0
7913 #endif
7914
7915 #define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
7916 #define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
7917 #define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
7918
7919 /*
7920 ** Forward declarations of structure
7921 */
7922 typedef struct Btree Btree;
7923 typedef struct BtCursor BtCursor;
7924 typedef struct BtShared BtShared;
7925
7926
7927 SQLITE_PRIVATE int sqlite3BtreeOpen(
7928   sqlite3_vfs *pVfs,       /* VFS to use with this b-tree */
7929   const char *zFilename,   /* Name of database file to open */
7930   sqlite3 *db,             /* Associated database connection */
7931   Btree **ppBtree,         /* Return open Btree* here */
7932   int flags,               /* Flags */
7933   int vfsFlags             /* Flags passed through to VFS open */
7934 );
7935
7936 /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
7937 ** following values.
7938 **
7939 ** NOTE:  These values must match the corresponding PAGER_ values in
7940 ** pager.h.
7941 */
7942 #define BTREE_OMIT_JOURNAL  1  /* Do not create or use a rollback journal */
7943 #define BTREE_NO_READLOCK   2  /* Omit readlocks on readonly files */
7944 #define BTREE_MEMORY        4  /* This is an in-memory DB */
7945 #define BTREE_SINGLE        8  /* The file contains at most 1 b-tree */
7946 #define BTREE_UNORDERED    16  /* Use of a hash implementation is OK */
7947
7948 SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
7949 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
7950 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int,int);
7951 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
7952 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
7953 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
7954 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
7955 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
7956 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
7957 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
7958 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
7959 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
7960 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
7961 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
7962 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
7963 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
7964 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*);
7965 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
7966 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
7967 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
7968 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
7969 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
7970 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
7971 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
7972 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
7973 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
7974
7975 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
7976 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
7977 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
7978
7979 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
7980
7981 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
7982 ** of the flags shown below.
7983 **
7984 ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
7985 ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
7986 ** is stored in the leaves.  (BTREE_INTKEY is used for SQL tables.)  With
7987 ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
7988 ** anywhere - the key is the content.  (BTREE_BLOBKEY is used for SQL
7989 ** indices.)
7990 */
7991 #define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
7992 #define BTREE_BLOBKEY    2    /* Table has keys only - no data */
7993
7994 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
7995 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
7996 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
7997
7998 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
7999 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
8000
8001 /*
8002 ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
8003 ** should be one of the following values. The integer values are assigned 
8004 ** to constants so that the offset of the corresponding field in an
8005 ** SQLite database header may be found using the following formula:
8006 **
8007 **   offset = 36 + (idx * 4)
8008 **
8009 ** For example, the free-page-count field is located at byte offset 36 of
8010 ** the database file header. The incr-vacuum-flag field is located at
8011 ** byte offset 64 (== 36+4*7).
8012 */
8013 #define BTREE_FREE_PAGE_COUNT     0
8014 #define BTREE_SCHEMA_VERSION      1
8015 #define BTREE_FILE_FORMAT         2
8016 #define BTREE_DEFAULT_CACHE_SIZE  3
8017 #define BTREE_LARGEST_ROOT_PAGE   4
8018 #define BTREE_TEXT_ENCODING       5
8019 #define BTREE_USER_VERSION        6
8020 #define BTREE_INCR_VACUUM         7
8021
8022 SQLITE_PRIVATE int sqlite3BtreeCursor(
8023   Btree*,                              /* BTree containing table to open */
8024   int iTable,                          /* Index of root page */
8025   int wrFlag,                          /* 1 for writing.  0 for read-only */
8026   struct KeyInfo*,                     /* First argument to compare function */
8027   BtCursor *pCursor                    /* Space to write cursor structure */
8028 );
8029 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
8030 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
8031
8032 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
8033 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
8034   BtCursor*,
8035   UnpackedRecord *pUnKey,
8036   i64 intKey,
8037   int bias,
8038   int *pRes
8039 );
8040 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
8041 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
8042 SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
8043                                   const void *pData, int nData,
8044                                   int nZero, int bias, int seekResult);
8045 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
8046 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
8047 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
8048 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
8049 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
8050 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
8051 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
8052 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
8053 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
8054 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
8055 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
8056 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
8057 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*);
8058
8059 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
8060 SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
8061
8062 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
8063 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
8064 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
8065
8066 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
8067
8068 #ifndef NDEBUG
8069 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
8070 #endif
8071
8072 #ifndef SQLITE_OMIT_BTREECOUNT
8073 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
8074 #endif
8075
8076 #ifdef SQLITE_TEST
8077 SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
8078 SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
8079 #endif
8080
8081 #ifndef SQLITE_OMIT_WAL
8082 SQLITE_PRIVATE   int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
8083 #endif
8084
8085 /*
8086 ** If we are not using shared cache, then there is no need to
8087 ** use mutexes to access the BtShared structures.  So make the
8088 ** Enter and Leave procedures no-ops.
8089 */
8090 #ifndef SQLITE_OMIT_SHARED_CACHE
8091 SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
8092 SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
8093 #else
8094 # define sqlite3BtreeEnter(X) 
8095 # define sqlite3BtreeEnterAll(X)
8096 #endif
8097
8098 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
8099 SQLITE_PRIVATE   int sqlite3BtreeSharable(Btree*);
8100 SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
8101 SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
8102 SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
8103 SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
8104 #ifndef NDEBUG
8105   /* These routines are used inside assert() statements only. */
8106 SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
8107 SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
8108 SQLITE_PRIVATE   int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
8109 #endif
8110 #else
8111
8112 # define sqlite3BtreeSharable(X) 0
8113 # define sqlite3BtreeLeave(X)
8114 # define sqlite3BtreeEnterCursor(X)
8115 # define sqlite3BtreeLeaveCursor(X)
8116 # define sqlite3BtreeLeaveAll(X)
8117
8118 # define sqlite3BtreeHoldsMutex(X) 1
8119 # define sqlite3BtreeHoldsAllMutexes(X) 1
8120 # define sqlite3SchemaMutexHeld(X,Y,Z) 1
8121 #endif
8122
8123
8124 #endif /* _BTREE_H_ */
8125
8126 /************** End of btree.h ***********************************************/
8127 /************** Continuing where we left off in sqliteInt.h ******************/
8128 /************** Include vdbe.h in the middle of sqliteInt.h ******************/
8129 /************** Begin file vdbe.h ********************************************/
8130 /*
8131 ** 2001 September 15
8132 **
8133 ** The author disclaims copyright to this source code.  In place of
8134 ** a legal notice, here is a blessing:
8135 **
8136 **    May you do good and not evil.
8137 **    May you find forgiveness for yourself and forgive others.
8138 **    May you share freely, never taking more than you give.
8139 **
8140 *************************************************************************
8141 ** Header file for the Virtual DataBase Engine (VDBE)
8142 **
8143 ** This header defines the interface to the virtual database engine
8144 ** or VDBE.  The VDBE implements an abstract machine that runs a
8145 ** simple program to access and modify the underlying database.
8146 */
8147 #ifndef _SQLITE_VDBE_H_
8148 #define _SQLITE_VDBE_H_
8149
8150 /*
8151 ** A single VDBE is an opaque structure named "Vdbe".  Only routines
8152 ** in the source file sqliteVdbe.c are allowed to see the insides
8153 ** of this structure.
8154 */
8155 typedef struct Vdbe Vdbe;
8156
8157 /*
8158 ** The names of the following types declared in vdbeInt.h are required
8159 ** for the VdbeOp definition.
8160 */
8161 typedef struct VdbeFunc VdbeFunc;
8162 typedef struct Mem Mem;
8163 typedef struct SubProgram SubProgram;
8164
8165 /*
8166 ** A single instruction of the virtual machine has an opcode
8167 ** and as many as three operands.  The instruction is recorded
8168 ** as an instance of the following structure:
8169 */
8170 struct VdbeOp {
8171   u8 opcode;          /* What operation to perform */
8172   signed char p4type; /* One of the P4_xxx constants for p4 */
8173   u8 opflags;         /* Mask of the OPFLG_* flags in opcodes.h */
8174   u8 p5;              /* Fifth parameter is an unsigned character */
8175   int p1;             /* First operand */
8176   int p2;             /* Second parameter (often the jump destination) */
8177   int p3;             /* The third parameter */
8178   union {             /* fourth parameter */
8179     int i;                 /* Integer value if p4type==P4_INT32 */
8180     void *p;               /* Generic pointer */
8181     char *z;               /* Pointer to data for string (char array) types */
8182     i64 *pI64;             /* Used when p4type is P4_INT64 */
8183     double *pReal;         /* Used when p4type is P4_REAL */
8184     FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
8185     VdbeFunc *pVdbeFunc;   /* Used when p4type is P4_VDBEFUNC */
8186     CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
8187     Mem *pMem;             /* Used when p4type is P4_MEM */
8188     VTable *pVtab;         /* Used when p4type is P4_VTAB */
8189     KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
8190     int *ai;               /* Used when p4type is P4_INTARRAY */
8191     SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
8192   } p4;
8193 #ifdef SQLITE_DEBUG
8194   char *zComment;          /* Comment to improve readability */
8195 #endif
8196 #ifdef VDBE_PROFILE
8197   int cnt;                 /* Number of times this instruction was executed */
8198   u64 cycles;              /* Total time spent executing this instruction */
8199 #endif
8200 };
8201 typedef struct VdbeOp VdbeOp;
8202
8203
8204 /*
8205 ** A sub-routine used to implement a trigger program.
8206 */
8207 struct SubProgram {
8208   VdbeOp *aOp;                  /* Array of opcodes for sub-program */
8209   int nOp;                      /* Elements in aOp[] */
8210   int nMem;                     /* Number of memory cells required */
8211   int nCsr;                     /* Number of cursors required */
8212   void *token;                  /* id that may be used to recursive triggers */
8213   SubProgram *pNext;            /* Next sub-program already visited */
8214 };
8215
8216 /*
8217 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
8218 ** it takes up less space.
8219 */
8220 struct VdbeOpList {
8221   u8 opcode;          /* What operation to perform */
8222   signed char p1;     /* First operand */
8223   signed char p2;     /* Second parameter (often the jump destination) */
8224   signed char p3;     /* Third parameter */
8225 };
8226 typedef struct VdbeOpList VdbeOpList;
8227
8228 /*
8229 ** Allowed values of VdbeOp.p4type
8230 */
8231 #define P4_NOTUSED    0   /* The P4 parameter is not used */
8232 #define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
8233 #define P4_STATIC   (-2)  /* Pointer to a static string */
8234 #define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
8235 #define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
8236 #define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
8237 #define P4_VDBEFUNC (-7)  /* P4 is a pointer to a VdbeFunc structure */
8238 #define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
8239 #define P4_TRANSIENT  0   /* P4 is a pointer to a transient string */
8240 #define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */
8241 #define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */
8242 #define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
8243 #define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
8244 #define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
8245 #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
8246 #define P4_SUBPROGRAM  (-18) /* P4 is a pointer to a SubProgram structure */
8247
8248 /* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
8249 ** is made.  That copy is freed when the Vdbe is finalized.  But if the
8250 ** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used.  It still
8251 ** gets freed when the Vdbe is finalized so it still should be obtained
8252 ** from a single sqliteMalloc().  But no copy is made and the calling
8253 ** function should *not* try to free the KeyInfo.
8254 */
8255 #define P4_KEYINFO_HANDOFF (-16)
8256 #define P4_KEYINFO_STATIC  (-17)
8257
8258 /*
8259 ** The Vdbe.aColName array contains 5n Mem structures, where n is the 
8260 ** number of columns of data returned by the statement.
8261 */
8262 #define COLNAME_NAME     0
8263 #define COLNAME_DECLTYPE 1
8264 #define COLNAME_DATABASE 2
8265 #define COLNAME_TABLE    3
8266 #define COLNAME_COLUMN   4
8267 #ifdef SQLITE_ENABLE_COLUMN_METADATA
8268 # define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
8269 #else
8270 # ifdef SQLITE_OMIT_DECLTYPE
8271 #   define COLNAME_N      1      /* Store only the name */
8272 # else
8273 #   define COLNAME_N      2      /* Store the name and decltype */
8274 # endif
8275 #endif
8276
8277 /*
8278 ** The following macro converts a relative address in the p2 field
8279 ** of a VdbeOp structure into a negative number so that 
8280 ** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
8281 ** the macro again restores the address.
8282 */
8283 #define ADDR(X)  (-1-(X))
8284
8285 /*
8286 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
8287 ** header file that defines a number for each opcode used by the VDBE.
8288 */
8289 /************** Include opcodes.h in the middle of vdbe.h ********************/
8290 /************** Begin file opcodes.h *****************************************/
8291 /* Automatically generated.  Do not edit */
8292 /* See the mkopcodeh.awk script for details */
8293 #define OP_Goto                                 1
8294 #define OP_Gosub                                2
8295 #define OP_Return                               3
8296 #define OP_Yield                                4
8297 #define OP_HaltIfNull                           5
8298 #define OP_Halt                                 6
8299 #define OP_Integer                              7
8300 #define OP_Int64                                8
8301 #define OP_Real                               130   /* same as TK_FLOAT    */
8302 #define OP_String8                             94   /* same as TK_STRING   */
8303 #define OP_String                               9
8304 #define OP_Null                                10
8305 #define OP_Blob                                11
8306 #define OP_Variable                            12
8307 #define OP_Move                                13
8308 #define OP_Copy                                14
8309 #define OP_SCopy                               15
8310 #define OP_ResultRow                           16
8311 #define OP_Concat                              91   /* same as TK_CONCAT   */
8312 #define OP_Add                                 86   /* same as TK_PLUS     */
8313 #define OP_Subtract                            87   /* same as TK_MINUS    */
8314 #define OP_Multiply                            88   /* same as TK_STAR     */
8315 #define OP_Divide                              89   /* same as TK_SLASH    */
8316 #define OP_Remainder                           90   /* same as TK_REM      */
8317 #define OP_CollSeq                             17
8318 #define OP_Function                            18
8319 #define OP_BitAnd                              82   /* same as TK_BITAND   */
8320 #define OP_BitOr                               83   /* same as TK_BITOR    */
8321 #define OP_ShiftLeft                           84   /* same as TK_LSHIFT   */
8322 #define OP_ShiftRight                          85   /* same as TK_RSHIFT   */
8323 #define OP_AddImm                              20
8324 #define OP_MustBeInt                           21
8325 #define OP_RealAffinity                        22
8326 #define OP_ToText                             141   /* same as TK_TO_TEXT  */
8327 #define OP_ToBlob                             142   /* same as TK_TO_BLOB  */
8328 #define OP_ToNumeric                          143   /* same as TK_TO_NUMERIC*/
8329 #define OP_ToInt                              144   /* same as TK_TO_INT   */
8330 #define OP_ToReal                             145   /* same as TK_TO_REAL  */
8331 #define OP_Eq                                  76   /* same as TK_EQ       */
8332 #define OP_Ne                                  75   /* same as TK_NE       */
8333 #define OP_Lt                                  79   /* same as TK_LT       */
8334 #define OP_Le                                  78   /* same as TK_LE       */
8335 #define OP_Gt                                  77   /* same as TK_GT       */
8336 #define OP_Ge                                  80   /* same as TK_GE       */
8337 #define OP_Permutation                         23
8338 #define OP_Compare                             24
8339 #define OP_Jump                                25
8340 #define OP_And                                 69   /* same as TK_AND      */
8341 #define OP_Or                                  68   /* same as TK_OR       */
8342 #define OP_Not                                 19   /* same as TK_NOT      */
8343 #define OP_BitNot                              93   /* same as TK_BITNOT   */
8344 #define OP_If                                  26
8345 #define OP_IfNot                               27
8346 #define OP_IsNull                              73   /* same as TK_ISNULL   */
8347 #define OP_NotNull                             74   /* same as TK_NOTNULL  */
8348 #define OP_Column                              28
8349 #define OP_Affinity                            29
8350 #define OP_MakeRecord                          30
8351 #define OP_Count                               31
8352 #define OP_Savepoint                           32
8353 #define OP_AutoCommit                          33
8354 #define OP_Transaction                         34
8355 #define OP_ReadCookie                          35
8356 #define OP_SetCookie                           36
8357 #define OP_VerifyCookie                        37
8358 #define OP_OpenRead                            38
8359 #define OP_OpenWrite                           39
8360 #define OP_OpenAutoindex                       40
8361 #define OP_OpenEphemeral                       41
8362 #define OP_OpenPseudo                          42
8363 #define OP_Close                               43
8364 #define OP_SeekLt                              44
8365 #define OP_SeekLe                              45
8366 #define OP_SeekGe                              46
8367 #define OP_SeekGt                              47
8368 #define OP_Seek                                48
8369 #define OP_NotFound                            49
8370 #define OP_Found                               50
8371 #define OP_IsUnique                            51
8372 #define OP_NotExists                           52
8373 #define OP_Sequence                            53
8374 #define OP_NewRowid                            54
8375 #define OP_Insert                              55
8376 #define OP_InsertInt                           56
8377 #define OP_Delete                              57
8378 #define OP_ResetCount                          58
8379 #define OP_RowKey                              59
8380 #define OP_RowData                             60
8381 #define OP_Rowid                               61
8382 #define OP_NullRow                             62
8383 #define OP_Last                                63
8384 #define OP_Sort                                64
8385 #define OP_Rewind                              65
8386 #define OP_Prev                                66
8387 #define OP_Next                                67
8388 #define OP_IdxInsert                           70
8389 #define OP_IdxDelete                           71
8390 #define OP_IdxRowid                            72
8391 #define OP_IdxLT                               81
8392 #define OP_IdxGE                               92
8393 #define OP_Destroy                             95
8394 #define OP_Clear                               96
8395 #define OP_CreateIndex                         97
8396 #define OP_CreateTable                         98
8397 #define OP_ParseSchema                         99
8398 #define OP_LoadAnalysis                       100
8399 #define OP_DropTable                          101
8400 #define OP_DropIndex                          102
8401 #define OP_DropTrigger                        103
8402 #define OP_IntegrityCk                        104
8403 #define OP_RowSetAdd                          105
8404 #define OP_RowSetRead                         106
8405 #define OP_RowSetTest                         107
8406 #define OP_Program                            108
8407 #define OP_Param                              109
8408 #define OP_FkCounter                          110
8409 #define OP_FkIfZero                           111
8410 #define OP_MemMax                             112
8411 #define OP_IfPos                              113
8412 #define OP_IfNeg                              114
8413 #define OP_IfZero                             115
8414 #define OP_AggStep                            116
8415 #define OP_AggFinal                           117
8416 #define OP_Checkpoint                         118
8417 #define OP_JournalMode                        119
8418 #define OP_Vacuum                             120
8419 #define OP_IncrVacuum                         121
8420 #define OP_Expire                             122
8421 #define OP_TableLock                          123
8422 #define OP_VBegin                             124
8423 #define OP_VCreate                            125
8424 #define OP_VDestroy                           126
8425 #define OP_VOpen                              127
8426 #define OP_VFilter                            128
8427 #define OP_VColumn                            129
8428 #define OP_VNext                              131
8429 #define OP_VRename                            132
8430 #define OP_VUpdate                            133
8431 #define OP_Pagecount                          134
8432 #define OP_MaxPgcnt                           135
8433 #define OP_Trace                              136
8434 #define OP_Noop                               137
8435 #define OP_Explain                            138
8436
8437 /* The following opcode values are never used */
8438 #define OP_NotUsed_139                        139
8439 #define OP_NotUsed_140                        140
8440
8441
8442 /* Properties such as "out2" or "jump" that are specified in
8443 ** comments following the "case" for each opcode in the vdbe.c
8444 ** are encoded into bitvectors as follows:
8445 */
8446 #define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */
8447 #define OPFLG_OUT2_PRERELEASE 0x0002  /* out2-prerelease: */
8448 #define OPFLG_IN1             0x0004  /* in1:   P1 is an input */
8449 #define OPFLG_IN2             0x0008  /* in2:   P2 is an input */
8450 #define OPFLG_IN3             0x0010  /* in3:   P3 is an input */
8451 #define OPFLG_OUT2            0x0020  /* out2:  P2 is an output */
8452 #define OPFLG_OUT3            0x0040  /* out3:  P3 is an output */
8453 #define OPFLG_INITIALIZER {\
8454 /*   0 */ 0x00, 0x01, 0x05, 0x04, 0x04, 0x10, 0x00, 0x02,\
8455 /*   8 */ 0x02, 0x02, 0x02, 0x02, 0x02, 0x00, 0x24, 0x24,\
8456 /*  16 */ 0x00, 0x00, 0x00, 0x24, 0x04, 0x05, 0x04, 0x00,\
8457 /*  24 */ 0x00, 0x01, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02,\
8458 /*  32 */ 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00, 0x00,\
8459 /*  40 */ 0x00, 0x00, 0x00, 0x00, 0x11, 0x11, 0x11, 0x11,\
8460 /*  48 */ 0x08, 0x11, 0x11, 0x11, 0x11, 0x02, 0x02, 0x00,\
8461 /*  56 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01,\
8462 /*  64 */ 0x01, 0x01, 0x01, 0x01, 0x4c, 0x4c, 0x08, 0x00,\
8463 /*  72 */ 0x02, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
8464 /*  80 */ 0x15, 0x01, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\
8465 /*  88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x01, 0x24, 0x02, 0x02,\
8466 /*  96 */ 0x00, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,\
8467 /* 104 */ 0x00, 0x0c, 0x45, 0x15, 0x01, 0x02, 0x00, 0x01,\
8468 /* 112 */ 0x08, 0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02,\
8469 /* 120 */ 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
8470 /* 128 */ 0x01, 0x00, 0x02, 0x01, 0x00, 0x00, 0x02, 0x02,\
8471 /* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04,\
8472 /* 144 */ 0x04, 0x04,}
8473
8474 /************** End of opcodes.h *********************************************/
8475 /************** Continuing where we left off in vdbe.h ***********************/
8476
8477 /*
8478 ** Prototypes for the VDBE interface.  See comments on the implementation
8479 ** for a description of what each of these routines does.
8480 */
8481 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
8482 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
8483 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
8484 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
8485 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
8486 SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
8487 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
8488 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
8489 SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
8490 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);
8491 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
8492 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3);
8493 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
8494 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
8495 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N);
8496 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
8497 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
8498 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
8499 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
8500 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
8501 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
8502 SQLITE_PRIVATE void sqlite3VdbeDeleteObject(sqlite3*,Vdbe*);
8503 SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
8504 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
8505 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
8506 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
8507 #ifdef SQLITE_DEBUG
8508 SQLITE_PRIVATE   int sqlite3VdbeAssertMayAbort(Vdbe *, int);
8509 SQLITE_PRIVATE   void sqlite3VdbeTrace(Vdbe*,FILE*);
8510 #endif
8511 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
8512 SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
8513 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
8514 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
8515 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
8516 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
8517 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
8518 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
8519 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
8520 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
8521 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8);
8522 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
8523 #ifndef SQLITE_OMIT_TRACE
8524 SQLITE_PRIVATE   char *sqlite3VdbeExpandSql(Vdbe*, const char*);
8525 #endif
8526
8527 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,char*,int);
8528 SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord*);
8529 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
8530
8531 #ifndef SQLITE_OMIT_TRIGGER
8532 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
8533 #endif
8534
8535
8536 #ifndef NDEBUG
8537 SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
8538 # define VdbeComment(X)  sqlite3VdbeComment X
8539 SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
8540 # define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
8541 #else
8542 # define VdbeComment(X)
8543 # define VdbeNoopComment(X)
8544 #endif
8545
8546 #endif
8547
8548 /************** End of vdbe.h ************************************************/
8549 /************** Continuing where we left off in sqliteInt.h ******************/
8550 /************** Include pager.h in the middle of sqliteInt.h *****************/
8551 /************** Begin file pager.h *******************************************/
8552 /*
8553 ** 2001 September 15
8554 **
8555 ** The author disclaims copyright to this source code.  In place of
8556 ** a legal notice, here is a blessing:
8557 **
8558 **    May you do good and not evil.
8559 **    May you find forgiveness for yourself and forgive others.
8560 **    May you share freely, never taking more than you give.
8561 **
8562 *************************************************************************
8563 ** This header file defines the interface that the sqlite page cache
8564 ** subsystem.  The page cache subsystem reads and writes a file a page
8565 ** at a time and provides a journal for rollback.
8566 */
8567
8568 #ifndef _PAGER_H_
8569 #define _PAGER_H_
8570
8571 /*
8572 ** Default maximum size for persistent journal files. A negative 
8573 ** value means no limit. This value may be overridden using the 
8574 ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
8575 */
8576 #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
8577   #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
8578 #endif
8579
8580 /*
8581 ** The type used to represent a page number.  The first page in a file
8582 ** is called page 1.  0 is used to represent "not a page".
8583 */
8584 typedef u32 Pgno;
8585
8586 /*
8587 ** Each open file is managed by a separate instance of the "Pager" structure.
8588 */
8589 typedef struct Pager Pager;
8590
8591 /*
8592 ** Handle type for pages.
8593 */
8594 typedef struct PgHdr DbPage;
8595
8596 /*
8597 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
8598 ** reserved for working around a windows/posix incompatibility). It is
8599 ** used in the journal to signify that the remainder of the journal file 
8600 ** is devoted to storing a master journal name - there are no more pages to
8601 ** roll back. See comments for function writeMasterJournal() in pager.c 
8602 ** for details.
8603 */
8604 #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
8605
8606 /*
8607 ** Allowed values for the flags parameter to sqlite3PagerOpen().
8608 **
8609 ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
8610 */
8611 #define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
8612 #define PAGER_NO_READLOCK   0x0002    /* Omit readlocks on readonly files */
8613 #define PAGER_MEMORY        0x0004    /* In-memory database */
8614
8615 /*
8616 ** Valid values for the second argument to sqlite3PagerLockingMode().
8617 */
8618 #define PAGER_LOCKINGMODE_QUERY      -1
8619 #define PAGER_LOCKINGMODE_NORMAL      0
8620 #define PAGER_LOCKINGMODE_EXCLUSIVE   1
8621
8622 /*
8623 ** Numeric constants that encode the journalmode.  
8624 */
8625 #define PAGER_JOURNALMODE_QUERY     (-1)  /* Query the value of journalmode */
8626 #define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
8627 #define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
8628 #define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
8629 #define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
8630 #define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
8631 #define PAGER_JOURNALMODE_WAL         5   /* Use write-ahead logging */
8632
8633 /*
8634 ** The remainder of this file contains the declarations of the functions
8635 ** that make up the Pager sub-system API. See source code comments for 
8636 ** a detailed description of each routine.
8637 */
8638
8639 /* Open and close a Pager connection. */ 
8640 SQLITE_PRIVATE int sqlite3PagerOpen(
8641   sqlite3_vfs*,
8642   Pager **ppPager,
8643   const char*,
8644   int,
8645   int,
8646   int,
8647   void(*)(DbPage*)
8648 );
8649 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
8650 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
8651
8652 /* Functions used to configure a Pager object. */
8653 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
8654 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
8655 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
8656 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
8657 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int,int);
8658 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
8659 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
8660 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
8661 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
8662 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
8663 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
8664
8665 /* Functions used to obtain and release page references. */ 
8666 SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
8667 #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
8668 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
8669 SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
8670 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
8671
8672 /* Operations on page references. */
8673 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
8674 SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
8675 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
8676 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
8677 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *); 
8678 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *); 
8679
8680 /* Functions used to manage pager transactions and savepoints. */
8681 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
8682 SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
8683 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
8684 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
8685 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
8686 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
8687 SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
8688 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
8689 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
8690 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
8691
8692 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
8693 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
8694 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
8695 SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
8696 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager);
8697
8698 /* Functions used to query pager state and configuration. */
8699 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
8700 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
8701 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
8702 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*);
8703 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
8704 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
8705 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
8706 SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
8707 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
8708 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
8709
8710 /* Functions used to truncate the database file. */
8711 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
8712
8713 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
8714 SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
8715 #endif
8716
8717 /* Functions to support testing and debugging. */
8718 #if !defined(NDEBUG) || defined(SQLITE_TEST)
8719 SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
8720 SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
8721 #endif
8722 #ifdef SQLITE_TEST
8723 SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
8724 SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
8725   void disable_simulated_io_errors(void);
8726   void enable_simulated_io_errors(void);
8727 #else
8728 # define disable_simulated_io_errors()
8729 # define enable_simulated_io_errors()
8730 #endif
8731
8732 #endif /* _PAGER_H_ */
8733
8734 /************** End of pager.h ***********************************************/
8735 /************** Continuing where we left off in sqliteInt.h ******************/
8736 /************** Include pcache.h in the middle of sqliteInt.h ****************/
8737 /************** Begin file pcache.h ******************************************/
8738 /*
8739 ** 2008 August 05
8740 **
8741 ** The author disclaims copyright to this source code.  In place of
8742 ** a legal notice, here is a blessing:
8743 **
8744 **    May you do good and not evil.
8745 **    May you find forgiveness for yourself and forgive others.
8746 **    May you share freely, never taking more than you give.
8747 **
8748 *************************************************************************
8749 ** This header file defines the interface that the sqlite page cache
8750 ** subsystem. 
8751 */
8752
8753 #ifndef _PCACHE_H_
8754
8755 typedef struct PgHdr PgHdr;
8756 typedef struct PCache PCache;
8757
8758 /*
8759 ** Every page in the cache is controlled by an instance of the following
8760 ** structure.
8761 */
8762 struct PgHdr {
8763   void *pData;                   /* Content of this page */
8764   void *pExtra;                  /* Extra content */
8765   PgHdr *pDirty;                 /* Transient list of dirty pages */
8766   Pgno pgno;                     /* Page number for this page */
8767   Pager *pPager;                 /* The pager this page is part of */
8768 #ifdef SQLITE_CHECK_PAGES
8769   u32 pageHash;                  /* Hash of page content */
8770 #endif
8771   u16 flags;                     /* PGHDR flags defined below */
8772
8773   /**********************************************************************
8774   ** Elements above are public.  All that follows is private to pcache.c
8775   ** and should not be accessed by other modules.
8776   */
8777   i16 nRef;                      /* Number of users of this page */
8778   PCache *pCache;                /* Cache that owns this page */
8779
8780   PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
8781   PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
8782 };
8783
8784 /* Bit values for PgHdr.flags */
8785 #define PGHDR_DIRTY             0x002  /* Page has changed */
8786 #define PGHDR_NEED_SYNC         0x004  /* Fsync the rollback journal before
8787                                        ** writing this page to the database */
8788 #define PGHDR_NEED_READ         0x008  /* Content is unread */
8789 #define PGHDR_REUSE_UNLIKELY    0x010  /* A hint that reuse is unlikely */
8790 #define PGHDR_DONT_WRITE        0x020  /* Do not write content to disk */
8791
8792 /* Initialize and shutdown the page cache subsystem */
8793 SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
8794 SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
8795
8796 /* Page cache buffer management:
8797 ** These routines implement SQLITE_CONFIG_PAGECACHE.
8798 */
8799 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
8800
8801 /* Create a new pager cache.
8802 ** Under memory stress, invoke xStress to try to make pages clean.
8803 ** Only clean and unpinned pages can be reclaimed.
8804 */
8805 SQLITE_PRIVATE void sqlite3PcacheOpen(
8806   int szPage,                    /* Size of every page */
8807   int szExtra,                   /* Extra space associated with each page */
8808   int bPurgeable,                /* True if pages are on backing store */
8809   int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
8810   void *pStress,                 /* Argument to xStress */
8811   PCache *pToInit                /* Preallocated space for the PCache */
8812 );
8813
8814 /* Modify the page-size after the cache has been created. */
8815 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
8816
8817 /* Return the size in bytes of a PCache object.  Used to preallocate
8818 ** storage space.
8819 */
8820 SQLITE_PRIVATE int sqlite3PcacheSize(void);
8821
8822 /* One release per successful fetch.  Page is pinned until released.
8823 ** Reference counted. 
8824 */
8825 SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
8826 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
8827
8828 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
8829 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
8830 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
8831 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
8832
8833 /* Change a page number.  Used by incr-vacuum. */
8834 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
8835
8836 /* Remove all pages with pgno>x.  Reset the cache if x==0 */
8837 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
8838
8839 /* Get a list of all dirty pages in the cache, sorted by page number */
8840 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
8841
8842 /* Reset and close the cache object */
8843 SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
8844
8845 /* Clear flags from pages of the page cache */
8846 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
8847
8848 /* Discard the contents of the cache */
8849 SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
8850
8851 /* Return the total number of outstanding page references */
8852 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
8853
8854 /* Increment the reference count of an existing page */
8855 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
8856
8857 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
8858
8859 /* Return the total number of pages stored in the cache */
8860 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
8861
8862 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
8863 /* Iterate through all dirty pages currently stored in the cache. This
8864 ** interface is only available if SQLITE_CHECK_PAGES is defined when the 
8865 ** library is built.
8866 */
8867 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
8868 #endif
8869
8870 /* Set and get the suggested cache-size for the specified pager-cache.
8871 **
8872 ** If no global maximum is configured, then the system attempts to limit
8873 ** the total number of pages cached by purgeable pager-caches to the sum
8874 ** of the suggested cache-sizes.
8875 */
8876 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
8877 #ifdef SQLITE_TEST
8878 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
8879 #endif
8880
8881 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
8882 /* Try to return memory used by the pcache module to the main memory heap */
8883 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
8884 #endif
8885
8886 #ifdef SQLITE_TEST
8887 SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
8888 #endif
8889
8890 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
8891
8892 #endif /* _PCACHE_H_ */
8893
8894 /************** End of pcache.h **********************************************/
8895 /************** Continuing where we left off in sqliteInt.h ******************/
8896
8897 /************** Include os.h in the middle of sqliteInt.h ********************/
8898 /************** Begin file os.h **********************************************/
8899 /*
8900 ** 2001 September 16
8901 **
8902 ** The author disclaims copyright to this source code.  In place of
8903 ** a legal notice, here is a blessing:
8904 **
8905 **    May you do good and not evil.
8906 **    May you find forgiveness for yourself and forgive others.
8907 **    May you share freely, never taking more than you give.
8908 **
8909 ******************************************************************************
8910 **
8911 ** This header file (together with is companion C source-code file
8912 ** "os.c") attempt to abstract the underlying operating system so that
8913 ** the SQLite library will work on both POSIX and windows systems.
8914 **
8915 ** This header file is #include-ed by sqliteInt.h and thus ends up
8916 ** being included by every source file.
8917 */
8918 #ifndef _SQLITE_OS_H_
8919 #define _SQLITE_OS_H_
8920
8921 /*
8922 ** Figure out if we are dealing with Unix, Windows, or some other
8923 ** operating system.  After the following block of preprocess macros,
8924 ** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, SQLITE_OS_OS2, and SQLITE_OS_OTHER 
8925 ** will defined to either 1 or 0.  One of the four will be 1.  The other 
8926 ** three will be 0.
8927 */
8928 #if defined(SQLITE_OS_OTHER)
8929 # if SQLITE_OS_OTHER==1
8930 #   undef SQLITE_OS_UNIX
8931 #   define SQLITE_OS_UNIX 0
8932 #   undef SQLITE_OS_WIN
8933 #   define SQLITE_OS_WIN 0
8934 #   undef SQLITE_OS_OS2
8935 #   define SQLITE_OS_OS2 0
8936 # else
8937 #   undef SQLITE_OS_OTHER
8938 # endif
8939 #endif
8940 #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
8941 # define SQLITE_OS_OTHER 0
8942 # ifndef SQLITE_OS_WIN
8943 #   if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
8944 #     define SQLITE_OS_WIN 1
8945 #     define SQLITE_OS_UNIX 0
8946 #     define SQLITE_OS_OS2 0
8947 #   elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__)
8948 #     define SQLITE_OS_WIN 0
8949 #     define SQLITE_OS_UNIX 0
8950 #     define SQLITE_OS_OS2 1
8951 #   else
8952 #     define SQLITE_OS_WIN 0
8953 #     define SQLITE_OS_UNIX 1
8954 #     define SQLITE_OS_OS2 0
8955 #  endif
8956 # else
8957 #  define SQLITE_OS_UNIX 0
8958 #  define SQLITE_OS_OS2 0
8959 # endif
8960 #else
8961 # ifndef SQLITE_OS_WIN
8962 #  define SQLITE_OS_WIN 0
8963 # endif
8964 #endif
8965
8966 /*
8967 ** Determine if we are dealing with WindowsCE - which has a much
8968 ** reduced API.
8969 */
8970 #if defined(_WIN32_WCE)
8971 # define SQLITE_OS_WINCE 1
8972 #else
8973 # define SQLITE_OS_WINCE 0
8974 #endif
8975
8976
8977 /*
8978 ** Define the maximum size of a temporary filename
8979 */
8980 #if SQLITE_OS_WIN
8981 # include <windows.h>
8982 # define SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
8983 #elif SQLITE_OS_OS2
8984 # if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY)
8985 #  include <os2safe.h> /* has to be included before os2.h for linking to work */
8986 # endif
8987 # define INCL_DOSDATETIME
8988 # define INCL_DOSFILEMGR
8989 # define INCL_DOSERRORS
8990 # define INCL_DOSMISC
8991 # define INCL_DOSPROCESS
8992 # define INCL_DOSMODULEMGR
8993 # define INCL_DOSSEMAPHORES
8994 # include <os2.h>
8995 # include <uconv.h>
8996 # define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP)
8997 #else
8998 # define SQLITE_TEMPNAME_SIZE 200
8999 #endif
9000
9001 /* If the SET_FULLSYNC macro is not defined above, then make it
9002 ** a no-op
9003 */
9004 #ifndef SET_FULLSYNC
9005 # define SET_FULLSYNC(x,y)
9006 #endif
9007
9008 /*
9009 ** The default size of a disk sector
9010 */
9011 #ifndef SQLITE_DEFAULT_SECTOR_SIZE
9012 # define SQLITE_DEFAULT_SECTOR_SIZE 512
9013 #endif
9014
9015 /*
9016 ** Temporary files are named starting with this prefix followed by 16 random
9017 ** alphanumeric characters, and no file extension. They are stored in the
9018 ** OS's standard temporary file directory, and are deleted prior to exit.
9019 ** If sqlite is being embedded in another program, you may wish to change the
9020 ** prefix to reflect your program's name, so that if your program exits
9021 ** prematurely, old temporary files can be easily identified. This can be done
9022 ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
9023 **
9024 ** 2006-10-31:  The default prefix used to be "sqlite_".  But then
9025 ** Mcafee started using SQLite in their anti-virus product and it
9026 ** started putting files with the "sqlite" name in the c:/temp folder.
9027 ** This annoyed many windows users.  Those users would then do a 
9028 ** Google search for "sqlite", find the telephone numbers of the
9029 ** developers and call to wake them up at night and complain.
9030 ** For this reason, the default name prefix is changed to be "sqlite" 
9031 ** spelled backwards.  So the temp files are still identified, but
9032 ** anybody smart enough to figure out the code is also likely smart
9033 ** enough to know that calling the developer will not help get rid
9034 ** of the file.
9035 */
9036 #ifndef SQLITE_TEMP_FILE_PREFIX
9037 # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
9038 #endif
9039
9040 /*
9041 ** The following values may be passed as the second argument to
9042 ** sqlite3OsLock(). The various locks exhibit the following semantics:
9043 **
9044 ** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
9045 ** RESERVED:  A single process may hold a RESERVED lock on a file at
9046 **            any time. Other processes may hold and obtain new SHARED locks.
9047 ** PENDING:   A single process may hold a PENDING lock on a file at
9048 **            any one time. Existing SHARED locks may persist, but no new
9049 **            SHARED locks may be obtained by other processes.
9050 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
9051 **
9052 ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
9053 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
9054 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
9055 ** sqlite3OsLock().
9056 */
9057 #define NO_LOCK         0
9058 #define SHARED_LOCK     1
9059 #define RESERVED_LOCK   2
9060 #define PENDING_LOCK    3
9061 #define EXCLUSIVE_LOCK  4
9062
9063 /*
9064 ** File Locking Notes:  (Mostly about windows but also some info for Unix)
9065 **
9066 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
9067 ** those functions are not available.  So we use only LockFile() and
9068 ** UnlockFile().
9069 **
9070 ** LockFile() prevents not just writing but also reading by other processes.
9071 ** A SHARED_LOCK is obtained by locking a single randomly-chosen 
9072 ** byte out of a specific range of bytes. The lock byte is obtained at 
9073 ** random so two separate readers can probably access the file at the 
9074 ** same time, unless they are unlucky and choose the same lock byte.
9075 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
9076 ** There can only be one writer.  A RESERVED_LOCK is obtained by locking
9077 ** a single byte of the file that is designated as the reserved lock byte.
9078 ** A PENDING_LOCK is obtained by locking a designated byte different from
9079 ** the RESERVED_LOCK byte.
9080 **
9081 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
9082 ** which means we can use reader/writer locks.  When reader/writer locks
9083 ** are used, the lock is placed on the same range of bytes that is used
9084 ** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
9085 ** will support two or more Win95 readers or two or more WinNT readers.
9086 ** But a single Win95 reader will lock out all WinNT readers and a single
9087 ** WinNT reader will lock out all other Win95 readers.
9088 **
9089 ** The following #defines specify the range of bytes used for locking.
9090 ** SHARED_SIZE is the number of bytes available in the pool from which
9091 ** a random byte is selected for a shared lock.  The pool of bytes for
9092 ** shared locks begins at SHARED_FIRST. 
9093 **
9094 ** The same locking strategy and
9095 ** byte ranges are used for Unix.  This leaves open the possiblity of having
9096 ** clients on win95, winNT, and unix all talking to the same shared file
9097 ** and all locking correctly.  To do so would require that samba (or whatever
9098 ** tool is being used for file sharing) implements locks correctly between
9099 ** windows and unix.  I'm guessing that isn't likely to happen, but by
9100 ** using the same locking range we are at least open to the possibility.
9101 **
9102 ** Locking in windows is manditory.  For this reason, we cannot store
9103 ** actual data in the bytes used for locking.  The pager never allocates
9104 ** the pages involved in locking therefore.  SHARED_SIZE is selected so
9105 ** that all locks will fit on a single page even at the minimum page size.
9106 ** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
9107 ** is set high so that we don't have to allocate an unused page except
9108 ** for very large databases.  But one should test the page skipping logic 
9109 ** by setting PENDING_BYTE low and running the entire regression suite.
9110 **
9111 ** Changing the value of PENDING_BYTE results in a subtly incompatible
9112 ** file format.  Depending on how it is changed, you might not notice
9113 ** the incompatibility right away, even running a full regression test.
9114 ** The default location of PENDING_BYTE is the first byte past the
9115 ** 1GB boundary.
9116 **
9117 */
9118 #ifdef SQLITE_OMIT_WSD
9119 # define PENDING_BYTE     (0x40000000)
9120 #else
9121 # define PENDING_BYTE      sqlite3PendingByte
9122 #endif
9123 #define RESERVED_BYTE     (PENDING_BYTE+1)
9124 #define SHARED_FIRST      (PENDING_BYTE+2)
9125 #define SHARED_SIZE       510
9126
9127 /*
9128 ** Wrapper around OS specific sqlite3_os_init() function.
9129 */
9130 SQLITE_PRIVATE int sqlite3OsInit(void);
9131
9132 /* 
9133 ** Functions for accessing sqlite3_file methods 
9134 */
9135 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
9136 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
9137 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
9138 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
9139 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
9140 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
9141 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
9142 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
9143 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
9144 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
9145 #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
9146 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
9147 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
9148 SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
9149 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
9150 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
9151 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
9152
9153 /* 
9154 ** Functions for accessing sqlite3_vfs methods 
9155 */
9156 SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
9157 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
9158 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
9159 SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
9160 #ifndef SQLITE_OMIT_LOAD_EXTENSION
9161 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
9162 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
9163 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
9164 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
9165 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
9166 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
9167 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
9168 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
9169
9170 /*
9171 ** Convenience functions for opening and closing files using 
9172 ** sqlite3_malloc() to obtain space for the file-handle structure.
9173 */
9174 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
9175 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
9176
9177 #endif /* _SQLITE_OS_H_ */
9178
9179 /************** End of os.h **************************************************/
9180 /************** Continuing where we left off in sqliteInt.h ******************/
9181 /************** Include mutex.h in the middle of sqliteInt.h *****************/
9182 /************** Begin file mutex.h *******************************************/
9183 /*
9184 ** 2007 August 28
9185 **
9186 ** The author disclaims copyright to this source code.  In place of
9187 ** a legal notice, here is a blessing:
9188 **
9189 **    May you do good and not evil.
9190 **    May you find forgiveness for yourself and forgive others.
9191 **    May you share freely, never taking more than you give.
9192 **
9193 *************************************************************************
9194 **
9195 ** This file contains the common header for all mutex implementations.
9196 ** The sqliteInt.h header #includes this file so that it is available
9197 ** to all source files.  We break it out in an effort to keep the code
9198 ** better organized.
9199 **
9200 ** NOTE:  source files should *not* #include this header file directly.
9201 ** Source files should #include the sqliteInt.h file and let that file
9202 ** include this one indirectly.
9203 */
9204
9205
9206 /*
9207 ** Figure out what version of the code to use.  The choices are
9208 **
9209 **   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
9210 **                             mutexes implemention cannot be overridden
9211 **                             at start-time.
9212 **
9213 **   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
9214 **                             mutual exclusion is provided.  But this
9215 **                             implementation can be overridden at
9216 **                             start-time.
9217 **
9218 **   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
9219 **
9220 **   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
9221 **
9222 **   SQLITE_MUTEX_OS2          For multi-threaded applications on OS/2.
9223 */
9224 #if !SQLITE_THREADSAFE
9225 # define SQLITE_MUTEX_OMIT
9226 #endif
9227 #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
9228 #  if SQLITE_OS_UNIX
9229 #    define SQLITE_MUTEX_PTHREADS
9230 #  elif SQLITE_OS_WIN
9231 #    define SQLITE_MUTEX_W32
9232 #  elif SQLITE_OS_OS2
9233 #    define SQLITE_MUTEX_OS2
9234 #  else
9235 #    define SQLITE_MUTEX_NOOP
9236 #  endif
9237 #endif
9238
9239 #ifdef SQLITE_MUTEX_OMIT
9240 /*
9241 ** If this is a no-op implementation, implement everything as macros.
9242 */
9243 #define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
9244 #define sqlite3_mutex_free(X)
9245 #define sqlite3_mutex_enter(X)
9246 #define sqlite3_mutex_try(X)      SQLITE_OK
9247 #define sqlite3_mutex_leave(X)
9248 #define sqlite3_mutex_held(X)     ((void)(X),1)
9249 #define sqlite3_mutex_notheld(X)  ((void)(X),1)
9250 #define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
9251 #define sqlite3MutexInit()        SQLITE_OK
9252 #define sqlite3MutexEnd()
9253 #endif /* defined(SQLITE_MUTEX_OMIT) */
9254
9255 /************** End of mutex.h ***********************************************/
9256 /************** Continuing where we left off in sqliteInt.h ******************/
9257
9258
9259 /*
9260 ** Each database file to be accessed by the system is an instance
9261 ** of the following structure.  There are normally two of these structures
9262 ** in the sqlite.aDb[] array.  aDb[0] is the main database file and
9263 ** aDb[1] is the database file used to hold temporary tables.  Additional
9264 ** databases may be attached.
9265 */
9266 struct Db {
9267   char *zName;         /* Name of this database */
9268   Btree *pBt;          /* The B*Tree structure for this database file */
9269   u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
9270   u8 safety_level;     /* How aggressive at syncing data to disk */
9271   Schema *pSchema;     /* Pointer to database schema (possibly shared) */
9272 };
9273
9274 /*
9275 ** An instance of the following structure stores a database schema.
9276 **
9277 ** Most Schema objects are associated with a Btree.  The exception is
9278 ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
9279 ** In shared cache mode, a single Schema object can be shared by multiple
9280 ** Btrees that refer to the same underlying BtShared object.
9281 ** 
9282 ** Schema objects are automatically deallocated when the last Btree that
9283 ** references them is destroyed.   The TEMP Schema is manually freed by
9284 ** sqlite3_close().
9285 *
9286 ** A thread must be holding a mutex on the corresponding Btree in order
9287 ** to access Schema content.  This implies that the thread must also be
9288 ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
9289 ** For a TEMP Schema, only the connection mutex is required.
9290 */
9291 struct Schema {
9292   int schema_cookie;   /* Database schema version number for this file */
9293   int iGeneration;     /* Generation counter.  Incremented with each change */
9294   Hash tblHash;        /* All tables indexed by name */
9295   Hash idxHash;        /* All (named) indices indexed by name */
9296   Hash trigHash;       /* All triggers indexed by name */
9297   Hash fkeyHash;       /* All foreign keys by referenced table name */
9298   Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
9299   u8 file_format;      /* Schema format version for this file */
9300   u8 enc;              /* Text encoding used by this database */
9301   u16 flags;           /* Flags associated with this schema */
9302   int cache_size;      /* Number of pages to use in the cache */
9303 };
9304
9305 /*
9306 ** These macros can be used to test, set, or clear bits in the 
9307 ** Db.pSchema->flags field.
9308 */
9309 #define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
9310 #define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
9311 #define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
9312 #define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)
9313
9314 /*
9315 ** Allowed values for the DB.pSchema->flags field.
9316 **
9317 ** The DB_SchemaLoaded flag is set after the database schema has been
9318 ** read into internal hash tables.
9319 **
9320 ** DB_UnresetViews means that one or more views have column names that
9321 ** have been filled out.  If the schema changes, these column names might
9322 ** changes and so the view will need to be reset.
9323 */
9324 #define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
9325 #define DB_UnresetViews    0x0002  /* Some views have defined column names */
9326 #define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
9327
9328 /*
9329 ** The number of different kinds of things that can be limited
9330 ** using the sqlite3_limit() interface.
9331 */
9332 #define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
9333
9334 /*
9335 ** Lookaside malloc is a set of fixed-size buffers that can be used
9336 ** to satisfy small transient memory allocation requests for objects
9337 ** associated with a particular database connection.  The use of
9338 ** lookaside malloc provides a significant performance enhancement
9339 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
9340 ** SQL statements.
9341 **
9342 ** The Lookaside structure holds configuration information about the
9343 ** lookaside malloc subsystem.  Each available memory allocation in
9344 ** the lookaside subsystem is stored on a linked list of LookasideSlot
9345 ** objects.
9346 **
9347 ** Lookaside allocations are only allowed for objects that are associated
9348 ** with a particular database connection.  Hence, schema information cannot
9349 ** be stored in lookaside because in shared cache mode the schema information
9350 ** is shared by multiple database connections.  Therefore, while parsing
9351 ** schema information, the Lookaside.bEnabled flag is cleared so that
9352 ** lookaside allocations are not used to construct the schema objects.
9353 */
9354 struct Lookaside {
9355   u16 sz;                 /* Size of each buffer in bytes */
9356   u8 bEnabled;            /* False to disable new lookaside allocations */
9357   u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
9358   int nOut;               /* Number of buffers currently checked out */
9359   int mxOut;              /* Highwater mark for nOut */
9360   int anStat[3];          /* 0: hits.  1: size misses.  2: full misses */
9361   LookasideSlot *pFree;   /* List of available buffers */
9362   void *pStart;           /* First byte of available memory space */
9363   void *pEnd;             /* First byte past end of available space */
9364 };
9365 struct LookasideSlot {
9366   LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
9367 };
9368
9369 /*
9370 ** A hash table for function definitions.
9371 **
9372 ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
9373 ** Collisions are on the FuncDef.pHash chain.
9374 */
9375 struct FuncDefHash {
9376   FuncDef *a[23];       /* Hash table for functions */
9377 };
9378
9379 /*
9380 ** Each database connection is an instance of the following structure.
9381 **
9382 ** The sqlite.lastRowid records the last insert rowid generated by an
9383 ** insert statement.  Inserts on views do not affect its value.  Each
9384 ** trigger has its own context, so that lastRowid can be updated inside
9385 ** triggers as usual.  The previous value will be restored once the trigger
9386 ** exits.  Upon entering a before or instead of trigger, lastRowid is no
9387 ** longer (since after version 2.8.12) reset to -1.
9388 **
9389 ** The sqlite.nChange does not count changes within triggers and keeps no
9390 ** context.  It is reset at start of sqlite3_exec.
9391 ** The sqlite.lsChange represents the number of changes made by the last
9392 ** insert, update, or delete statement.  It remains constant throughout the
9393 ** length of a statement and is then updated by OP_SetCounts.  It keeps a
9394 ** context stack just like lastRowid so that the count of changes
9395 ** within a trigger is not seen outside the trigger.  Changes to views do not
9396 ** affect the value of lsChange.
9397 ** The sqlite.csChange keeps track of the number of current changes (since
9398 ** the last statement) and is used to update sqlite_lsChange.
9399 **
9400 ** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16
9401 ** store the most recent error code and, if applicable, string. The
9402 ** internal function sqlite3Error() is used to set these variables
9403 ** consistently.
9404 */
9405 struct sqlite3 {
9406   sqlite3_vfs *pVfs;            /* OS Interface */
9407   int nDb;                      /* Number of backends currently in use */
9408   Db *aDb;                      /* All backends */
9409   int flags;                    /* Miscellaneous flags. See below */
9410   unsigned int openFlags;       /* Flags passed to sqlite3_vfs.xOpen() */
9411   int errCode;                  /* Most recent error code (SQLITE_*) */
9412   int errMask;                  /* & result codes with this before returning */
9413   u8 autoCommit;                /* The auto-commit flag. */
9414   u8 temp_store;                /* 1: file 2: memory 0: default */
9415   u8 mallocFailed;              /* True if we have seen a malloc failure */
9416   u8 dfltLockMode;              /* Default locking-mode for attached dbs */
9417   signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
9418   u8 suppressErr;               /* Do not issue error messages if true */
9419   u8 vtabOnConflict;            /* Value to return for s3_vtab_on_conflict() */
9420   int nextPagesize;             /* Pagesize after VACUUM if >0 */
9421   int nTable;                   /* Number of tables in the database */
9422   CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
9423   i64 lastRowid;                /* ROWID of most recent insert (see above) */
9424   u32 magic;                    /* Magic number for detect library misuse */
9425   int nChange;                  /* Value returned by sqlite3_changes() */
9426   int nTotalChange;             /* Value returned by sqlite3_total_changes() */
9427   sqlite3_mutex *mutex;         /* Connection mutex */
9428   int aLimit[SQLITE_N_LIMIT];   /* Limits */
9429   struct sqlite3InitInfo {      /* Information used during initialization */
9430     int iDb;                    /* When back is being initialized */
9431     int newTnum;                /* Rootpage of table being initialized */
9432     u8 busy;                    /* TRUE if currently initializing */
9433     u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */
9434   } init;
9435   int nExtension;               /* Number of loaded extensions */
9436   void **aExtension;            /* Array of shared library handles */
9437   struct Vdbe *pVdbe;           /* List of active virtual machines */
9438   int activeVdbeCnt;            /* Number of VDBEs currently executing */
9439   int writeVdbeCnt;             /* Number of active VDBEs that are writing */
9440   int vdbeExecCnt;              /* Number of nested calls to VdbeExec() */
9441   void (*xTrace)(void*,const char*);        /* Trace function */
9442   void *pTraceArg;                          /* Argument to the trace function */
9443   void (*xProfile)(void*,const char*,u64);  /* Profiling function */
9444   void *pProfileArg;                        /* Argument to profile function */
9445   void *pCommitArg;                 /* Argument to xCommitCallback() */   
9446   int (*xCommitCallback)(void*);    /* Invoked at every commit. */
9447   void *pRollbackArg;               /* Argument to xRollbackCallback() */   
9448   void (*xRollbackCallback)(void*); /* Invoked at every commit. */
9449   void *pUpdateArg;
9450   void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
9451 #ifndef SQLITE_OMIT_WAL
9452   int (*xWalCallback)(void *, sqlite3 *, const char *, int);
9453   void *pWalArg;
9454 #endif
9455   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
9456   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
9457   void *pCollNeededArg;
9458   sqlite3_value *pErr;          /* Most recent error message */
9459   char *zErrMsg;                /* Most recent error message (UTF-8 encoded) */
9460   char *zErrMsg16;              /* Most recent error message (UTF-16 encoded) */
9461   union {
9462     volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
9463     double notUsed1;            /* Spacer */
9464   } u1;
9465   Lookaside lookaside;          /* Lookaside malloc configuration */
9466 #ifndef SQLITE_OMIT_AUTHORIZATION
9467   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
9468                                 /* Access authorization function */
9469   void *pAuthArg;               /* 1st argument to the access auth function */
9470 #endif
9471 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
9472   int (*xProgress)(void *);     /* The progress callback */
9473   void *pProgressArg;           /* Argument to the progress callback */
9474   int nProgressOps;             /* Number of opcodes for progress callback */
9475 #endif
9476 #ifndef SQLITE_OMIT_VIRTUALTABLE
9477   Hash aModule;                 /* populated by sqlite3_create_module() */
9478   VtabCtx *pVtabCtx;            /* Context for active vtab connect/create */
9479   VTable **aVTrans;             /* Virtual tables with open transactions */
9480   int nVTrans;                  /* Allocated size of aVTrans */
9481   VTable *pDisconnect;    /* Disconnect these in next sqlite3_prepare() */
9482 #endif
9483   FuncDefHash aFunc;            /* Hash table of connection functions */
9484   Hash aCollSeq;                /* All collating sequences */
9485   BusyHandler busyHandler;      /* Busy callback */
9486   int busyTimeout;              /* Busy handler timeout, in msec */
9487   Db aDbStatic[2];              /* Static space for the 2 default backends */
9488   Savepoint *pSavepoint;        /* List of active savepoints */
9489   int nSavepoint;               /* Number of non-transaction savepoints */
9490   int nStatement;               /* Number of nested statement-transactions  */
9491   u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
9492   i64 nDeferredCons;            /* Net deferred constraints this transaction. */
9493   int *pnBytesFreed;            /* If not NULL, increment this in DbFree() */
9494
9495 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
9496   /* The following variables are all protected by the STATIC_MASTER 
9497   ** mutex, not by sqlite3.mutex. They are used by code in notify.c. 
9498   **
9499   ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
9500   ** unlock so that it can proceed.
9501   **
9502   ** When X.pBlockingConnection==Y, that means that something that X tried
9503   ** tried to do recently failed with an SQLITE_LOCKED error due to locks
9504   ** held by Y.
9505   */
9506   sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
9507   sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
9508   void *pUnlockArg;                     /* Argument to xUnlockNotify */
9509   void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
9510   sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
9511 #endif
9512 };
9513
9514 /*
9515 ** A macro to discover the encoding of a database.
9516 */
9517 #define ENC(db) ((db)->aDb[0].pSchema->enc)
9518
9519 /*
9520 ** Possible values for the sqlite3.flags.
9521 */
9522 #define SQLITE_VdbeTrace      0x00000100  /* True to trace VDBE execution */
9523 #define SQLITE_InternChanges  0x00000200  /* Uncommitted Hash table changes */
9524 #define SQLITE_FullColNames   0x00000400  /* Show full column names on SELECT */
9525 #define SQLITE_ShortColNames  0x00000800  /* Show short columns names */
9526 #define SQLITE_CountRows      0x00001000  /* Count rows changed by INSERT, */
9527                                           /*   DELETE, or UPDATE and return */
9528                                           /*   the count using a callback. */
9529 #define SQLITE_NullCallback   0x00002000  /* Invoke the callback once if the */
9530                                           /*   result set is empty */
9531 #define SQLITE_SqlTrace       0x00004000  /* Debug print SQL as it executes */
9532 #define SQLITE_VdbeListing    0x00008000  /* Debug listings of VDBE programs */
9533 #define SQLITE_WriteSchema    0x00010000  /* OK to update SQLITE_MASTER */
9534 #define SQLITE_NoReadlock     0x00020000  /* Readlocks are omitted when 
9535                                           ** accessing read-only databases */
9536 #define SQLITE_IgnoreChecks   0x00040000  /* Do not enforce check constraints */
9537 #define SQLITE_ReadUncommitted 0x0080000  /* For shared-cache mode */
9538 #define SQLITE_LegacyFileFmt  0x00100000  /* Create new databases in format 1 */
9539 #define SQLITE_FullFSync      0x00200000  /* Use full fsync on the backend */
9540 #define SQLITE_CkptFullFSync  0x00400000  /* Use full fsync for checkpoint */
9541 #define SQLITE_RecoveryMode   0x00800000  /* Ignore schema errors */
9542 #define SQLITE_ReverseOrder   0x01000000  /* Reverse unordered SELECTs */
9543 #define SQLITE_RecTriggers    0x02000000  /* Enable recursive triggers */
9544 #define SQLITE_ForeignKeys    0x04000000  /* Enforce foreign key constraints  */
9545 #define SQLITE_AutoIndex      0x08000000  /* Enable automatic indexes */
9546 #define SQLITE_PreferBuiltin  0x10000000  /* Preference to built-in funcs */
9547 #define SQLITE_LoadExtension  0x20000000  /* Enable load_extension */
9548 #define SQLITE_EnableTrigger  0x40000000  /* True to enable triggers */
9549
9550 /*
9551 ** Bits of the sqlite3.flags field that are used by the
9552 ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface.
9553 ** These must be the low-order bits of the flags field.
9554 */
9555 #define SQLITE_QueryFlattener 0x01        /* Disable query flattening */
9556 #define SQLITE_ColumnCache    0x02        /* Disable the column cache */
9557 #define SQLITE_IndexSort      0x04        /* Disable indexes for sorting */
9558 #define SQLITE_IndexSearch    0x08        /* Disable indexes for searching */
9559 #define SQLITE_IndexCover     0x10        /* Disable index covering table */
9560 #define SQLITE_GroupByOrder   0x20        /* Disable GROUPBY cover of ORDERBY */
9561 #define SQLITE_FactorOutConst 0x40        /* Disable factoring out constants */
9562 #define SQLITE_IdxRealAsInt   0x80        /* Store REAL as INT in indices */
9563 #define SQLITE_OptMask        0xff        /* Mask of all disablable opts */
9564
9565 /*
9566 ** Possible values for the sqlite.magic field.
9567 ** The numbers are obtained at random and have no special meaning, other
9568 ** than being distinct from one another.
9569 */
9570 #define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
9571 #define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
9572 #define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
9573 #define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
9574 #define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
9575
9576 /*
9577 ** Each SQL function is defined by an instance of the following
9578 ** structure.  A pointer to this structure is stored in the sqlite.aFunc
9579 ** hash table.  When multiple functions have the same name, the hash table
9580 ** points to a linked list of these structures.
9581 */
9582 struct FuncDef {
9583   i16 nArg;            /* Number of arguments.  -1 means unlimited */
9584   u8 iPrefEnc;         /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
9585   u8 flags;            /* Some combination of SQLITE_FUNC_* */
9586   void *pUserData;     /* User data parameter */
9587   FuncDef *pNext;      /* Next function with same name */
9588   void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
9589   void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
9590   void (*xFinalize)(sqlite3_context*);                /* Aggregate finalizer */
9591   char *zName;         /* SQL name of the function. */
9592   FuncDef *pHash;      /* Next with a different name but the same hash */
9593   FuncDestructor *pDestructor;   /* Reference counted destructor function */
9594 };
9595
9596 /*
9597 ** This structure encapsulates a user-function destructor callback (as
9598 ** configured using create_function_v2()) and a reference counter. When
9599 ** create_function_v2() is called to create a function with a destructor,
9600 ** a single object of this type is allocated. FuncDestructor.nRef is set to 
9601 ** the number of FuncDef objects created (either 1 or 3, depending on whether
9602 ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
9603 ** member of each of the new FuncDef objects is set to point to the allocated
9604 ** FuncDestructor.
9605 **
9606 ** Thereafter, when one of the FuncDef objects is deleted, the reference
9607 ** count on this object is decremented. When it reaches 0, the destructor
9608 ** is invoked and the FuncDestructor structure freed.
9609 */
9610 struct FuncDestructor {
9611   int nRef;
9612   void (*xDestroy)(void *);
9613   void *pUserData;
9614 };
9615
9616 /*
9617 ** Possible values for FuncDef.flags
9618 */
9619 #define SQLITE_FUNC_LIKE     0x01 /* Candidate for the LIKE optimization */
9620 #define SQLITE_FUNC_CASE     0x02 /* Case-sensitive LIKE-type function */
9621 #define SQLITE_FUNC_EPHEM    0x04 /* Ephemeral.  Delete with VDBE */
9622 #define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */
9623 #define SQLITE_FUNC_PRIVATE  0x10 /* Allowed for internal use only */
9624 #define SQLITE_FUNC_COUNT    0x20 /* Built-in count(*) aggregate */
9625 #define SQLITE_FUNC_COALESCE 0x40 /* Built-in coalesce() or ifnull() function */
9626
9627 /*
9628 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
9629 ** used to create the initializers for the FuncDef structures.
9630 **
9631 **   FUNCTION(zName, nArg, iArg, bNC, xFunc)
9632 **     Used to create a scalar function definition of a function zName 
9633 **     implemented by C function xFunc that accepts nArg arguments. The
9634 **     value passed as iArg is cast to a (void*) and made available
9635 **     as the user-data (sqlite3_user_data()) for the function. If 
9636 **     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
9637 **
9638 **   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
9639 **     Used to create an aggregate function definition implemented by
9640 **     the C functions xStep and xFinal. The first four parameters
9641 **     are interpreted in the same way as the first 4 parameters to
9642 **     FUNCTION().
9643 **
9644 **   LIKEFUNC(zName, nArg, pArg, flags)
9645 **     Used to create a scalar function definition of a function zName 
9646 **     that accepts nArg arguments and is implemented by a call to C 
9647 **     function likeFunc. Argument pArg is cast to a (void *) and made
9648 **     available as the function user-data (sqlite3_user_data()). The
9649 **     FuncDef.flags variable is set to the value passed as the flags
9650 **     parameter.
9651 */
9652 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
9653   {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
9654    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
9655 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
9656   {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
9657    pArg, 0, xFunc, 0, 0, #zName, 0, 0}
9658 #define LIKEFUNC(zName, nArg, arg, flags) \
9659   {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
9660 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
9661   {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \
9662    SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
9663
9664 /*
9665 ** All current savepoints are stored in a linked list starting at
9666 ** sqlite3.pSavepoint. The first element in the list is the most recently
9667 ** opened savepoint. Savepoints are added to the list by the vdbe
9668 ** OP_Savepoint instruction.
9669 */
9670 struct Savepoint {
9671   char *zName;                        /* Savepoint name (nul-terminated) */
9672   i64 nDeferredCons;                  /* Number of deferred fk violations */
9673   Savepoint *pNext;                   /* Parent savepoint (if any) */
9674 };
9675
9676 /*
9677 ** The following are used as the second parameter to sqlite3Savepoint(),
9678 ** and as the P1 argument to the OP_Savepoint instruction.
9679 */
9680 #define SAVEPOINT_BEGIN      0
9681 #define SAVEPOINT_RELEASE    1
9682 #define SAVEPOINT_ROLLBACK   2
9683
9684
9685 /*
9686 ** Each SQLite module (virtual table definition) is defined by an
9687 ** instance of the following structure, stored in the sqlite3.aModule
9688 ** hash table.
9689 */
9690 struct Module {
9691   const sqlite3_module *pModule;       /* Callback pointers */
9692   const char *zName;                   /* Name passed to create_module() */
9693   void *pAux;                          /* pAux passed to create_module() */
9694   void (*xDestroy)(void *);            /* Module destructor function */
9695 };
9696
9697 /*
9698 ** information about each column of an SQL table is held in an instance
9699 ** of this structure.
9700 */
9701 struct Column {
9702   char *zName;     /* Name of this column */
9703   Expr *pDflt;     /* Default value of this column */
9704   char *zDflt;     /* Original text of the default value */
9705   char *zType;     /* Data type for this column */
9706   char *zColl;     /* Collating sequence.  If NULL, use the default */
9707   u8 notNull;      /* True if there is a NOT NULL constraint */
9708   u8 isPrimKey;    /* True if this column is part of the PRIMARY KEY */
9709   char affinity;   /* One of the SQLITE_AFF_... values */
9710 #ifndef SQLITE_OMIT_VIRTUALTABLE
9711   u8 isHidden;     /* True if this column is 'hidden' */
9712 #endif
9713 };
9714
9715 /*
9716 ** A "Collating Sequence" is defined by an instance of the following
9717 ** structure. Conceptually, a collating sequence consists of a name and
9718 ** a comparison routine that defines the order of that sequence.
9719 **
9720 ** There may two separate implementations of the collation function, one
9721 ** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
9722 ** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
9723 ** native byte order. When a collation sequence is invoked, SQLite selects
9724 ** the version that will require the least expensive encoding
9725 ** translations, if any.
9726 **
9727 ** The CollSeq.pUser member variable is an extra parameter that passed in
9728 ** as the first argument to the UTF-8 comparison function, xCmp.
9729 ** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
9730 ** xCmp16.
9731 **
9732 ** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
9733 ** collating sequence is undefined.  Indices built on an undefined
9734 ** collating sequence may not be read or written.
9735 */
9736 struct CollSeq {
9737   char *zName;          /* Name of the collating sequence, UTF-8 encoded */
9738   u8 enc;               /* Text encoding handled by xCmp() */
9739   u8 type;              /* One of the SQLITE_COLL_... values below */
9740   void *pUser;          /* First argument to xCmp() */
9741   int (*xCmp)(void*,int, const void*, int, const void*);
9742   void (*xDel)(void*);  /* Destructor for pUser */
9743 };
9744
9745 /*
9746 ** Allowed values of CollSeq.type:
9747 */
9748 #define SQLITE_COLL_BINARY  1  /* The default memcmp() collating sequence */
9749 #define SQLITE_COLL_NOCASE  2  /* The built-in NOCASE collating sequence */
9750 #define SQLITE_COLL_REVERSE 3  /* The built-in REVERSE collating sequence */
9751 #define SQLITE_COLL_USER    0  /* Any other user-defined collating sequence */
9752
9753 /*
9754 ** A sort order can be either ASC or DESC.
9755 */
9756 #define SQLITE_SO_ASC       0  /* Sort in ascending order */
9757 #define SQLITE_SO_DESC      1  /* Sort in ascending order */
9758
9759 /*
9760 ** Column affinity types.
9761 **
9762 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
9763 ** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
9764 ** the speed a little by numbering the values consecutively.  
9765 **
9766 ** But rather than start with 0 or 1, we begin with 'a'.  That way,
9767 ** when multiple affinity types are concatenated into a string and
9768 ** used as the P4 operand, they will be more readable.
9769 **
9770 ** Note also that the numeric types are grouped together so that testing
9771 ** for a numeric type is a single comparison.
9772 */
9773 #define SQLITE_AFF_TEXT     'a'
9774 #define SQLITE_AFF_NONE     'b'
9775 #define SQLITE_AFF_NUMERIC  'c'
9776 #define SQLITE_AFF_INTEGER  'd'
9777 #define SQLITE_AFF_REAL     'e'
9778
9779 #define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
9780
9781 /*
9782 ** The SQLITE_AFF_MASK values masks off the significant bits of an
9783 ** affinity value. 
9784 */
9785 #define SQLITE_AFF_MASK     0x67
9786
9787 /*
9788 ** Additional bit values that can be ORed with an affinity without
9789 ** changing the affinity.
9790 */
9791 #define SQLITE_JUMPIFNULL   0x08  /* jumps if either operand is NULL */
9792 #define SQLITE_STOREP2      0x10  /* Store result in reg[P2] rather than jump */
9793 #define SQLITE_NULLEQ       0x80  /* NULL=NULL */
9794
9795 /*
9796 ** An object of this type is created for each virtual table present in
9797 ** the database schema. 
9798 **
9799 ** If the database schema is shared, then there is one instance of this
9800 ** structure for each database connection (sqlite3*) that uses the shared
9801 ** schema. This is because each database connection requires its own unique
9802 ** instance of the sqlite3_vtab* handle used to access the virtual table 
9803 ** implementation. sqlite3_vtab* handles can not be shared between 
9804 ** database connections, even when the rest of the in-memory database 
9805 ** schema is shared, as the implementation often stores the database
9806 ** connection handle passed to it via the xConnect() or xCreate() method
9807 ** during initialization internally. This database connection handle may
9808 ** then be used by the virtual table implementation to access real tables 
9809 ** within the database. So that they appear as part of the callers 
9810 ** transaction, these accesses need to be made via the same database 
9811 ** connection as that used to execute SQL operations on the virtual table.
9812 **
9813 ** All VTable objects that correspond to a single table in a shared
9814 ** database schema are initially stored in a linked-list pointed to by
9815 ** the Table.pVTable member variable of the corresponding Table object.
9816 ** When an sqlite3_prepare() operation is required to access the virtual
9817 ** table, it searches the list for the VTable that corresponds to the
9818 ** database connection doing the preparing so as to use the correct
9819 ** sqlite3_vtab* handle in the compiled query.
9820 **
9821 ** When an in-memory Table object is deleted (for example when the
9822 ** schema is being reloaded for some reason), the VTable objects are not 
9823 ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed 
9824 ** immediately. Instead, they are moved from the Table.pVTable list to
9825 ** another linked list headed by the sqlite3.pDisconnect member of the
9826 ** corresponding sqlite3 structure. They are then deleted/xDisconnected 
9827 ** next time a statement is prepared using said sqlite3*. This is done
9828 ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
9829 ** Refer to comments above function sqlite3VtabUnlockList() for an
9830 ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
9831 ** list without holding the corresponding sqlite3.mutex mutex.
9832 **
9833 ** The memory for objects of this type is always allocated by 
9834 ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as 
9835 ** the first argument.
9836 */
9837 struct VTable {
9838   sqlite3 *db;              /* Database connection associated with this table */
9839   Module *pMod;             /* Pointer to module implementation */
9840   sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
9841   int nRef;                 /* Number of pointers to this structure */
9842   u8 bConstraint;           /* True if constraints are supported */
9843   int iSavepoint;           /* Depth of the SAVEPOINT stack */
9844   VTable *pNext;            /* Next in linked list (see above) */
9845 };
9846
9847 /*
9848 ** Each SQL table is represented in memory by an instance of the
9849 ** following structure.
9850 **
9851 ** Table.zName is the name of the table.  The case of the original
9852 ** CREATE TABLE statement is stored, but case is not significant for
9853 ** comparisons.
9854 **
9855 ** Table.nCol is the number of columns in this table.  Table.aCol is a
9856 ** pointer to an array of Column structures, one for each column.
9857 **
9858 ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
9859 ** the column that is that key.   Otherwise Table.iPKey is negative.  Note
9860 ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
9861 ** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
9862 ** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
9863 ** is generated for each row of the table.  TF_HasPrimaryKey is set if
9864 ** the table has any PRIMARY KEY, INTEGER or otherwise.
9865 **
9866 ** Table.tnum is the page number for the root BTree page of the table in the
9867 ** database file.  If Table.iDb is the index of the database table backend
9868 ** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
9869 ** holds temporary tables and indices.  If TF_Ephemeral is set
9870 ** then the table is stored in a file that is automatically deleted
9871 ** when the VDBE cursor to the table is closed.  In this case Table.tnum 
9872 ** refers VDBE cursor number that holds the table open, not to the root
9873 ** page number.  Transient tables are used to hold the results of a
9874 ** sub-query that appears instead of a real table name in the FROM clause 
9875 ** of a SELECT statement.
9876 */
9877 struct Table {
9878   char *zName;         /* Name of the table or view */
9879   int iPKey;           /* If not negative, use aCol[iPKey] as the primary key */
9880   int nCol;            /* Number of columns in this table */
9881   Column *aCol;        /* Information about each column */
9882   Index *pIndex;       /* List of SQL indexes on this table. */
9883   int tnum;            /* Root BTree node for this table (see note above) */
9884   unsigned nRowEst;    /* Estimated rows in table - from sqlite_stat1 table */
9885   Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
9886   u16 nRef;            /* Number of pointers to this Table */
9887   u8 tabFlags;         /* Mask of TF_* values */
9888   u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
9889   FKey *pFKey;         /* Linked list of all foreign keys in this table */
9890   char *zColAff;       /* String defining the affinity of each column */
9891 #ifndef SQLITE_OMIT_CHECK
9892   Expr *pCheck;        /* The AND of all CHECK constraints */
9893 #endif
9894 #ifndef SQLITE_OMIT_ALTERTABLE
9895   int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
9896 #endif
9897 #ifndef SQLITE_OMIT_VIRTUALTABLE
9898   VTable *pVTable;     /* List of VTable objects. */
9899   int nModuleArg;      /* Number of arguments to the module */
9900   char **azModuleArg;  /* Text of all module args. [0] is module name */
9901 #endif
9902   Trigger *pTrigger;   /* List of triggers stored in pSchema */
9903   Schema *pSchema;     /* Schema that contains this table */
9904   Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
9905 };
9906
9907 /*
9908 ** Allowed values for Tabe.tabFlags.
9909 */
9910 #define TF_Readonly        0x01    /* Read-only system table */
9911 #define TF_Ephemeral       0x02    /* An ephemeral table */
9912 #define TF_HasPrimaryKey   0x04    /* Table has a primary key */
9913 #define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
9914 #define TF_Virtual         0x10    /* Is a virtual table */
9915 #define TF_NeedMetadata    0x20    /* aCol[].zType and aCol[].pColl missing */
9916
9917
9918
9919 /*
9920 ** Test to see whether or not a table is a virtual table.  This is
9921 ** done as a macro so that it will be optimized out when virtual
9922 ** table support is omitted from the build.
9923 */
9924 #ifndef SQLITE_OMIT_VIRTUALTABLE
9925 #  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
9926 #  define IsHiddenColumn(X) ((X)->isHidden)
9927 #else
9928 #  define IsVirtual(X)      0
9929 #  define IsHiddenColumn(X) 0
9930 #endif
9931
9932 /*
9933 ** Each foreign key constraint is an instance of the following structure.
9934 **
9935 ** A foreign key is associated with two tables.  The "from" table is
9936 ** the table that contains the REFERENCES clause that creates the foreign
9937 ** key.  The "to" table is the table that is named in the REFERENCES clause.
9938 ** Consider this example:
9939 **
9940 **     CREATE TABLE ex1(
9941 **       a INTEGER PRIMARY KEY,
9942 **       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
9943 **     );
9944 **
9945 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
9946 **
9947 ** Each REFERENCES clause generates an instance of the following structure
9948 ** which is attached to the from-table.  The to-table need not exist when
9949 ** the from-table is created.  The existence of the to-table is not checked.
9950 */
9951 struct FKey {
9952   Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
9953   FKey *pNextFrom;  /* Next foreign key in pFrom */
9954   char *zTo;        /* Name of table that the key points to (aka: Parent) */
9955   FKey *pNextTo;    /* Next foreign key on table named zTo */
9956   FKey *pPrevTo;    /* Previous foreign key on table named zTo */
9957   int nCol;         /* Number of columns in this key */
9958   /* EV: R-30323-21917 */
9959   u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */
9960   u8 aAction[2];          /* ON DELETE and ON UPDATE actions, respectively */
9961   Trigger *apTrigger[2];  /* Triggers for aAction[] actions */
9962   struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */
9963     int iFrom;         /* Index of column in pFrom */
9964     char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */
9965   } aCol[1];        /* One entry for each of nCol column s */
9966 };
9967
9968 /*
9969 ** SQLite supports many different ways to resolve a constraint
9970 ** error.  ROLLBACK processing means that a constraint violation
9971 ** causes the operation in process to fail and for the current transaction
9972 ** to be rolled back.  ABORT processing means the operation in process
9973 ** fails and any prior changes from that one operation are backed out,
9974 ** but the transaction is not rolled back.  FAIL processing means that
9975 ** the operation in progress stops and returns an error code.  But prior
9976 ** changes due to the same operation are not backed out and no rollback
9977 ** occurs.  IGNORE means that the particular row that caused the constraint
9978 ** error is not inserted or updated.  Processing continues and no error
9979 ** is returned.  REPLACE means that preexisting database rows that caused
9980 ** a UNIQUE constraint violation are removed so that the new insert or
9981 ** update can proceed.  Processing continues and no error is reported.
9982 **
9983 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
9984 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
9985 ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
9986 ** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
9987 ** referenced table row is propagated into the row that holds the
9988 ** foreign key.
9989 ** 
9990 ** The following symbolic values are used to record which type
9991 ** of action to take.
9992 */
9993 #define OE_None     0   /* There is no constraint to check */
9994 #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
9995 #define OE_Abort    2   /* Back out changes but do no rollback transaction */
9996 #define OE_Fail     3   /* Stop the operation but leave all prior changes */
9997 #define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
9998 #define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
9999
10000 #define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
10001 #define OE_SetNull  7   /* Set the foreign key value to NULL */
10002 #define OE_SetDflt  8   /* Set the foreign key value to its default */
10003 #define OE_Cascade  9   /* Cascade the changes */
10004
10005 #define OE_Default  99  /* Do whatever the default action is */
10006
10007
10008 /*
10009 ** An instance of the following structure is passed as the first
10010 ** argument to sqlite3VdbeKeyCompare and is used to control the 
10011 ** comparison of the two index keys.
10012 */
10013 struct KeyInfo {
10014   sqlite3 *db;        /* The database connection */
10015   u8 enc;             /* Text encoding - one of the SQLITE_UTF* values */
10016   u16 nField;         /* Number of entries in aColl[] */
10017   u8 *aSortOrder;     /* Sort order for each column.  May be NULL */
10018   CollSeq *aColl[1];  /* Collating sequence for each term of the key */
10019 };
10020
10021 /*
10022 ** An instance of the following structure holds information about a
10023 ** single index record that has already been parsed out into individual
10024 ** values.
10025 **
10026 ** A record is an object that contains one or more fields of data.
10027 ** Records are used to store the content of a table row and to store
10028 ** the key of an index.  A blob encoding of a record is created by
10029 ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
10030 ** OP_Column opcode.
10031 **
10032 ** This structure holds a record that has already been disassembled
10033 ** into its constituent fields.
10034 */
10035 struct UnpackedRecord {
10036   KeyInfo *pKeyInfo;  /* Collation and sort-order information */
10037   u16 nField;         /* Number of entries in apMem[] */
10038   u16 flags;          /* Boolean settings.  UNPACKED_... below */
10039   i64 rowid;          /* Used by UNPACKED_PREFIX_SEARCH */
10040   Mem *aMem;          /* Values */
10041 };
10042
10043 /*
10044 ** Allowed values of UnpackedRecord.flags
10045 */
10046 #define UNPACKED_NEED_FREE     0x0001  /* Memory is from sqlite3Malloc() */
10047 #define UNPACKED_NEED_DESTROY  0x0002  /* apMem[]s should all be destroyed */
10048 #define UNPACKED_IGNORE_ROWID  0x0004  /* Ignore trailing rowid on key1 */
10049 #define UNPACKED_INCRKEY       0x0008  /* Make this key an epsilon larger */
10050 #define UNPACKED_PREFIX_MATCH  0x0010  /* A prefix match is considered OK */
10051 #define UNPACKED_PREFIX_SEARCH 0x0020  /* A prefix match is considered OK */
10052
10053 /*
10054 ** Each SQL index is represented in memory by an
10055 ** instance of the following structure.
10056 **
10057 ** The columns of the table that are to be indexed are described
10058 ** by the aiColumn[] field of this structure.  For example, suppose
10059 ** we have the following table and index:
10060 **
10061 **     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
10062 **     CREATE INDEX Ex2 ON Ex1(c3,c1);
10063 **
10064 ** In the Table structure describing Ex1, nCol==3 because there are
10065 ** three columns in the table.  In the Index structure describing
10066 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
10067 ** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the 
10068 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
10069 ** The second column to be indexed (c1) has an index of 0 in
10070 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
10071 **
10072 ** The Index.onError field determines whether or not the indexed columns
10073 ** must be unique and what to do if they are not.  When Index.onError=OE_None,
10074 ** it means this is not a unique index.  Otherwise it is a unique index
10075 ** and the value of Index.onError indicate the which conflict resolution 
10076 ** algorithm to employ whenever an attempt is made to insert a non-unique
10077 ** element.
10078 */
10079 struct Index {
10080   char *zName;     /* Name of this index */
10081   int nColumn;     /* Number of columns in the table used by this index */
10082   int *aiColumn;   /* Which columns are used by this index.  1st is 0 */
10083   unsigned *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
10084   Table *pTable;   /* The SQL table being indexed */
10085   int tnum;        /* Page containing root of this index in database file */
10086   u8 onError;      /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
10087   u8 autoIndex;    /* True if is automatically created (ex: by UNIQUE) */
10088   u8 bUnordered;   /* Use this index for == or IN queries only */
10089   char *zColAff;   /* String defining the affinity of each column */
10090   Index *pNext;    /* The next index associated with the same table */
10091   Schema *pSchema; /* Schema containing this index */
10092   u8 *aSortOrder;  /* Array of size Index.nColumn. True==DESC, False==ASC */
10093   char **azColl;   /* Array of collation sequence names for index */
10094   IndexSample *aSample;    /* Array of SQLITE_INDEX_SAMPLES samples */
10095 };
10096
10097 /*
10098 ** Each sample stored in the sqlite_stat2 table is represented in memory 
10099 ** using a structure of this type.
10100 */
10101 struct IndexSample {
10102   union {
10103     char *z;        /* Value if eType is SQLITE_TEXT or SQLITE_BLOB */
10104     double r;       /* Value if eType is SQLITE_FLOAT or SQLITE_INTEGER */
10105   } u;
10106   u8 eType;         /* SQLITE_NULL, SQLITE_INTEGER ... etc. */
10107   u8 nByte;         /* Size in byte of text or blob. */
10108 };
10109
10110 /*
10111 ** Each token coming out of the lexer is an instance of
10112 ** this structure.  Tokens are also used as part of an expression.
10113 **
10114 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
10115 ** may contain random values.  Do not make any assumptions about Token.dyn
10116 ** and Token.n when Token.z==0.
10117 */
10118 struct Token {
10119   const char *z;     /* Text of the token.  Not NULL-terminated! */
10120   unsigned int n;    /* Number of characters in this token */
10121 };
10122
10123 /*
10124 ** An instance of this structure contains information needed to generate
10125 ** code for a SELECT that contains aggregate functions.
10126 **
10127 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
10128 ** pointer to this structure.  The Expr.iColumn field is the index in
10129 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
10130 ** code for that node.
10131 **
10132 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
10133 ** original Select structure that describes the SELECT statement.  These
10134 ** fields do not need to be freed when deallocating the AggInfo structure.
10135 */
10136 struct AggInfo {
10137   u8 directMode;          /* Direct rendering mode means take data directly
10138                           ** from source tables rather than from accumulators */
10139   u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
10140                           ** than the source table */
10141   int sortingIdx;         /* Cursor number of the sorting index */
10142   ExprList *pGroupBy;     /* The group by clause */
10143   int nSortingColumn;     /* Number of columns in the sorting index */
10144   struct AggInfo_col {    /* For each column used in source tables */
10145     Table *pTab;             /* Source table */
10146     int iTable;              /* Cursor number of the source table */
10147     int iColumn;             /* Column number within the source table */
10148     int iSorterColumn;       /* Column number in the sorting index */
10149     int iMem;                /* Memory location that acts as accumulator */
10150     Expr *pExpr;             /* The original expression */
10151   } *aCol;
10152   int nColumn;            /* Number of used entries in aCol[] */
10153   int nColumnAlloc;       /* Number of slots allocated for aCol[] */
10154   int nAccumulator;       /* Number of columns that show through to the output.
10155                           ** Additional columns are used only as parameters to
10156                           ** aggregate functions */
10157   struct AggInfo_func {   /* For each aggregate function */
10158     Expr *pExpr;             /* Expression encoding the function */
10159     FuncDef *pFunc;          /* The aggregate function implementation */
10160     int iMem;                /* Memory location that acts as accumulator */
10161     int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
10162   } *aFunc;
10163   int nFunc;              /* Number of entries in aFunc[] */
10164   int nFuncAlloc;         /* Number of slots allocated for aFunc[] */
10165 };
10166
10167 /*
10168 ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
10169 ** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
10170 ** than 32767 we have to make it 32-bit.  16-bit is preferred because
10171 ** it uses less memory in the Expr object, which is a big memory user
10172 ** in systems with lots of prepared statements.  And few applications
10173 ** need more than about 10 or 20 variables.  But some extreme users want
10174 ** to have prepared statements with over 32767 variables, and for them
10175 ** the option is available (at compile-time).
10176 */
10177 #if SQLITE_MAX_VARIABLE_NUMBER<=32767
10178 typedef i16 ynVar;
10179 #else
10180 typedef int ynVar;
10181 #endif
10182
10183 /*
10184 ** Each node of an expression in the parse tree is an instance
10185 ** of this structure.
10186 **
10187 ** Expr.op is the opcode. The integer parser token codes are reused
10188 ** as opcodes here. For example, the parser defines TK_GE to be an integer
10189 ** code representing the ">=" operator. This same integer code is reused
10190 ** to represent the greater-than-or-equal-to operator in the expression
10191 ** tree.
10192 **
10193 ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB, 
10194 ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
10195 ** the expression is a variable (TK_VARIABLE), then Expr.token contains the 
10196 ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
10197 ** then Expr.token contains the name of the function.
10198 **
10199 ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
10200 ** binary operator. Either or both may be NULL.
10201 **
10202 ** Expr.x.pList is a list of arguments if the expression is an SQL function,
10203 ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
10204 ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
10205 ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
10206 ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is 
10207 ** valid.
10208 **
10209 ** An expression of the form ID or ID.ID refers to a column in a table.
10210 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
10211 ** the integer cursor number of a VDBE cursor pointing to that table and
10212 ** Expr.iColumn is the column number for the specific column.  If the
10213 ** expression is used as a result in an aggregate SELECT, then the
10214 ** value is also stored in the Expr.iAgg column in the aggregate so that
10215 ** it can be accessed after all aggregates are computed.
10216 **
10217 ** If the expression is an unbound variable marker (a question mark 
10218 ** character '?' in the original SQL) then the Expr.iTable holds the index 
10219 ** number for that variable.
10220 **
10221 ** If the expression is a subquery then Expr.iColumn holds an integer
10222 ** register number containing the result of the subquery.  If the
10223 ** subquery gives a constant result, then iTable is -1.  If the subquery
10224 ** gives a different answer at different times during statement processing
10225 ** then iTable is the address of a subroutine that computes the subquery.
10226 **
10227 ** If the Expr is of type OP_Column, and the table it is selecting from
10228 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
10229 ** corresponding table definition.
10230 **
10231 ** ALLOCATION NOTES:
10232 **
10233 ** Expr objects can use a lot of memory space in database schema.  To
10234 ** help reduce memory requirements, sometimes an Expr object will be
10235 ** truncated.  And to reduce the number of memory allocations, sometimes
10236 ** two or more Expr objects will be stored in a single memory allocation,
10237 ** together with Expr.zToken strings.
10238 **
10239 ** If the EP_Reduced and EP_TokenOnly flags are set when
10240 ** an Expr object is truncated.  When EP_Reduced is set, then all
10241 ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
10242 ** are contained within the same memory allocation.  Note, however, that
10243 ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
10244 ** allocated, regardless of whether or not EP_Reduced is set.
10245 */
10246 struct Expr {
10247   u8 op;                 /* Operation performed by this node */
10248   char affinity;         /* The affinity of the column or 0 if not a column */
10249   u16 flags;             /* Various flags.  EP_* See below */
10250   union {
10251     char *zToken;          /* Token value. Zero terminated and dequoted */
10252     int iValue;            /* Non-negative integer value if EP_IntValue */
10253   } u;
10254
10255   /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
10256   ** space is allocated for the fields below this point. An attempt to
10257   ** access them will result in a segfault or malfunction. 
10258   *********************************************************************/
10259
10260   Expr *pLeft;           /* Left subnode */
10261   Expr *pRight;          /* Right subnode */
10262   union {
10263     ExprList *pList;     /* Function arguments or in "<expr> IN (<expr-list)" */
10264     Select *pSelect;     /* Used for sub-selects and "<expr> IN (<select>)" */
10265   } x;
10266   CollSeq *pColl;        /* The collation type of the column or 0 */
10267
10268   /* If the EP_Reduced flag is set in the Expr.flags mask, then no
10269   ** space is allocated for the fields below this point. An attempt to
10270   ** access them will result in a segfault or malfunction.
10271   *********************************************************************/
10272
10273   int iTable;            /* TK_COLUMN: cursor number of table holding column
10274                          ** TK_REGISTER: register number
10275                          ** TK_TRIGGER: 1 -> new, 0 -> old */
10276   ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
10277                          ** TK_VARIABLE: variable number (always >= 1). */
10278   i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
10279   i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
10280   u8 flags2;             /* Second set of flags.  EP2_... */
10281   u8 op2;                /* If a TK_REGISTER, the original value of Expr.op */
10282   AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
10283   Table *pTab;           /* Table for TK_COLUMN expressions. */
10284 #if SQLITE_MAX_EXPR_DEPTH>0
10285   int nHeight;           /* Height of the tree headed by this node */
10286 #endif
10287 };
10288
10289 /*
10290 ** The following are the meanings of bits in the Expr.flags field.
10291 */
10292 #define EP_FromJoin   0x0001  /* Originated in ON or USING clause of a join */
10293 #define EP_Agg        0x0002  /* Contains one or more aggregate functions */
10294 #define EP_Resolved   0x0004  /* IDs have been resolved to COLUMNs */
10295 #define EP_Error      0x0008  /* Expression contains one or more errors */
10296 #define EP_Distinct   0x0010  /* Aggregate function with DISTINCT keyword */
10297 #define EP_VarSelect  0x0020  /* pSelect is correlated, not constant */
10298 #define EP_DblQuoted  0x0040  /* token.z was originally in "..." */
10299 #define EP_InfixFunc  0x0080  /* True for an infix function: LIKE, GLOB, etc */
10300 #define EP_ExpCollate 0x0100  /* Collating sequence specified explicitly */
10301 #define EP_FixedDest  0x0200  /* Result needed in a specific register */
10302 #define EP_IntValue   0x0400  /* Integer value contained in u.iValue */
10303 #define EP_xIsSelect  0x0800  /* x.pSelect is valid (otherwise x.pList is) */
10304
10305 #define EP_Reduced    0x1000  /* Expr struct is EXPR_REDUCEDSIZE bytes only */
10306 #define EP_TokenOnly  0x2000  /* Expr struct is EXPR_TOKENONLYSIZE bytes only */
10307 #define EP_Static     0x4000  /* Held in memory not obtained from malloc() */
10308
10309 /*
10310 ** The following are the meanings of bits in the Expr.flags2 field.
10311 */
10312 #define EP2_MallocedToken  0x0001  /* Need to sqlite3DbFree() Expr.zToken */
10313 #define EP2_Irreducible    0x0002  /* Cannot EXPRDUP_REDUCE this Expr */
10314
10315 /*
10316 ** The pseudo-routine sqlite3ExprSetIrreducible sets the EP2_Irreducible
10317 ** flag on an expression structure.  This flag is used for VV&A only.  The
10318 ** routine is implemented as a macro that only works when in debugging mode,
10319 ** so as not to burden production code.
10320 */
10321 #ifdef SQLITE_DEBUG
10322 # define ExprSetIrreducible(X)  (X)->flags2 |= EP2_Irreducible
10323 #else
10324 # define ExprSetIrreducible(X)
10325 #endif
10326
10327 /*
10328 ** These macros can be used to test, set, or clear bits in the 
10329 ** Expr.flags field.
10330 */
10331 #define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
10332 #define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
10333 #define ExprSetProperty(E,P)     (E)->flags|=(P)
10334 #define ExprClearProperty(E,P)   (E)->flags&=~(P)
10335
10336 /*
10337 ** Macros to determine the number of bytes required by a normal Expr 
10338 ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags 
10339 ** and an Expr struct with the EP_TokenOnly flag set.
10340 */
10341 #define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
10342 #define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
10343 #define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
10344
10345 /*
10346 ** Flags passed to the sqlite3ExprDup() function. See the header comment 
10347 ** above sqlite3ExprDup() for details.
10348 */
10349 #define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
10350
10351 /*
10352 ** A list of expressions.  Each expression may optionally have a
10353 ** name.  An expr/name combination can be used in several ways, such
10354 ** as the list of "expr AS ID" fields following a "SELECT" or in the
10355 ** list of "ID = expr" items in an UPDATE.  A list of expressions can
10356 ** also be used as the argument to a function, in which case the a.zName
10357 ** field is not used.
10358 */
10359 struct ExprList {
10360   int nExpr;             /* Number of expressions on the list */
10361   int nAlloc;            /* Number of entries allocated below */
10362   int iECursor;          /* VDBE Cursor associated with this ExprList */
10363   struct ExprList_item {
10364     Expr *pExpr;           /* The list of expressions */
10365     char *zName;           /* Token associated with this expression */
10366     char *zSpan;           /* Original text of the expression */
10367     u8 sortOrder;          /* 1 for DESC or 0 for ASC */
10368     u8 done;               /* A flag to indicate when processing is finished */
10369     u16 iCol;              /* For ORDER BY, column number in result set */
10370     u16 iAlias;            /* Index into Parse.aAlias[] for zName */
10371   } *a;                  /* One entry for each expression */
10372 };
10373
10374 /*
10375 ** An instance of this structure is used by the parser to record both
10376 ** the parse tree for an expression and the span of input text for an
10377 ** expression.
10378 */
10379 struct ExprSpan {
10380   Expr *pExpr;          /* The expression parse tree */
10381   const char *zStart;   /* First character of input text */
10382   const char *zEnd;     /* One character past the end of input text */
10383 };
10384
10385 /*
10386 ** An instance of this structure can hold a simple list of identifiers,
10387 ** such as the list "a,b,c" in the following statements:
10388 **
10389 **      INSERT INTO t(a,b,c) VALUES ...;
10390 **      CREATE INDEX idx ON t(a,b,c);
10391 **      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
10392 **
10393 ** The IdList.a.idx field is used when the IdList represents the list of
10394 ** column names after a table name in an INSERT statement.  In the statement
10395 **
10396 **     INSERT INTO t(a,b,c) ...
10397 **
10398 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
10399 */
10400 struct IdList {
10401   struct IdList_item {
10402     char *zName;      /* Name of the identifier */
10403     int idx;          /* Index in some Table.aCol[] of a column named zName */
10404   } *a;
10405   int nId;         /* Number of identifiers on the list */
10406   int nAlloc;      /* Number of entries allocated for a[] below */
10407 };
10408
10409 /*
10410 ** The bitmask datatype defined below is used for various optimizations.
10411 **
10412 ** Changing this from a 64-bit to a 32-bit type limits the number of
10413 ** tables in a join to 32 instead of 64.  But it also reduces the size
10414 ** of the library by 738 bytes on ix86.
10415 */
10416 typedef u64 Bitmask;
10417
10418 /*
10419 ** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
10420 */
10421 #define BMS  ((int)(sizeof(Bitmask)*8))
10422
10423 /*
10424 ** The following structure describes the FROM clause of a SELECT statement.
10425 ** Each table or subquery in the FROM clause is a separate element of
10426 ** the SrcList.a[] array.
10427 **
10428 ** With the addition of multiple database support, the following structure
10429 ** can also be used to describe a particular table such as the table that
10430 ** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
10431 ** such a table must be a simple name: ID.  But in SQLite, the table can
10432 ** now be identified by a database name, a dot, then the table name: ID.ID.
10433 **
10434 ** The jointype starts out showing the join type between the current table
10435 ** and the next table on the list.  The parser builds the list this way.
10436 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
10437 ** jointype expresses the join between the table and the previous table.
10438 **
10439 ** In the colUsed field, the high-order bit (bit 63) is set if the table
10440 ** contains more than 63 columns and the 64-th or later column is used.
10441 */
10442 struct SrcList {
10443   i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
10444   i16 nAlloc;      /* Number of entries allocated in a[] below */
10445   struct SrcList_item {
10446     char *zDatabase;  /* Name of database holding this table */
10447     char *zName;      /* Name of the table */
10448     char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
10449     Table *pTab;      /* An SQL table corresponding to zName */
10450     Select *pSelect;  /* A SELECT statement used in place of a table name */
10451     u8 isPopulated;   /* Temporary table associated with SELECT is populated */
10452     u8 jointype;      /* Type of join between this able and the previous */
10453     u8 notIndexed;    /* True if there is a NOT INDEXED clause */
10454 #ifndef SQLITE_OMIT_EXPLAIN
10455     u8 iSelectId;     /* If pSelect!=0, the id of the sub-select in EQP */
10456 #endif
10457     int iCursor;      /* The VDBE cursor number used to access this table */
10458     Expr *pOn;        /* The ON clause of a join */
10459     IdList *pUsing;   /* The USING clause of a join */
10460     Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
10461     char *zIndex;     /* Identifier from "INDEXED BY <zIndex>" clause */
10462     Index *pIndex;    /* Index structure corresponding to zIndex, if any */
10463   } a[1];             /* One entry for each identifier on the list */
10464 };
10465
10466 /*
10467 ** Permitted values of the SrcList.a.jointype field
10468 */
10469 #define JT_INNER     0x0001    /* Any kind of inner or cross join */
10470 #define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
10471 #define JT_NATURAL   0x0004    /* True for a "natural" join */
10472 #define JT_LEFT      0x0008    /* Left outer join */
10473 #define JT_RIGHT     0x0010    /* Right outer join */
10474 #define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
10475 #define JT_ERROR     0x0040    /* unknown or unsupported join type */
10476
10477
10478 /*
10479 ** A WherePlan object holds information that describes a lookup
10480 ** strategy.
10481 **
10482 ** This object is intended to be opaque outside of the where.c module.
10483 ** It is included here only so that that compiler will know how big it
10484 ** is.  None of the fields in this object should be used outside of
10485 ** the where.c module.
10486 **
10487 ** Within the union, pIdx is only used when wsFlags&WHERE_INDEXED is true.
10488 ** pTerm is only used when wsFlags&WHERE_MULTI_OR is true.  And pVtabIdx
10489 ** is only used when wsFlags&WHERE_VIRTUALTABLE is true.  It is never the
10490 ** case that more than one of these conditions is true.
10491 */
10492 struct WherePlan {
10493   u32 wsFlags;                   /* WHERE_* flags that describe the strategy */
10494   u32 nEq;                       /* Number of == constraints */
10495   double nRow;                   /* Estimated number of rows (for EQP) */
10496   union {
10497     Index *pIdx;                   /* Index when WHERE_INDEXED is true */
10498     struct WhereTerm *pTerm;       /* WHERE clause term for OR-search */
10499     sqlite3_index_info *pVtabIdx;  /* Virtual table index to use */
10500   } u;
10501 };
10502
10503 /*
10504 ** For each nested loop in a WHERE clause implementation, the WhereInfo
10505 ** structure contains a single instance of this structure.  This structure
10506 ** is intended to be private the the where.c module and should not be
10507 ** access or modified by other modules.
10508 **
10509 ** The pIdxInfo field is used to help pick the best index on a
10510 ** virtual table.  The pIdxInfo pointer contains indexing
10511 ** information for the i-th table in the FROM clause before reordering.
10512 ** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
10513 ** All other information in the i-th WhereLevel object for the i-th table
10514 ** after FROM clause ordering.
10515 */
10516 struct WhereLevel {
10517   WherePlan plan;       /* query plan for this element of the FROM clause */
10518   int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
10519   int iTabCur;          /* The VDBE cursor used to access the table */
10520   int iIdxCur;          /* The VDBE cursor used to access pIdx */
10521   int addrBrk;          /* Jump here to break out of the loop */
10522   int addrNxt;          /* Jump here to start the next IN combination */
10523   int addrCont;         /* Jump here to continue with the next loop cycle */
10524   int addrFirst;        /* First instruction of interior of the loop */
10525   u8 iFrom;             /* Which entry in the FROM clause */
10526   u8 op, p5;            /* Opcode and P5 of the opcode that ends the loop */
10527   int p1, p2;           /* Operands of the opcode used to ends the loop */
10528   union {               /* Information that depends on plan.wsFlags */
10529     struct {
10530       int nIn;              /* Number of entries in aInLoop[] */
10531       struct InLoop {
10532         int iCur;              /* The VDBE cursor used by this IN operator */
10533         int addrInTop;         /* Top of the IN loop */
10534       } *aInLoop;           /* Information about each nested IN operator */
10535     } in;                 /* Used when plan.wsFlags&WHERE_IN_ABLE */
10536   } u;
10537
10538   /* The following field is really not part of the current level.  But
10539   ** we need a place to cache virtual table index information for each
10540   ** virtual table in the FROM clause and the WhereLevel structure is
10541   ** a convenient place since there is one WhereLevel for each FROM clause
10542   ** element.
10543   */
10544   sqlite3_index_info *pIdxInfo;  /* Index info for n-th source table */
10545 };
10546
10547 /*
10548 ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
10549 ** and the WhereInfo.wctrlFlags member.
10550 */
10551 #define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
10552 #define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
10553 #define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
10554 #define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
10555 #define WHERE_DUPLICATES_OK    0x0008 /* Ok to return a row more than once */
10556 #define WHERE_OMIT_OPEN        0x0010 /* Table cursors are already open */
10557 #define WHERE_OMIT_CLOSE       0x0020 /* Omit close of table & index cursors */
10558 #define WHERE_FORCE_TABLE      0x0040 /* Do not use an index-only search */
10559 #define WHERE_ONETABLE_ONLY    0x0080 /* Only code the 1st table in pTabList */
10560
10561 /*
10562 ** The WHERE clause processing routine has two halves.  The
10563 ** first part does the start of the WHERE loop and the second
10564 ** half does the tail of the WHERE loop.  An instance of
10565 ** this structure is returned by the first half and passed
10566 ** into the second half to give some continuity.
10567 */
10568 struct WhereInfo {
10569   Parse *pParse;       /* Parsing and code generating context */
10570   u16 wctrlFlags;      /* Flags originally passed to sqlite3WhereBegin() */
10571   u8 okOnePass;        /* Ok to use one-pass algorithm for UPDATE or DELETE */
10572   u8 untestedTerms;    /* Not all WHERE terms resolved by outer loop */
10573   SrcList *pTabList;             /* List of tables in the join */
10574   int iTop;                      /* The very beginning of the WHERE loop */
10575   int iContinue;                 /* Jump here to continue with next record */
10576   int iBreak;                    /* Jump here to break out of the loop */
10577   int nLevel;                    /* Number of nested loop */
10578   struct WhereClause *pWC;       /* Decomposition of the WHERE clause */
10579   double savedNQueryLoop;        /* pParse->nQueryLoop outside the WHERE loop */
10580   double nRowOut;                /* Estimated number of output rows */
10581   WhereLevel a[1];               /* Information about each nest loop in WHERE */
10582 };
10583
10584 /*
10585 ** A NameContext defines a context in which to resolve table and column
10586 ** names.  The context consists of a list of tables (the pSrcList) field and
10587 ** a list of named expression (pEList).  The named expression list may
10588 ** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
10589 ** to the table being operated on by INSERT, UPDATE, or DELETE.  The
10590 ** pEList corresponds to the result set of a SELECT and is NULL for
10591 ** other statements.
10592 **
10593 ** NameContexts can be nested.  When resolving names, the inner-most 
10594 ** context is searched first.  If no match is found, the next outer
10595 ** context is checked.  If there is still no match, the next context
10596 ** is checked.  This process continues until either a match is found
10597 ** or all contexts are check.  When a match is found, the nRef member of
10598 ** the context containing the match is incremented. 
10599 **
10600 ** Each subquery gets a new NameContext.  The pNext field points to the
10601 ** NameContext in the parent query.  Thus the process of scanning the
10602 ** NameContext list corresponds to searching through successively outer
10603 ** subqueries looking for a match.
10604 */
10605 struct NameContext {
10606   Parse *pParse;       /* The parser */
10607   SrcList *pSrcList;   /* One or more tables used to resolve names */
10608   ExprList *pEList;    /* Optional list of named expressions */
10609   int nRef;            /* Number of names resolved by this context */
10610   int nErr;            /* Number of errors encountered while resolving names */
10611   u8 allowAgg;         /* Aggregate functions allowed here */
10612   u8 hasAgg;           /* True if aggregates are seen */
10613   u8 isCheck;          /* True if resolving names in a CHECK constraint */
10614   int nDepth;          /* Depth of subquery recursion. 1 for no recursion */
10615   AggInfo *pAggInfo;   /* Information about aggregates at this level */
10616   NameContext *pNext;  /* Next outer name context.  NULL for outermost */
10617 };
10618
10619 /*
10620 ** An instance of the following structure contains all information
10621 ** needed to generate code for a single SELECT statement.
10622 **
10623 ** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
10624 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
10625 ** limit and nOffset to the value of the offset (or 0 if there is not
10626 ** offset).  But later on, nLimit and nOffset become the memory locations
10627 ** in the VDBE that record the limit and offset counters.
10628 **
10629 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
10630 ** These addresses must be stored so that we can go back and fill in
10631 ** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
10632 ** the number of columns in P2 can be computed at the same time
10633 ** as the OP_OpenEphm instruction is coded because not
10634 ** enough information about the compound query is known at that point.
10635 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
10636 ** for the result set.  The KeyInfo for addrOpenTran[2] contains collating
10637 ** sequences for the ORDER BY clause.
10638 */
10639 struct Select {
10640   ExprList *pEList;      /* The fields of the result */
10641   u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
10642   char affinity;         /* MakeRecord with this affinity for SRT_Set */
10643   u16 selFlags;          /* Various SF_* values */
10644   SrcList *pSrc;         /* The FROM clause */
10645   Expr *pWhere;          /* The WHERE clause */
10646   ExprList *pGroupBy;    /* The GROUP BY clause */
10647   Expr *pHaving;         /* The HAVING clause */
10648   ExprList *pOrderBy;    /* The ORDER BY clause */
10649   Select *pPrior;        /* Prior select in a compound select statement */
10650   Select *pNext;         /* Next select to the left in a compound */
10651   Select *pRightmost;    /* Right-most select in a compound select statement */
10652   Expr *pLimit;          /* LIMIT expression. NULL means not used. */
10653   Expr *pOffset;         /* OFFSET expression. NULL means not used. */
10654   int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
10655   int addrOpenEphm[3];   /* OP_OpenEphem opcodes related to this select */
10656   double nSelectRow;     /* Estimated number of result rows */
10657 };
10658
10659 /*
10660 ** Allowed values for Select.selFlags.  The "SF" prefix stands for
10661 ** "Select Flag".
10662 */
10663 #define SF_Distinct        0x0001  /* Output should be DISTINCT */
10664 #define SF_Resolved        0x0002  /* Identifiers have been resolved */
10665 #define SF_Aggregate       0x0004  /* Contains aggregate functions */
10666 #define SF_UsesEphemeral   0x0008  /* Uses the OpenEphemeral opcode */
10667 #define SF_Expanded        0x0010  /* sqlite3SelectExpand() called on this */
10668 #define SF_HasTypeInfo     0x0020  /* FROM subqueries have Table metadata */
10669
10670
10671 /*
10672 ** The results of a select can be distributed in several ways.  The
10673 ** "SRT" prefix means "SELECT Result Type".
10674 */
10675 #define SRT_Union        1  /* Store result as keys in an index */
10676 #define SRT_Except       2  /* Remove result from a UNION index */
10677 #define SRT_Exists       3  /* Store 1 if the result is not empty */
10678 #define SRT_Discard      4  /* Do not save the results anywhere */
10679
10680 /* The ORDER BY clause is ignored for all of the above */
10681 #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
10682
10683 #define SRT_Output       5  /* Output each row of result */
10684 #define SRT_Mem          6  /* Store result in a memory cell */
10685 #define SRT_Set          7  /* Store results as keys in an index */
10686 #define SRT_Table        8  /* Store result as data with an automatic rowid */
10687 #define SRT_EphemTab     9  /* Create transient tab and store like SRT_Table */
10688 #define SRT_Coroutine   10  /* Generate a single row of result */
10689
10690 /*
10691 ** A structure used to customize the behavior of sqlite3Select(). See
10692 ** comments above sqlite3Select() for details.
10693 */
10694 typedef struct SelectDest SelectDest;
10695 struct SelectDest {
10696   u8 eDest;         /* How to dispose of the results */
10697   u8 affinity;      /* Affinity used when eDest==SRT_Set */
10698   int iParm;        /* A parameter used by the eDest disposal method */
10699   int iMem;         /* Base register where results are written */
10700   int nMem;         /* Number of registers allocated */
10701 };
10702
10703 /*
10704 ** During code generation of statements that do inserts into AUTOINCREMENT 
10705 ** tables, the following information is attached to the Table.u.autoInc.p
10706 ** pointer of each autoincrement table to record some side information that
10707 ** the code generator needs.  We have to keep per-table autoincrement
10708 ** information in case inserts are down within triggers.  Triggers do not
10709 ** normally coordinate their activities, but we do need to coordinate the
10710 ** loading and saving of autoincrement information.
10711 */
10712 struct AutoincInfo {
10713   AutoincInfo *pNext;   /* Next info block in a list of them all */
10714   Table *pTab;          /* Table this info block refers to */
10715   int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
10716   int regCtr;           /* Memory register holding the rowid counter */
10717 };
10718
10719 /*
10720 ** Size of the column cache
10721 */
10722 #ifndef SQLITE_N_COLCACHE
10723 # define SQLITE_N_COLCACHE 10
10724 #endif
10725
10726 /*
10727 ** At least one instance of the following structure is created for each 
10728 ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
10729 ** statement. All such objects are stored in the linked list headed at
10730 ** Parse.pTriggerPrg and deleted once statement compilation has been
10731 ** completed.
10732 **
10733 ** A Vdbe sub-program that implements the body and WHEN clause of trigger
10734 ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
10735 ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
10736 ** The Parse.pTriggerPrg list never contains two entries with the same
10737 ** values for both pTrigger and orconf.
10738 **
10739 ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
10740 ** accessed (or set to 0 for triggers fired as a result of INSERT 
10741 ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
10742 ** a mask of new.* columns used by the program.
10743 */
10744 struct TriggerPrg {
10745   Trigger *pTrigger;      /* Trigger this program was coded from */
10746   int orconf;             /* Default ON CONFLICT policy */
10747   SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
10748   u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
10749   TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
10750 };
10751
10752 /*
10753 ** The yDbMask datatype for the bitmask of all attached databases.
10754 */
10755 #if SQLITE_MAX_ATTACHED>30
10756   typedef sqlite3_uint64 yDbMask;
10757 #else
10758   typedef unsigned int yDbMask;
10759 #endif
10760
10761 /*
10762 ** An SQL parser context.  A copy of this structure is passed through
10763 ** the parser and down into all the parser action routine in order to
10764 ** carry around information that is global to the entire parse.
10765 **
10766 ** The structure is divided into two parts.  When the parser and code
10767 ** generate call themselves recursively, the first part of the structure
10768 ** is constant but the second part is reset at the beginning and end of
10769 ** each recursion.
10770 **
10771 ** The nTableLock and aTableLock variables are only used if the shared-cache 
10772 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
10773 ** used to store the set of table-locks required by the statement being
10774 ** compiled. Function sqlite3TableLock() is used to add entries to the
10775 ** list.
10776 */
10777 struct Parse {
10778   sqlite3 *db;         /* The main database structure */
10779   int rc;              /* Return code from execution */
10780   char *zErrMsg;       /* An error message */
10781   Vdbe *pVdbe;         /* An engine for executing database bytecode */
10782   u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
10783   u8 nameClash;        /* A permanent table name clashes with temp table name */
10784   u8 checkSchema;      /* Causes schema cookie check after an error */
10785   u8 nested;           /* Number of nested calls to the parser/code generator */
10786   u8 parseError;       /* True after a parsing error.  Ticket #1794 */
10787   u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
10788   u8 nTempInUse;       /* Number of aTempReg[] currently checked out */
10789   int aTempReg[8];     /* Holding area for temporary registers */
10790   int nRangeReg;       /* Size of the temporary register block */
10791   int iRangeReg;       /* First register in temporary register block */
10792   int nErr;            /* Number of errors seen */
10793   int nTab;            /* Number of previously allocated VDBE cursors */
10794   int nMem;            /* Number of memory cells used so far */
10795   int nSet;            /* Number of sets used so far */
10796   int ckBase;          /* Base register of data during check constraints */
10797   int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
10798   int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
10799   u8 nColCache;        /* Number of entries in the column cache */
10800   u8 iColCache;        /* Next entry of the cache to replace */
10801   struct yColCache {
10802     int iTable;           /* Table cursor number */
10803     int iColumn;          /* Table column number */
10804     u8 tempReg;           /* iReg is a temp register that needs to be freed */
10805     int iLevel;           /* Nesting level */
10806     int iReg;             /* Reg with value of this column. 0 means none. */
10807     int lru;              /* Least recently used entry has the smallest value */
10808   } aColCache[SQLITE_N_COLCACHE];  /* One for each column cache entry */
10809   yDbMask writeMask;   /* Start a write transaction on these databases */
10810   yDbMask cookieMask;  /* Bitmask of schema verified databases */
10811   u8 isMultiWrite;     /* True if statement may affect/insert multiple rows */
10812   u8 mayAbort;         /* True if statement may throw an ABORT exception */
10813   int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
10814   int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
10815 #ifndef SQLITE_OMIT_SHARED_CACHE
10816   int nTableLock;        /* Number of locks in aTableLock */
10817   TableLock *aTableLock; /* Required table locks for shared-cache mode */
10818 #endif
10819   int regRowid;        /* Register holding rowid of CREATE TABLE entry */
10820   int regRoot;         /* Register holding root page number for new objects */
10821   AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
10822   int nMaxArg;         /* Max args passed to user function by sub-program */
10823
10824   /* Information used while coding trigger programs. */
10825   Parse *pToplevel;    /* Parse structure for main program (or NULL) */
10826   Table *pTriggerTab;  /* Table triggers are being coded for */
10827   u32 oldmask;         /* Mask of old.* columns referenced */
10828   u32 newmask;         /* Mask of new.* columns referenced */
10829   u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
10830   u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
10831   u8 disableTriggers;  /* True to disable triggers */
10832   double nQueryLoop;   /* Estimated number of iterations of a query */
10833
10834   /* Above is constant between recursions.  Below is reset before and after
10835   ** each recursion */
10836
10837   int nVar;            /* Number of '?' variables seen in the SQL so far */
10838   int nzVar;           /* Number of available slots in azVar[] */
10839   char **azVar;        /* Pointers to names of parameters */
10840   Vdbe *pReprepare;    /* VM being reprepared (sqlite3Reprepare()) */
10841   int nAlias;          /* Number of aliased result set columns */
10842   int nAliasAlloc;     /* Number of allocated slots for aAlias[] */
10843   int *aAlias;         /* Register used to hold aliased result */
10844   u8 explain;          /* True if the EXPLAIN flag is found on the query */
10845   Token sNameToken;    /* Token with unqualified schema object name */
10846   Token sLastToken;    /* The last token parsed */
10847   const char *zTail;   /* All SQL text past the last semicolon parsed */
10848   Table *pNewTable;    /* A table being constructed by CREATE TABLE */
10849   Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
10850   const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
10851 #ifndef SQLITE_OMIT_VIRTUALTABLE
10852   Token sArg;                /* Complete text of a module argument */
10853   u8 declareVtab;            /* True if inside sqlite3_declare_vtab() */
10854   int nVtabLock;             /* Number of virtual tables to lock */
10855   Table **apVtabLock;        /* Pointer to virtual tables needing locking */
10856 #endif
10857   int nHeight;            /* Expression tree height of current sub-select */
10858   Table *pZombieTab;      /* List of Table objects to delete after code gen */
10859   TriggerPrg *pTriggerPrg;    /* Linked list of coded triggers */
10860
10861 #ifndef SQLITE_OMIT_EXPLAIN
10862   int iSelectId;
10863   int iNextSelectId;
10864 #endif
10865 };
10866
10867 #ifdef SQLITE_OMIT_VIRTUALTABLE
10868   #define IN_DECLARE_VTAB 0
10869 #else
10870   #define IN_DECLARE_VTAB (pParse->declareVtab)
10871 #endif
10872
10873 /*
10874 ** An instance of the following structure can be declared on a stack and used
10875 ** to save the Parse.zAuthContext value so that it can be restored later.
10876 */
10877 struct AuthContext {
10878   const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
10879   Parse *pParse;              /* The Parse structure */
10880 };
10881
10882 /*
10883 ** Bitfield flags for P5 value in OP_Insert and OP_Delete
10884 */
10885 #define OPFLAG_NCHANGE       0x01    /* Set to update db->nChange */
10886 #define OPFLAG_LASTROWID     0x02    /* Set to update db->lastRowid */
10887 #define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
10888 #define OPFLAG_APPEND        0x08    /* This is likely to be an append */
10889 #define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
10890 #define OPFLAG_CLEARCACHE    0x20    /* Clear pseudo-table cache in OP_Column */
10891
10892 /*
10893  * Each trigger present in the database schema is stored as an instance of
10894  * struct Trigger. 
10895  *
10896  * Pointers to instances of struct Trigger are stored in two ways.
10897  * 1. In the "trigHash" hash table (part of the sqlite3* that represents the 
10898  *    database). This allows Trigger structures to be retrieved by name.
10899  * 2. All triggers associated with a single table form a linked list, using the
10900  *    pNext member of struct Trigger. A pointer to the first element of the
10901  *    linked list is stored as the "pTrigger" member of the associated
10902  *    struct Table.
10903  *
10904  * The "step_list" member points to the first element of a linked list
10905  * containing the SQL statements specified as the trigger program.
10906  */
10907 struct Trigger {
10908   char *zName;            /* The name of the trigger                        */
10909   char *table;            /* The table or view to which the trigger applies */
10910   u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
10911   u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
10912   Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
10913   IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
10914                              the <column-list> is stored here */
10915   Schema *pSchema;        /* Schema containing the trigger */
10916   Schema *pTabSchema;     /* Schema containing the table */
10917   TriggerStep *step_list; /* Link list of trigger program steps             */
10918   Trigger *pNext;         /* Next trigger associated with the table */
10919 };
10920
10921 /*
10922 ** A trigger is either a BEFORE or an AFTER trigger.  The following constants
10923 ** determine which. 
10924 **
10925 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
10926 ** In that cases, the constants below can be ORed together.
10927 */
10928 #define TRIGGER_BEFORE  1
10929 #define TRIGGER_AFTER   2
10930
10931 /*
10932  * An instance of struct TriggerStep is used to store a single SQL statement
10933  * that is a part of a trigger-program. 
10934  *
10935  * Instances of struct TriggerStep are stored in a singly linked list (linked
10936  * using the "pNext" member) referenced by the "step_list" member of the 
10937  * associated struct Trigger instance. The first element of the linked list is
10938  * the first step of the trigger-program.
10939  * 
10940  * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
10941  * "SELECT" statement. The meanings of the other members is determined by the 
10942  * value of "op" as follows:
10943  *
10944  * (op == TK_INSERT)
10945  * orconf    -> stores the ON CONFLICT algorithm
10946  * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
10947  *              this stores a pointer to the SELECT statement. Otherwise NULL.
10948  * target    -> A token holding the quoted name of the table to insert into.
10949  * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
10950  *              this stores values to be inserted. Otherwise NULL.
10951  * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ... 
10952  *              statement, then this stores the column-names to be
10953  *              inserted into.
10954  *
10955  * (op == TK_DELETE)
10956  * target    -> A token holding the quoted name of the table to delete from.
10957  * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
10958  *              Otherwise NULL.
10959  * 
10960  * (op == TK_UPDATE)
10961  * target    -> A token holding the quoted name of the table to update rows of.
10962  * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
10963  *              Otherwise NULL.
10964  * pExprList -> A list of the columns to update and the expressions to update
10965  *              them to. See sqlite3Update() documentation of "pChanges"
10966  *              argument.
10967  * 
10968  */
10969 struct TriggerStep {
10970   u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
10971   u8 orconf;           /* OE_Rollback etc. */
10972   Trigger *pTrig;      /* The trigger that this step is a part of */
10973   Select *pSelect;     /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
10974   Token target;        /* Target table for DELETE, UPDATE, INSERT */
10975   Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
10976   ExprList *pExprList; /* SET clause for UPDATE.  VALUES clause for INSERT */
10977   IdList *pIdList;     /* Column names for INSERT */
10978   TriggerStep *pNext;  /* Next in the link-list */
10979   TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
10980 };
10981
10982 /*
10983 ** The following structure contains information used by the sqliteFix...
10984 ** routines as they walk the parse tree to make database references
10985 ** explicit.  
10986 */
10987 typedef struct DbFixer DbFixer;
10988 struct DbFixer {
10989   Parse *pParse;      /* The parsing context.  Error messages written here */
10990   const char *zDb;    /* Make sure all objects are contained in this database */
10991   const char *zType;  /* Type of the container - used for error messages */
10992   const Token *pName; /* Name of the container - used for error messages */
10993 };
10994
10995 /*
10996 ** An objected used to accumulate the text of a string where we
10997 ** do not necessarily know how big the string will be in the end.
10998 */
10999 struct StrAccum {
11000   sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
11001   char *zBase;         /* A base allocation.  Not from malloc. */
11002   char *zText;         /* The string collected so far */
11003   int  nChar;          /* Length of the string so far */
11004   int  nAlloc;         /* Amount of space allocated in zText */
11005   int  mxAlloc;        /* Maximum allowed string length */
11006   u8   mallocFailed;   /* Becomes true if any memory allocation fails */
11007   u8   useMalloc;      /* 0: none,  1: sqlite3DbMalloc,  2: sqlite3_malloc */
11008   u8   tooBig;         /* Becomes true if string size exceeds limits */
11009 };
11010
11011 /*
11012 ** A pointer to this structure is used to communicate information
11013 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
11014 */
11015 typedef struct {
11016   sqlite3 *db;        /* The database being initialized */
11017   int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
11018   char **pzErrMsg;    /* Error message stored here */
11019   int rc;             /* Result code stored here */
11020 } InitData;
11021
11022 /*
11023 ** Structure containing global configuration data for the SQLite library.
11024 **
11025 ** This structure also contains some state information.
11026 */
11027 struct Sqlite3Config {
11028   int bMemstat;                     /* True to enable memory status */
11029   int bCoreMutex;                   /* True to enable core mutexing */
11030   int bFullMutex;                   /* True to enable full mutexing */
11031   int bOpenUri;                     /* True to interpret filenames as URIs */
11032   int mxStrlen;                     /* Maximum string length */
11033   int szLookaside;                  /* Default lookaside buffer size */
11034   int nLookaside;                   /* Default lookaside buffer count */
11035   sqlite3_mem_methods m;            /* Low-level memory allocation interface */
11036   sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
11037   sqlite3_pcache_methods pcache;    /* Low-level page-cache interface */
11038   void *pHeap;                      /* Heap storage space */
11039   int nHeap;                        /* Size of pHeap[] */
11040   int mnReq, mxReq;                 /* Min and max heap requests sizes */
11041   void *pScratch;                   /* Scratch memory */
11042   int szScratch;                    /* Size of each scratch buffer */
11043   int nScratch;                     /* Number of scratch buffers */
11044   void *pPage;                      /* Page cache memory */
11045   int szPage;                       /* Size of each page in pPage[] */
11046   int nPage;                        /* Number of pages in pPage[] */
11047   int mxParserStack;                /* maximum depth of the parser stack */
11048   int sharedCacheEnabled;           /* true if shared-cache mode enabled */
11049   /* The above might be initialized to non-zero.  The following need to always
11050   ** initially be zero, however. */
11051   int isInit;                       /* True after initialization has finished */
11052   int inProgress;                   /* True while initialization in progress */
11053   int isMutexInit;                  /* True after mutexes are initialized */
11054   int isMallocInit;                 /* True after malloc is initialized */
11055   int isPCacheInit;                 /* True after malloc is initialized */
11056   sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
11057   int nRefInitMutex;                /* Number of users of pInitMutex */
11058   void (*xLog)(void*,int,const char*); /* Function for logging */
11059   void *pLogArg;                       /* First argument to xLog() */
11060   int bLocaltimeFault;              /* True to fail localtime() calls */
11061 };
11062
11063 /*
11064 ** Context pointer passed down through the tree-walk.
11065 */
11066 struct Walker {
11067   int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
11068   int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
11069   Parse *pParse;                            /* Parser context.  */
11070   union {                                   /* Extra data for callback */
11071     NameContext *pNC;                          /* Naming context */
11072     int i;                                     /* Integer value */
11073   } u;
11074 };
11075
11076 /* Forward declarations */
11077 SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
11078 SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
11079 SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
11080 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
11081 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
11082
11083 /*
11084 ** Return code from the parse-tree walking primitives and their
11085 ** callbacks.
11086 */
11087 #define WRC_Continue    0   /* Continue down into children */
11088 #define WRC_Prune       1   /* Omit children but continue walking siblings */
11089 #define WRC_Abort       2   /* Abandon the tree walk */
11090
11091 /*
11092 ** Assuming zIn points to the first byte of a UTF-8 character,
11093 ** advance zIn to point to the first byte of the next UTF-8 character.
11094 */
11095 #define SQLITE_SKIP_UTF8(zIn) {                        \
11096   if( (*(zIn++))>=0xc0 ){                              \
11097     while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
11098   }                                                    \
11099 }
11100
11101 /*
11102 ** The SQLITE_*_BKPT macros are substitutes for the error codes with
11103 ** the same name but without the _BKPT suffix.  These macros invoke
11104 ** routines that report the line-number on which the error originated
11105 ** using sqlite3_log().  The routines also provide a convenient place
11106 ** to set a debugger breakpoint.
11107 */
11108 SQLITE_PRIVATE int sqlite3CorruptError(int);
11109 SQLITE_PRIVATE int sqlite3MisuseError(int);
11110 SQLITE_PRIVATE int sqlite3CantopenError(int);
11111 #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
11112 #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
11113 #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
11114
11115
11116 /*
11117 ** FTS4 is really an extension for FTS3.  It is enabled using the
11118 ** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
11119 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
11120 */
11121 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
11122 # define SQLITE_ENABLE_FTS3
11123 #endif
11124
11125 /*
11126 ** The ctype.h header is needed for non-ASCII systems.  It is also
11127 ** needed by FTS3 when FTS3 is included in the amalgamation.
11128 */
11129 #if !defined(SQLITE_ASCII) || \
11130     (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
11131 # include <ctype.h>
11132 #endif
11133
11134 /*
11135 ** The following macros mimic the standard library functions toupper(),
11136 ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
11137 ** sqlite versions only work for ASCII characters, regardless of locale.
11138 */
11139 #ifdef SQLITE_ASCII
11140 # define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
11141 # define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
11142 # define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
11143 # define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
11144 # define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
11145 # define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
11146 # define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
11147 #else
11148 # define sqlite3Toupper(x)   toupper((unsigned char)(x))
11149 # define sqlite3Isspace(x)   isspace((unsigned char)(x))
11150 # define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
11151 # define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
11152 # define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
11153 # define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
11154 # define sqlite3Tolower(x)   tolower((unsigned char)(x))
11155 #endif
11156
11157 /*
11158 ** Internal function prototypes
11159 */
11160 SQLITE_PRIVATE int sqlite3StrICmp(const char *, const char *);
11161 SQLITE_PRIVATE int sqlite3Strlen30(const char*);
11162 #define sqlite3StrNICmp sqlite3_strnicmp
11163
11164 SQLITE_PRIVATE int sqlite3MallocInit(void);
11165 SQLITE_PRIVATE void sqlite3MallocEnd(void);
11166 SQLITE_PRIVATE void *sqlite3Malloc(int);
11167 SQLITE_PRIVATE void *sqlite3MallocZero(int);
11168 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
11169 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
11170 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
11171 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
11172 SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
11173 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
11174 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
11175 SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
11176 SQLITE_PRIVATE int sqlite3MallocSize(void*);
11177 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
11178 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
11179 SQLITE_PRIVATE void sqlite3ScratchFree(void*);
11180 SQLITE_PRIVATE void *sqlite3PageMalloc(int);
11181 SQLITE_PRIVATE void sqlite3PageFree(void*);
11182 SQLITE_PRIVATE void sqlite3MemSetDefault(void);
11183 SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
11184 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
11185
11186 /*
11187 ** On systems with ample stack space and that support alloca(), make
11188 ** use of alloca() to obtain space for large automatic objects.  By default,
11189 ** obtain space from malloc().
11190 **
11191 ** The alloca() routine never returns NULL.  This will cause code paths
11192 ** that deal with sqlite3StackAlloc() failures to be unreachable.
11193 */
11194 #ifdef SQLITE_USE_ALLOCA
11195 # define sqlite3StackAllocRaw(D,N)   alloca(N)
11196 # define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)
11197 # define sqlite3StackFree(D,P)       
11198 #else
11199 # define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
11200 # define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)
11201 # define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
11202 #endif
11203
11204 #ifdef SQLITE_ENABLE_MEMSYS3
11205 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
11206 #endif
11207 #ifdef SQLITE_ENABLE_MEMSYS5
11208 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
11209 #endif
11210
11211
11212 #ifndef SQLITE_MUTEX_OMIT
11213 SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
11214 SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3NoopMutex(void);
11215 SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
11216 SQLITE_PRIVATE   int sqlite3MutexInit(void);
11217 SQLITE_PRIVATE   int sqlite3MutexEnd(void);
11218 #endif
11219
11220 SQLITE_PRIVATE int sqlite3StatusValue(int);
11221 SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
11222 SQLITE_PRIVATE void sqlite3StatusSet(int, int);
11223
11224 #ifndef SQLITE_OMIT_FLOATING_POINT
11225 SQLITE_PRIVATE   int sqlite3IsNaN(double);
11226 #else
11227 # define sqlite3IsNaN(X)  0
11228 #endif
11229
11230 SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
11231 #ifndef SQLITE_OMIT_TRACE
11232 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
11233 #endif
11234 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
11235 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
11236 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
11237 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
11238 SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
11239 #endif
11240 #if defined(SQLITE_TEST)
11241 SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
11242 #endif
11243 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
11244 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
11245 SQLITE_PRIVATE int sqlite3Dequote(char*);
11246 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
11247 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
11248 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
11249 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
11250 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
11251 SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
11252 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
11253 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
11254 SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
11255 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
11256 SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
11257 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
11258 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
11259 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
11260 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
11261 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
11262 SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
11263 SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
11264 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
11265 SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
11266 SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
11267 SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
11268 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3*, int);
11269 SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
11270 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
11271 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
11272 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
11273 SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
11274 SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
11275 SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
11276 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
11277 SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
11278 SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
11279 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
11280 SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
11281 SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
11282 SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
11283                     sqlite3_vfs**,char**,char **);
11284
11285 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
11286 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
11287 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
11288 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
11289 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
11290 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
11291 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
11292
11293 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
11294 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
11295 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
11296 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
11297 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
11298
11299 SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
11300
11301 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
11302 SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
11303 #else
11304 # define sqlite3ViewGetColumnNames(A,B) 0
11305 #endif
11306
11307 SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
11308 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
11309 #ifndef SQLITE_OMIT_AUTOINCREMENT
11310 SQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);
11311 SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);
11312 #else
11313 # define sqlite3AutoincrementBegin(X)
11314 # define sqlite3AutoincrementEnd(X)
11315 #endif
11316 SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
11317 SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int,int*,int*,int*);
11318 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
11319 SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
11320 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
11321 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
11322 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
11323                                       Token*, Select*, Expr*, IdList*);
11324 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
11325 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
11326 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
11327 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
11328 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
11329 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
11330 SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
11331                         Token*, int, int);
11332 SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
11333 SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
11334 SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
11335                          Expr*,ExprList*,int,Expr*,Expr*);
11336 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
11337 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
11338 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
11339 SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
11340 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
11341 SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse *, SrcList *, Expr *, ExprList *, Expr *, Expr *, char *);
11342 #endif
11343 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
11344 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
11345 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**, u16);
11346 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
11347 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int);
11348 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
11349 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
11350 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, int, int, int);
11351 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
11352 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
11353 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
11354 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
11355 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
11356 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
11357 SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
11358 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
11359 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
11360 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
11361 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
11362 SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
11363 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
11364 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
11365 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
11366 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
11367 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
11368 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
11369 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
11370 SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
11371 SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
11372 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
11373 SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
11374 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*);
11375 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
11376 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
11377 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
11378 SQLITE_PRIVATE void sqlite3PrngSaveState(void);
11379 SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
11380 SQLITE_PRIVATE void sqlite3PrngResetState(void);
11381 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*);
11382 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
11383 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
11384 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
11385 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
11386 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
11387 SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
11388 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
11389 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
11390 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
11391 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
11392 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
11393 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
11394 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
11395 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
11396 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
11397 SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int);
11398 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
11399 SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
11400 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
11401                                      int*,int,int,int,int,int*);
11402 SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
11403 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
11404 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
11405 SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
11406 SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
11407 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, char*, int);
11408 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
11409 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
11410 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
11411 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
11412 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
11413 SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
11414 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int);
11415 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
11416 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
11417 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
11418 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
11419 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
11420 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
11421
11422 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
11423 SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
11424 #endif
11425
11426 #ifndef SQLITE_OMIT_TRIGGER
11427 SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
11428                            Expr*,int, int);
11429 SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
11430 SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
11431 SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
11432 SQLITE_PRIVATE   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
11433 SQLITE_PRIVATE   Trigger *sqlite3TriggerList(Parse *, Table *);
11434 SQLITE_PRIVATE   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
11435                             int, int, int);
11436 SQLITE_PRIVATE   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
11437   void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
11438 SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
11439 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
11440 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
11441                                         ExprList*,Select*,u8);
11442 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
11443 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
11444 SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
11445 SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
11446 SQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
11447 # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
11448 #else
11449 # define sqlite3TriggersExist(B,C,D,E,F) 0
11450 # define sqlite3DeleteTrigger(A,B)
11451 # define sqlite3DropTriggerPtr(A,B)
11452 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
11453 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
11454 # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
11455 # define sqlite3TriggerList(X, Y) 0
11456 # define sqlite3ParseToplevel(p) p
11457 # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
11458 #endif
11459
11460 SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
11461 SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
11462 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
11463 #ifndef SQLITE_OMIT_AUTHORIZATION
11464 SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
11465 SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
11466 SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
11467 SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
11468 SQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
11469 #else
11470 # define sqlite3AuthRead(a,b,c,d)
11471 # define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
11472 # define sqlite3AuthContextPush(a,b,c)
11473 # define sqlite3AuthContextPop(a)  ((void)(a))
11474 #endif
11475 SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
11476 SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
11477 SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
11478 SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
11479 SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
11480 SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
11481 SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
11482 SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
11483 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
11484 SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
11485 SQLITE_PRIVATE int sqlite3Atoi(const char*);
11486 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
11487 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
11488 SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8*, const u8**);
11489
11490 /*
11491 ** Routines to read and write variable-length integers.  These used to
11492 ** be defined locally, but now we use the varint routines in the util.c
11493 ** file.  Code should use the MACRO forms below, as the Varint32 versions
11494 ** are coded to assume the single byte case is already handled (which 
11495 ** the MACRO form does).
11496 */
11497 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
11498 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
11499 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
11500 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
11501 SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
11502
11503 /*
11504 ** The header of a record consists of a sequence variable-length integers.
11505 ** These integers are almost always small and are encoded as a single byte.
11506 ** The following macros take advantage this fact to provide a fast encode
11507 ** and decode of the integers in a record header.  It is faster for the common
11508 ** case where the integer is a single byte.  It is a little slower when the
11509 ** integer is two or more bytes.  But overall it is faster.
11510 **
11511 ** The following expressions are equivalent:
11512 **
11513 **     x = sqlite3GetVarint32( A, &B );
11514 **     x = sqlite3PutVarint32( A, B );
11515 **
11516 **     x = getVarint32( A, B );
11517 **     x = putVarint32( A, B );
11518 **
11519 */
11520 #define getVarint32(A,B)  (u8)((*(A)<(u8)0x80) ? ((B) = (u32)*(A)),1 : sqlite3GetVarint32((A), (u32 *)&(B)))
11521 #define putVarint32(A,B)  (u8)(((u32)(B)<(u32)0x80) ? (*(A) = (unsigned char)(B)),1 : sqlite3PutVarint32((A), (B)))
11522 #define getVarint    sqlite3GetVarint
11523 #define putVarint    sqlite3PutVarint
11524
11525
11526 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
11527 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
11528 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
11529 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
11530 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
11531 SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
11532 SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
11533 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
11534 SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
11535 SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
11536 SQLITE_PRIVATE const char *sqlite3ErrStr(int);
11537 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
11538 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
11539 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
11540 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
11541 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Expr*, CollSeq*);
11542 SQLITE_PRIVATE Expr *sqlite3ExprSetCollByToken(Parse *pParse, Expr*, Token*);
11543 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
11544 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
11545 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
11546 SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
11547 SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
11548 SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
11549 SQLITE_PRIVATE int sqlite3AbsInt32(int);
11550 #ifdef SQLITE_ENABLE_8_3_NAMES
11551 SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
11552 #else
11553 # define sqlite3FileSuffix3(X,Y)
11554 #endif
11555 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z);
11556
11557 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
11558 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
11559 SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8, 
11560                         void(*)(void*));
11561 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
11562 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
11563 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
11564 #ifdef SQLITE_ENABLE_STAT2
11565 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *, u8, char *, int, int *);
11566 #endif
11567 SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
11568 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
11569 #ifndef SQLITE_AMALGAMATION
11570 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
11571 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
11572 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
11573 SQLITE_PRIVATE const Token sqlite3IntTokens[];
11574 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
11575 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
11576 #ifndef SQLITE_OMIT_WSD
11577 SQLITE_PRIVATE int sqlite3PendingByte;
11578 #endif
11579 #endif
11580 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
11581 SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
11582 SQLITE_PRIVATE void sqlite3AlterFunctions(void);
11583 SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
11584 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
11585 SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
11586 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
11587 SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
11588 SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
11589 SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
11590 SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
11591 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
11592 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
11593 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
11594 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
11595 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(sqlite3*, u8, CollSeq *, const char*);
11596 SQLITE_PRIVATE char sqlite3AffinityType(const char*);
11597 SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
11598 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
11599 SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
11600 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
11601 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
11602 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
11603 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
11604 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
11605 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
11606 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
11607 SQLITE_PRIVATE void sqlite3SchemaClear(void *);
11608 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
11609 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
11610 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
11611 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *, 
11612   void (*)(sqlite3_context*,int,sqlite3_value **),
11613   void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
11614   FuncDestructor *pDestructor
11615 );
11616 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
11617 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
11618
11619 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
11620 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
11621 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
11622 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
11623 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
11624 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
11625
11626 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
11627 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
11628
11629 /*
11630 ** The interface to the LEMON-generated parser
11631 */
11632 SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
11633 SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
11634 SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
11635 #ifdef YYTRACKMAXSTACKDEPTH
11636 SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
11637 #endif
11638
11639 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
11640 #ifndef SQLITE_OMIT_LOAD_EXTENSION
11641 SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
11642 #else
11643 # define sqlite3CloseExtensions(X)
11644 #endif
11645
11646 #ifndef SQLITE_OMIT_SHARED_CACHE
11647 SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
11648 #else
11649   #define sqlite3TableLock(v,w,x,y,z)
11650 #endif
11651
11652 #ifdef SQLITE_TEST
11653 SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
11654 #endif
11655
11656 #ifdef SQLITE_OMIT_VIRTUALTABLE
11657 #  define sqlite3VtabClear(Y)
11658 #  define sqlite3VtabSync(X,Y) SQLITE_OK
11659 #  define sqlite3VtabRollback(X)
11660 #  define sqlite3VtabCommit(X)
11661 #  define sqlite3VtabInSync(db) 0
11662 #  define sqlite3VtabLock(X) 
11663 #  define sqlite3VtabUnlock(X)
11664 #  define sqlite3VtabUnlockList(X)
11665 #  define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
11666 #else
11667 SQLITE_PRIVATE    void sqlite3VtabClear(sqlite3 *db, Table*);
11668 SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, char **);
11669 SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
11670 SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
11671 SQLITE_PRIVATE    void sqlite3VtabLock(VTable *);
11672 SQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);
11673 SQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);
11674 SQLITE_PRIVATE    int sqlite3VtabSavepoint(sqlite3 *, int, int);
11675 #  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
11676 #endif
11677 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
11678 SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*);
11679 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
11680 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
11681 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
11682 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
11683 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
11684 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
11685 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
11686 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
11687 SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
11688 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
11689 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
11690 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
11691 SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
11692 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
11693 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
11694 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
11695 SQLITE_PRIVATE const char *sqlite3JournalModename(int);
11696 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
11697 SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
11698
11699 /* Declarations for functions in fkey.c. All of these are replaced by
11700 ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
11701 ** key functionality is available. If OMIT_TRIGGER is defined but
11702 ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
11703 ** this case foreign keys are parsed, but no other functionality is 
11704 ** provided (enforcement of FK constraints requires the triggers sub-system).
11705 */
11706 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
11707 SQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int);
11708 SQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);
11709 SQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int);
11710 SQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);
11711 SQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);
11712 SQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);
11713 #else
11714   #define sqlite3FkActions(a,b,c,d)
11715   #define sqlite3FkCheck(a,b,c,d)
11716   #define sqlite3FkDropTable(a,b,c)
11717   #define sqlite3FkOldmask(a,b)      0
11718   #define sqlite3FkRequired(a,b,c,d) 0
11719 #endif
11720 #ifndef SQLITE_OMIT_FOREIGN_KEY
11721 SQLITE_PRIVATE   void sqlite3FkDelete(sqlite3 *, Table*);
11722 #else
11723   #define sqlite3FkDelete(a,b)
11724 #endif
11725
11726
11727 /*
11728 ** Available fault injectors.  Should be numbered beginning with 0.
11729 */
11730 #define SQLITE_FAULTINJECTOR_MALLOC     0
11731 #define SQLITE_FAULTINJECTOR_COUNT      1
11732
11733 /*
11734 ** The interface to the code in fault.c used for identifying "benign"
11735 ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
11736 ** is not defined.
11737 */
11738 #ifndef SQLITE_OMIT_BUILTIN_TEST
11739 SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
11740 SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
11741 #else
11742   #define sqlite3BeginBenignMalloc()
11743   #define sqlite3EndBenignMalloc()
11744 #endif
11745
11746 #define IN_INDEX_ROWID           1
11747 #define IN_INDEX_EPH             2
11748 #define IN_INDEX_INDEX           3
11749 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
11750
11751 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
11752 SQLITE_PRIVATE   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
11753 SQLITE_PRIVATE   int sqlite3JournalSize(sqlite3_vfs *);
11754 SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
11755 #else
11756   #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
11757 #endif
11758
11759 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
11760 SQLITE_PRIVATE int sqlite3MemJournalSize(void);
11761 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
11762
11763 #if SQLITE_MAX_EXPR_DEPTH>0
11764 SQLITE_PRIVATE   void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
11765 SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
11766 SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
11767 #else
11768   #define sqlite3ExprSetHeight(x,y)
11769   #define sqlite3SelectExprHeight(x) 0
11770   #define sqlite3ExprCheckHeight(x,y)
11771 #endif
11772
11773 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
11774 SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
11775
11776 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
11777 SQLITE_PRIVATE   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
11778 SQLITE_PRIVATE   void sqlite3ConnectionUnlocked(sqlite3 *db);
11779 SQLITE_PRIVATE   void sqlite3ConnectionClosed(sqlite3 *db);
11780 #else
11781   #define sqlite3ConnectionBlocked(x,y)
11782   #define sqlite3ConnectionUnlocked(x)
11783   #define sqlite3ConnectionClosed(x)
11784 #endif
11785
11786 #ifdef SQLITE_DEBUG
11787 SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
11788 #endif
11789
11790 /*
11791 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
11792 ** sqlite3IoTrace is a pointer to a printf-like routine used to
11793 ** print I/O tracing messages. 
11794 */
11795 #ifdef SQLITE_ENABLE_IOTRACE
11796 # define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
11797 SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
11798 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
11799 #else
11800 # define IOTRACE(A)
11801 # define sqlite3VdbeIOTraceSql(X)
11802 #endif
11803
11804 /*
11805 ** These routines are available for the mem2.c debugging memory allocator
11806 ** only.  They are used to verify that different "types" of memory
11807 ** allocations are properly tracked by the system.
11808 **
11809 ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
11810 ** the MEMTYPE_* macros defined below.  The type must be a bitmask with
11811 ** a single bit set.
11812 **
11813 ** sqlite3MemdebugHasType() returns true if any of the bits in its second
11814 ** argument match the type set by the previous sqlite3MemdebugSetType().
11815 ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
11816 **
11817 ** sqlite3MemdebugNoType() returns true if none of the bits in its second
11818 ** argument match the type set by the previous sqlite3MemdebugSetType().
11819 **
11820 ** Perhaps the most important point is the difference between MEMTYPE_HEAP
11821 ** and MEMTYPE_LOOKASIDE.  If an allocation is MEMTYPE_LOOKASIDE, that means
11822 ** it might have been allocated by lookaside, except the allocation was
11823 ** too large or lookaside was already full.  It is important to verify
11824 ** that allocations that might have been satisfied by lookaside are not
11825 ** passed back to non-lookaside free() routines.  Asserts such as the
11826 ** example above are placed on the non-lookaside free() routines to verify
11827 ** this constraint. 
11828 **
11829 ** All of this is no-op for a production build.  It only comes into
11830 ** play when the SQLITE_MEMDEBUG compile-time option is used.
11831 */
11832 #ifdef SQLITE_MEMDEBUG
11833 SQLITE_PRIVATE   void sqlite3MemdebugSetType(void*,u8);
11834 SQLITE_PRIVATE   int sqlite3MemdebugHasType(void*,u8);
11835 SQLITE_PRIVATE   int sqlite3MemdebugNoType(void*,u8);
11836 #else
11837 # define sqlite3MemdebugSetType(X,Y)  /* no-op */
11838 # define sqlite3MemdebugHasType(X,Y)  1
11839 # define sqlite3MemdebugNoType(X,Y)   1
11840 #endif
11841 #define MEMTYPE_HEAP       0x01  /* General heap allocations */
11842 #define MEMTYPE_LOOKASIDE  0x02  /* Might have been lookaside memory */
11843 #define MEMTYPE_SCRATCH    0x04  /* Scratch allocations */
11844 #define MEMTYPE_PCACHE     0x08  /* Page cache allocations */
11845 #define MEMTYPE_DB         0x10  /* Uses sqlite3DbMalloc, not sqlite_malloc */
11846
11847 #endif /* _SQLITEINT_H_ */
11848
11849 /************** End of sqliteInt.h *******************************************/
11850 /************** Begin file global.c ******************************************/
11851 /*
11852 ** 2008 June 13
11853 **
11854 ** The author disclaims copyright to this source code.  In place of
11855 ** a legal notice, here is a blessing:
11856 **
11857 **    May you do good and not evil.
11858 **    May you find forgiveness for yourself and forgive others.
11859 **    May you share freely, never taking more than you give.
11860 **
11861 *************************************************************************
11862 **
11863 ** This file contains definitions of global variables and contants.
11864 */
11865
11866 /* An array to map all upper-case characters into their corresponding
11867 ** lower-case character. 
11868 **
11869 ** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
11870 ** handle case conversions for the UTF character set since the tables
11871 ** involved are nearly as big or bigger than SQLite itself.
11872 */
11873 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
11874 #ifdef SQLITE_ASCII
11875       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
11876      18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
11877      36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
11878      54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
11879     104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
11880     122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
11881     108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
11882     126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
11883     144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
11884     162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
11885     180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
11886     198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
11887     216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
11888     234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
11889     252,253,254,255
11890 #endif
11891 #ifdef SQLITE_EBCDIC
11892       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
11893      16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
11894      32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
11895      48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
11896      64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
11897      80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
11898      96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
11899     112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
11900     128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
11901     144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
11902     160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
11903     176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
11904     192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
11905     208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
11906     224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
11907     239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
11908 #endif
11909 };
11910
11911 /*
11912 ** The following 256 byte lookup table is used to support SQLites built-in
11913 ** equivalents to the following standard library functions:
11914 **
11915 **   isspace()                        0x01
11916 **   isalpha()                        0x02
11917 **   isdigit()                        0x04
11918 **   isalnum()                        0x06
11919 **   isxdigit()                       0x08
11920 **   toupper()                        0x20
11921 **   SQLite identifier character      0x40
11922 **
11923 ** Bit 0x20 is set if the mapped character requires translation to upper
11924 ** case. i.e. if the character is a lower-case ASCII character.
11925 ** If x is a lower-case ASCII character, then its upper-case equivalent
11926 ** is (x - 0x20). Therefore toupper() can be implemented as:
11927 **
11928 **   (x & ~(map[x]&0x20))
11929 **
11930 ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
11931 ** array. tolower() is used more often than toupper() by SQLite.
11932 **
11933 ** Bit 0x40 is set if the character non-alphanumeric and can be used in an 
11934 ** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
11935 ** non-ASCII UTF character. Hence the test for whether or not a character is
11936 ** part of an identifier is 0x46.
11937 **
11938 ** SQLite's versions are identical to the standard versions assuming a
11939 ** locale of "C". They are implemented as macros in sqliteInt.h.
11940 */
11941 #ifdef SQLITE_ASCII
11942 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
11943   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
11944   0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
11945   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
11946   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
11947   0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,  /* 20..27     !"#$%&' */
11948   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
11949   0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
11950   0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
11951
11952   0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
11953   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
11954   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
11955   0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\]^_ */
11956   0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
11957   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
11958   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
11959   0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
11960
11961   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */
11962   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */
11963   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */
11964   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */
11965   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */
11966   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */
11967   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */
11968   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */
11969
11970   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */
11971   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */
11972   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */
11973   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */
11974   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
11975   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
11976   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
11977   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
11978 };
11979 #endif
11980
11981 #ifndef SQLITE_USE_URI
11982 # define  SQLITE_USE_URI 0
11983 #endif
11984
11985 /*
11986 ** The following singleton contains the global configuration for
11987 ** the SQLite library.
11988 */
11989 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
11990    SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
11991    1,                         /* bCoreMutex */
11992    SQLITE_THREADSAFE==1,      /* bFullMutex */
11993    SQLITE_USE_URI,            /* bOpenUri */
11994    0x7ffffffe,                /* mxStrlen */
11995    100,                       /* szLookaside */
11996    500,                       /* nLookaside */
11997    {0,0,0,0,0,0,0,0},         /* m */
11998    {0,0,0,0,0,0,0,0,0},       /* mutex */
11999    {0,0,0,0,0,0,0,0,0,0,0},   /* pcache */
12000    (void*)0,                  /* pHeap */
12001    0,                         /* nHeap */
12002    0, 0,                      /* mnHeap, mxHeap */
12003    (void*)0,                  /* pScratch */
12004    0,                         /* szScratch */
12005    0,                         /* nScratch */
12006    (void*)0,                  /* pPage */
12007    0,                         /* szPage */
12008    0,                         /* nPage */
12009    0,                         /* mxParserStack */
12010    0,                         /* sharedCacheEnabled */
12011    /* All the rest should always be initialized to zero */
12012    0,                         /* isInit */
12013    0,                         /* inProgress */
12014    0,                         /* isMutexInit */
12015    0,                         /* isMallocInit */
12016    0,                         /* isPCacheInit */
12017    0,                         /* pInitMutex */
12018    0,                         /* nRefInitMutex */
12019    0,                         /* xLog */
12020    0,                         /* pLogArg */
12021    0,                         /* bLocaltimeFault */
12022 };
12023
12024
12025 /*
12026 ** Hash table for global functions - functions common to all
12027 ** database connections.  After initialization, this table is
12028 ** read-only.
12029 */
12030 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
12031
12032 /*
12033 ** Constant tokens for values 0 and 1.
12034 */
12035 SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
12036    { "0", 1 },
12037    { "1", 1 }
12038 };
12039
12040
12041 /*
12042 ** The value of the "pending" byte must be 0x40000000 (1 byte past the
12043 ** 1-gibabyte boundary) in a compatible database.  SQLite never uses
12044 ** the database page that contains the pending byte.  It never attempts
12045 ** to read or write that page.  The pending byte page is set assign
12046 ** for use by the VFS layers as space for managing file locks.
12047 **
12048 ** During testing, it is often desirable to move the pending byte to
12049 ** a different position in the file.  This allows code that has to
12050 ** deal with the pending byte to run on files that are much smaller
12051 ** than 1 GiB.  The sqlite3_test_control() interface can be used to
12052 ** move the pending byte.
12053 **
12054 ** IMPORTANT:  Changing the pending byte to any value other than
12055 ** 0x40000000 results in an incompatible database file format!
12056 ** Changing the pending byte during operating results in undefined
12057 ** and dileterious behavior.
12058 */
12059 #ifndef SQLITE_OMIT_WSD
12060 SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
12061 #endif
12062
12063 /*
12064 ** Properties of opcodes.  The OPFLG_INITIALIZER macro is
12065 ** created by mkopcodeh.awk during compilation.  Data is obtained
12066 ** from the comments following the "case OP_xxxx:" statements in
12067 ** the vdbe.c file.  
12068 */
12069 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
12070
12071 /************** End of global.c **********************************************/
12072 /************** Begin file ctime.c *******************************************/
12073 /*
12074 ** 2010 February 23
12075 **
12076 ** The author disclaims copyright to this source code.  In place of
12077 ** a legal notice, here is a blessing:
12078 **
12079 **    May you do good and not evil.
12080 **    May you find forgiveness for yourself and forgive others.
12081 **    May you share freely, never taking more than you give.
12082 **
12083 *************************************************************************
12084 **
12085 ** This file implements routines used to report what compile-time options
12086 ** SQLite was built with.
12087 */
12088
12089 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
12090
12091
12092 /*
12093 ** An array of names of all compile-time options.  This array should 
12094 ** be sorted A-Z.
12095 **
12096 ** This array looks large, but in a typical installation actually uses
12097 ** only a handful of compile-time options, so most times this array is usually
12098 ** rather short and uses little memory space.
12099 */
12100 static const char * const azCompileOpt[] = {
12101
12102 /* These macros are provided to "stringify" the value of the define
12103 ** for those options in which the value is meaningful. */
12104 #define CTIMEOPT_VAL_(opt) #opt
12105 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
12106
12107 #ifdef SQLITE_32BIT_ROWID
12108   "32BIT_ROWID",
12109 #endif
12110 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
12111   "4_BYTE_ALIGNED_MALLOC",
12112 #endif
12113 #ifdef SQLITE_CASE_SENSITIVE_LIKE
12114   "CASE_SENSITIVE_LIKE",
12115 #endif
12116 #ifdef SQLITE_CHECK_PAGES
12117   "CHECK_PAGES",
12118 #endif
12119 #ifdef SQLITE_COVERAGE_TEST
12120   "COVERAGE_TEST",
12121 #endif
12122 #ifdef SQLITE_DEBUG
12123   "DEBUG",
12124 #endif
12125 #ifdef SQLITE_DEFAULT_LOCKING_MODE
12126   "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
12127 #endif
12128 #ifdef SQLITE_DISABLE_DIRSYNC
12129   "DISABLE_DIRSYNC",
12130 #endif
12131 #ifdef SQLITE_DISABLE_LFS
12132   "DISABLE_LFS",
12133 #endif
12134 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
12135   "ENABLE_ATOMIC_WRITE",
12136 #endif
12137 #ifdef SQLITE_ENABLE_CEROD
12138   "ENABLE_CEROD",
12139 #endif
12140 #ifdef SQLITE_ENABLE_COLUMN_METADATA
12141   "ENABLE_COLUMN_METADATA",
12142 #endif
12143 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
12144   "ENABLE_EXPENSIVE_ASSERT",
12145 #endif
12146 #ifdef SQLITE_ENABLE_FTS1
12147   "ENABLE_FTS1",
12148 #endif
12149 #ifdef SQLITE_ENABLE_FTS2
12150   "ENABLE_FTS2",
12151 #endif
12152 #ifdef SQLITE_ENABLE_FTS3
12153   "ENABLE_FTS3",
12154 #endif
12155 #ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
12156   "ENABLE_FTS3_PARENTHESIS",
12157 #endif
12158 #ifdef SQLITE_ENABLE_FTS4
12159   "ENABLE_FTS4",
12160 #endif
12161 #ifdef SQLITE_ENABLE_ICU
12162   "ENABLE_ICU",
12163 #endif
12164 #ifdef SQLITE_ENABLE_IOTRACE
12165   "ENABLE_IOTRACE",
12166 #endif
12167 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
12168   "ENABLE_LOAD_EXTENSION",
12169 #endif
12170 #ifdef SQLITE_ENABLE_LOCKING_STYLE
12171   "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
12172 #endif
12173 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
12174   "ENABLE_MEMORY_MANAGEMENT",
12175 #endif
12176 #ifdef SQLITE_ENABLE_MEMSYS3
12177   "ENABLE_MEMSYS3",
12178 #endif
12179 #ifdef SQLITE_ENABLE_MEMSYS5
12180   "ENABLE_MEMSYS5",
12181 #endif
12182 #ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
12183   "ENABLE_OVERSIZE_CELL_CHECK",
12184 #endif
12185 #ifdef SQLITE_ENABLE_RTREE
12186   "ENABLE_RTREE",
12187 #endif
12188 #ifdef SQLITE_ENABLE_STAT2
12189   "ENABLE_STAT2",
12190 #endif
12191 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
12192   "ENABLE_UNLOCK_NOTIFY",
12193 #endif
12194 #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
12195   "ENABLE_UPDATE_DELETE_LIMIT",
12196 #endif
12197 #ifdef SQLITE_HAS_CODEC
12198   "HAS_CODEC",
12199 #endif
12200 #ifdef SQLITE_HAVE_ISNAN
12201   "HAVE_ISNAN",
12202 #endif
12203 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
12204   "HOMEGROWN_RECURSIVE_MUTEX",
12205 #endif
12206 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
12207   "IGNORE_AFP_LOCK_ERRORS",
12208 #endif
12209 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
12210   "IGNORE_FLOCK_LOCK_ERRORS",
12211 #endif
12212 #ifdef SQLITE_INT64_TYPE
12213   "INT64_TYPE",
12214 #endif
12215 #ifdef SQLITE_LOCK_TRACE
12216   "LOCK_TRACE",
12217 #endif
12218 #ifdef SQLITE_MEMDEBUG
12219   "MEMDEBUG",
12220 #endif
12221 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
12222   "MIXED_ENDIAN_64BIT_FLOAT",
12223 #endif
12224 #ifdef SQLITE_NO_SYNC
12225   "NO_SYNC",
12226 #endif
12227 #ifdef SQLITE_OMIT_ALTERTABLE
12228   "OMIT_ALTERTABLE",
12229 #endif
12230 #ifdef SQLITE_OMIT_ANALYZE
12231   "OMIT_ANALYZE",
12232 #endif
12233 #ifdef SQLITE_OMIT_ATTACH
12234   "OMIT_ATTACH",
12235 #endif
12236 #ifdef SQLITE_OMIT_AUTHORIZATION
12237   "OMIT_AUTHORIZATION",
12238 #endif
12239 #ifdef SQLITE_OMIT_AUTOINCREMENT
12240   "OMIT_AUTOINCREMENT",
12241 #endif
12242 #ifdef SQLITE_OMIT_AUTOINIT
12243   "OMIT_AUTOINIT",
12244 #endif
12245 #ifdef SQLITE_OMIT_AUTOMATIC_INDEX
12246   "OMIT_AUTOMATIC_INDEX",
12247 #endif
12248 #ifdef SQLITE_OMIT_AUTORESET
12249   "OMIT_AUTORESET",
12250 #endif
12251 #ifdef SQLITE_OMIT_AUTOVACUUM
12252   "OMIT_AUTOVACUUM",
12253 #endif
12254 #ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
12255   "OMIT_BETWEEN_OPTIMIZATION",
12256 #endif
12257 #ifdef SQLITE_OMIT_BLOB_LITERAL
12258   "OMIT_BLOB_LITERAL",
12259 #endif
12260 #ifdef SQLITE_OMIT_BTREECOUNT
12261   "OMIT_BTREECOUNT",
12262 #endif
12263 #ifdef SQLITE_OMIT_BUILTIN_TEST
12264   "OMIT_BUILTIN_TEST",
12265 #endif
12266 #ifdef SQLITE_OMIT_CAST
12267   "OMIT_CAST",
12268 #endif
12269 #ifdef SQLITE_OMIT_CHECK
12270   "OMIT_CHECK",
12271 #endif
12272 /* // redundant
12273 ** #ifdef SQLITE_OMIT_COMPILEOPTION_DIAGS
12274 **   "OMIT_COMPILEOPTION_DIAGS",
12275 ** #endif
12276 */
12277 #ifdef SQLITE_OMIT_COMPLETE
12278   "OMIT_COMPLETE",
12279 #endif
12280 #ifdef SQLITE_OMIT_COMPOUND_SELECT
12281   "OMIT_COMPOUND_SELECT",
12282 #endif
12283 #ifdef SQLITE_OMIT_DATETIME_FUNCS
12284   "OMIT_DATETIME_FUNCS",
12285 #endif
12286 #ifdef SQLITE_OMIT_DECLTYPE
12287   "OMIT_DECLTYPE",
12288 #endif
12289 #ifdef SQLITE_OMIT_DEPRECATED
12290   "OMIT_DEPRECATED",
12291 #endif
12292 #ifdef SQLITE_OMIT_DISKIO
12293   "OMIT_DISKIO",
12294 #endif
12295 #ifdef SQLITE_OMIT_EXPLAIN
12296   "OMIT_EXPLAIN",
12297 #endif
12298 #ifdef SQLITE_OMIT_FLAG_PRAGMAS
12299   "OMIT_FLAG_PRAGMAS",
12300 #endif
12301 #ifdef SQLITE_OMIT_FLOATING_POINT
12302   "OMIT_FLOATING_POINT",
12303 #endif
12304 #ifdef SQLITE_OMIT_FOREIGN_KEY
12305   "OMIT_FOREIGN_KEY",
12306 #endif
12307 #ifdef SQLITE_OMIT_GET_TABLE
12308   "OMIT_GET_TABLE",
12309 #endif
12310 #ifdef SQLITE_OMIT_INCRBLOB
12311   "OMIT_INCRBLOB",
12312 #endif
12313 #ifdef SQLITE_OMIT_INTEGRITY_CHECK
12314   "OMIT_INTEGRITY_CHECK",
12315 #endif
12316 #ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
12317   "OMIT_LIKE_OPTIMIZATION",
12318 #endif
12319 #ifdef SQLITE_OMIT_LOAD_EXTENSION
12320   "OMIT_LOAD_EXTENSION",
12321 #endif
12322 #ifdef SQLITE_OMIT_LOCALTIME
12323   "OMIT_LOCALTIME",
12324 #endif
12325 #ifdef SQLITE_OMIT_LOOKASIDE
12326   "OMIT_LOOKASIDE",
12327 #endif
12328 #ifdef SQLITE_OMIT_MEMORYDB
12329   "OMIT_MEMORYDB",
12330 #endif
12331 #ifdef SQLITE_OMIT_OR_OPTIMIZATION
12332   "OMIT_OR_OPTIMIZATION",
12333 #endif
12334 #ifdef SQLITE_OMIT_PAGER_PRAGMAS
12335   "OMIT_PAGER_PRAGMAS",
12336 #endif
12337 #ifdef SQLITE_OMIT_PRAGMA
12338   "OMIT_PRAGMA",
12339 #endif
12340 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
12341   "OMIT_PROGRESS_CALLBACK",
12342 #endif
12343 #ifdef SQLITE_OMIT_QUICKBALANCE
12344   "OMIT_QUICKBALANCE",
12345 #endif
12346 #ifdef SQLITE_OMIT_REINDEX
12347   "OMIT_REINDEX",
12348 #endif
12349 #ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
12350   "OMIT_SCHEMA_PRAGMAS",
12351 #endif
12352 #ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
12353   "OMIT_SCHEMA_VERSION_PRAGMAS",
12354 #endif
12355 #ifdef SQLITE_OMIT_SHARED_CACHE
12356   "OMIT_SHARED_CACHE",
12357 #endif
12358 #ifdef SQLITE_OMIT_SUBQUERY
12359   "OMIT_SUBQUERY",
12360 #endif
12361 #ifdef SQLITE_OMIT_TCL_VARIABLE
12362   "OMIT_TCL_VARIABLE",
12363 #endif
12364 #ifdef SQLITE_OMIT_TEMPDB
12365   "OMIT_TEMPDB",
12366 #endif
12367 #ifdef SQLITE_OMIT_TRACE
12368   "OMIT_TRACE",
12369 #endif
12370 #ifdef SQLITE_OMIT_TRIGGER
12371   "OMIT_TRIGGER",
12372 #endif
12373 #ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
12374   "OMIT_TRUNCATE_OPTIMIZATION",
12375 #endif
12376 #ifdef SQLITE_OMIT_UTF16
12377   "OMIT_UTF16",
12378 #endif
12379 #ifdef SQLITE_OMIT_VACUUM
12380   "OMIT_VACUUM",
12381 #endif
12382 #ifdef SQLITE_OMIT_VIEW
12383   "OMIT_VIEW",
12384 #endif
12385 #ifdef SQLITE_OMIT_VIRTUALTABLE
12386   "OMIT_VIRTUALTABLE",
12387 #endif
12388 #ifdef SQLITE_OMIT_WAL
12389   "OMIT_WAL",
12390 #endif
12391 #ifdef SQLITE_OMIT_WSD
12392   "OMIT_WSD",
12393 #endif
12394 #ifdef SQLITE_OMIT_XFER_OPT
12395   "OMIT_XFER_OPT",
12396 #endif
12397 #ifdef SQLITE_PERFORMANCE_TRACE
12398   "PERFORMANCE_TRACE",
12399 #endif
12400 #ifdef SQLITE_PROXY_DEBUG
12401   "PROXY_DEBUG",
12402 #endif
12403 #ifdef SQLITE_SECURE_DELETE
12404   "SECURE_DELETE",
12405 #endif
12406 #ifdef SQLITE_SMALL_STACK
12407   "SMALL_STACK",
12408 #endif
12409 #ifdef SQLITE_SOUNDEX
12410   "SOUNDEX",
12411 #endif
12412 #ifdef SQLITE_TCL
12413   "TCL",
12414 #endif
12415 #ifdef SQLITE_TEMP_STORE
12416   "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
12417 #endif
12418 #ifdef SQLITE_TEST
12419   "TEST",
12420 #endif
12421 #ifdef SQLITE_THREADSAFE
12422   "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
12423 #endif
12424 #ifdef SQLITE_USE_ALLOCA
12425   "USE_ALLOCA",
12426 #endif
12427 #ifdef SQLITE_ZERO_MALLOC
12428   "ZERO_MALLOC"
12429 #endif
12430 };
12431
12432 /*
12433 ** Given the name of a compile-time option, return true if that option
12434 ** was used and false if not.
12435 **
12436 ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
12437 ** is not required for a match.
12438 */
12439 SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
12440   int i, n;
12441   if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
12442   n = sqlite3Strlen30(zOptName);
12443
12444   /* Since ArraySize(azCompileOpt) is normally in single digits, a
12445   ** linear search is adequate.  No need for a binary search. */
12446   for(i=0; i<ArraySize(azCompileOpt); i++){
12447     if(   (sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0)
12448        && ( (azCompileOpt[i][n]==0) || (azCompileOpt[i][n]=='=') ) ) return 1;
12449   }
12450   return 0;
12451 }
12452
12453 /*
12454 ** Return the N-th compile-time option string.  If N is out of range,
12455 ** return a NULL pointer.
12456 */
12457 SQLITE_API const char *sqlite3_compileoption_get(int N){
12458   if( N>=0 && N<ArraySize(azCompileOpt) ){
12459     return azCompileOpt[N];
12460   }
12461   return 0;
12462 }
12463
12464 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
12465
12466 /************** End of ctime.c ***********************************************/
12467 /************** Begin file status.c ******************************************/
12468 /*
12469 ** 2008 June 18
12470 **
12471 ** The author disclaims copyright to this source code.  In place of
12472 ** a legal notice, here is a blessing:
12473 **
12474 **    May you do good and not evil.
12475 **    May you find forgiveness for yourself and forgive others.
12476 **    May you share freely, never taking more than you give.
12477 **
12478 *************************************************************************
12479 **
12480 ** This module implements the sqlite3_status() interface and related
12481 ** functionality.
12482 */
12483 /************** Include vdbeInt.h in the middle of status.c ******************/
12484 /************** Begin file vdbeInt.h *****************************************/
12485 /*
12486 ** 2003 September 6
12487 **
12488 ** The author disclaims copyright to this source code.  In place of
12489 ** a legal notice, here is a blessing:
12490 **
12491 **    May you do good and not evil.
12492 **    May you find forgiveness for yourself and forgive others.
12493 **    May you share freely, never taking more than you give.
12494 **
12495 *************************************************************************
12496 ** This is the header file for information that is private to the
12497 ** VDBE.  This information used to all be at the top of the single
12498 ** source code file "vdbe.c".  When that file became too big (over
12499 ** 6000 lines long) it was split up into several smaller files and
12500 ** this header information was factored out.
12501 */
12502 #ifndef _VDBEINT_H_
12503 #define _VDBEINT_H_
12504
12505 /*
12506 ** SQL is translated into a sequence of instructions to be
12507 ** executed by a virtual machine.  Each instruction is an instance
12508 ** of the following structure.
12509 */
12510 typedef struct VdbeOp Op;
12511
12512 /*
12513 ** Boolean values
12514 */
12515 typedef unsigned char Bool;
12516
12517 /*
12518 ** A cursor is a pointer into a single BTree within a database file.
12519 ** The cursor can seek to a BTree entry with a particular key, or
12520 ** loop over all entries of the Btree.  You can also insert new BTree
12521 ** entries or retrieve the key or data from the entry that the cursor
12522 ** is currently pointing to.
12523 ** 
12524 ** Every cursor that the virtual machine has open is represented by an
12525 ** instance of the following structure.
12526 */
12527 struct VdbeCursor {
12528   BtCursor *pCursor;    /* The cursor structure of the backend */
12529   Btree *pBt;           /* Separate file holding temporary table */
12530   KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
12531   int iDb;              /* Index of cursor database in db->aDb[] (or -1) */
12532   int pseudoTableReg;   /* Register holding pseudotable content. */
12533   int nField;           /* Number of fields in the header */
12534   Bool zeroed;          /* True if zeroed out and ready for reuse */
12535   Bool rowidIsValid;    /* True if lastRowid is valid */
12536   Bool atFirst;         /* True if pointing to first entry */
12537   Bool useRandomRowid;  /* Generate new record numbers semi-randomly */
12538   Bool nullRow;         /* True if pointing to a row with no data */
12539   Bool deferredMoveto;  /* A call to sqlite3BtreeMoveto() is needed */
12540   Bool isTable;         /* True if a table requiring integer keys */
12541   Bool isIndex;         /* True if an index containing keys only - no data */
12542   Bool isOrdered;       /* True if the underlying table is BTREE_UNORDERED */
12543   sqlite3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
12544   const sqlite3_module *pModule;     /* Module for cursor pVtabCursor */
12545   i64 seqCount;         /* Sequence counter */
12546   i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */
12547   i64 lastRowid;        /* Last rowid from a Next or NextIdx operation */
12548
12549   /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or 
12550   ** OP_IsUnique opcode on this cursor. */
12551   int seekResult;
12552
12553   /* Cached information about the header for the data record that the
12554   ** cursor is currently pointing to.  Only valid if cacheStatus matches
12555   ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
12556   ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
12557   ** the cache is out of date.
12558   **
12559   ** aRow might point to (ephemeral) data for the current row, or it might
12560   ** be NULL.
12561   */
12562   u32 cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
12563   int payloadSize;      /* Total number of bytes in the record */
12564   u32 *aType;           /* Type values for all entries in the record */
12565   u32 *aOffset;         /* Cached offsets to the start of each columns data */
12566   u8 *aRow;             /* Data for the current row, if all on one page */
12567 };
12568 typedef struct VdbeCursor VdbeCursor;
12569
12570 /*
12571 ** When a sub-program is executed (OP_Program), a structure of this type
12572 ** is allocated to store the current value of the program counter, as
12573 ** well as the current memory cell array and various other frame specific
12574 ** values stored in the Vdbe struct. When the sub-program is finished, 
12575 ** these values are copied back to the Vdbe from the VdbeFrame structure,
12576 ** restoring the state of the VM to as it was before the sub-program
12577 ** began executing.
12578 **
12579 ** The memory for a VdbeFrame object is allocated and managed by a memory
12580 ** cell in the parent (calling) frame. When the memory cell is deleted or
12581 ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
12582 ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
12583 ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
12584 ** this instead of deleting the VdbeFrame immediately is to avoid recursive
12585 ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
12586 ** child frame are released.
12587 **
12588 ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
12589 ** set to NULL if the currently executing frame is the main program.
12590 */
12591 typedef struct VdbeFrame VdbeFrame;
12592 struct VdbeFrame {
12593   Vdbe *v;                /* VM this frame belongs to */
12594   int pc;                 /* Program Counter in parent (calling) frame */
12595   Op *aOp;                /* Program instructions for parent frame */
12596   int nOp;                /* Size of aOp array */
12597   Mem *aMem;              /* Array of memory cells for parent frame */
12598   int nMem;               /* Number of entries in aMem */
12599   VdbeCursor **apCsr;     /* Array of Vdbe cursors for parent frame */
12600   u16 nCursor;            /* Number of entries in apCsr */
12601   void *token;            /* Copy of SubProgram.token */
12602   int nChildMem;          /* Number of memory cells for child frame */
12603   int nChildCsr;          /* Number of cursors for child frame */
12604   i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
12605   int nChange;            /* Statement changes (Vdbe.nChanges)     */
12606   VdbeFrame *pParent;     /* Parent of this frame, or NULL if parent is main */
12607 };
12608
12609 #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
12610
12611 /*
12612 ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
12613 */
12614 #define CACHE_STALE 0
12615
12616 /*
12617 ** Internally, the vdbe manipulates nearly all SQL values as Mem
12618 ** structures. Each Mem struct may cache multiple representations (string,
12619 ** integer etc.) of the same value.
12620 */
12621 struct Mem {
12622   sqlite3 *db;        /* The associated database connection */
12623   char *z;            /* String or BLOB value */
12624   double r;           /* Real value */
12625   union {
12626     i64 i;              /* Integer value used when MEM_Int is set in flags */
12627     int nZero;          /* Used when bit MEM_Zero is set in flags */
12628     FuncDef *pDef;      /* Used only when flags==MEM_Agg */
12629     RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
12630     VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */
12631   } u;
12632   int n;              /* Number of characters in string value, excluding '\0' */
12633   u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
12634   u8  type;           /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
12635   u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
12636 #ifdef SQLITE_DEBUG
12637   Mem *pScopyFrom;    /* This Mem is a shallow copy of pScopyFrom */
12638   void *pFiller;      /* So that sizeof(Mem) is a multiple of 8 */
12639 #endif
12640   void (*xDel)(void *);  /* If not null, call this function to delete Mem.z */
12641   char *zMalloc;      /* Dynamic buffer allocated by sqlite3_malloc() */
12642 };
12643
12644 /* One or more of the following flags are set to indicate the validOK
12645 ** representations of the value stored in the Mem struct.
12646 **
12647 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
12648 ** No other flags may be set in this case.
12649 **
12650 ** If the MEM_Str flag is set then Mem.z points at a string representation.
12651 ** Usually this is encoded in the same unicode encoding as the main
12652 ** database (see below for exceptions). If the MEM_Term flag is also
12653 ** set, then the string is nul terminated. The MEM_Int and MEM_Real 
12654 ** flags may coexist with the MEM_Str flag.
12655 */
12656 #define MEM_Null      0x0001   /* Value is NULL */
12657 #define MEM_Str       0x0002   /* Value is a string */
12658 #define MEM_Int       0x0004   /* Value is an integer */
12659 #define MEM_Real      0x0008   /* Value is a real number */
12660 #define MEM_Blob      0x0010   /* Value is a BLOB */
12661 #define MEM_RowSet    0x0020   /* Value is a RowSet object */
12662 #define MEM_Frame     0x0040   /* Value is a VdbeFrame object */
12663 #define MEM_Invalid   0x0080   /* Value is undefined */
12664 #define MEM_TypeMask  0x00ff   /* Mask of type bits */
12665
12666 /* Whenever Mem contains a valid string or blob representation, one of
12667 ** the following flags must be set to determine the memory management
12668 ** policy for Mem.z.  The MEM_Term flag tells us whether or not the
12669 ** string is \000 or \u0000 terminated
12670 */
12671 #define MEM_Term      0x0200   /* String rep is nul terminated */
12672 #define MEM_Dyn       0x0400   /* Need to call sqliteFree() on Mem.z */
12673 #define MEM_Static    0x0800   /* Mem.z points to a static string */
12674 #define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
12675 #define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
12676 #define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
12677 #ifdef SQLITE_OMIT_INCRBLOB
12678   #undef MEM_Zero
12679   #define MEM_Zero 0x0000
12680 #endif
12681
12682 /*
12683 ** Clear any existing type flags from a Mem and replace them with f
12684 */
12685 #define MemSetTypeFlag(p, f) \
12686    ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
12687
12688 /*
12689 ** Return true if a memory cell is not marked as invalid.  This macro
12690 ** is for use inside assert() statements only.
12691 */
12692 #ifdef SQLITE_DEBUG
12693 #define memIsValid(M)  ((M)->flags & MEM_Invalid)==0
12694 #endif
12695
12696
12697 /* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
12698 ** additional information about auxiliary information bound to arguments
12699 ** of the function.  This is used to implement the sqlite3_get_auxdata()
12700 ** and sqlite3_set_auxdata() APIs.  The "auxdata" is some auxiliary data
12701 ** that can be associated with a constant argument to a function.  This
12702 ** allows functions such as "regexp" to compile their constant regular
12703 ** expression argument once and reused the compiled code for multiple
12704 ** invocations.
12705 */
12706 struct VdbeFunc {
12707   FuncDef *pFunc;               /* The definition of the function */
12708   int nAux;                     /* Number of entries allocated for apAux[] */
12709   struct AuxData {
12710     void *pAux;                   /* Aux data for the i-th argument */
12711     void (*xDelete)(void *);      /* Destructor for the aux data */
12712   } apAux[1];                   /* One slot for each function argument */
12713 };
12714
12715 /*
12716 ** The "context" argument for a installable function.  A pointer to an
12717 ** instance of this structure is the first argument to the routines used
12718 ** implement the SQL functions.
12719 **
12720 ** There is a typedef for this structure in sqlite.h.  So all routines,
12721 ** even the public interface to SQLite, can use a pointer to this structure.
12722 ** But this file is the only place where the internal details of this
12723 ** structure are known.
12724 **
12725 ** This structure is defined inside of vdbeInt.h because it uses substructures
12726 ** (Mem) which are only defined there.
12727 */
12728 struct sqlite3_context {
12729   FuncDef *pFunc;       /* Pointer to function information.  MUST BE FIRST */
12730   VdbeFunc *pVdbeFunc;  /* Auxilary data, if created. */
12731   Mem s;                /* The return value is stored here */
12732   Mem *pMem;            /* Memory cell used to store aggregate context */
12733   int isError;          /* Error code returned by the function. */
12734   CollSeq *pColl;       /* Collating sequence */
12735 };
12736
12737 /*
12738 ** An instance of the virtual machine.  This structure contains the complete
12739 ** state of the virtual machine.
12740 **
12741 ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
12742 ** is really a pointer to an instance of this structure.
12743 **
12744 ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
12745 ** any virtual table method invocations made by the vdbe program. It is
12746 ** set to 2 for xDestroy method calls and 1 for all other methods. This
12747 ** variable is used for two purposes: to allow xDestroy methods to execute
12748 ** "DROP TABLE" statements and to prevent some nasty side effects of
12749 ** malloc failure when SQLite is invoked recursively by a virtual table 
12750 ** method function.
12751 */
12752 struct Vdbe {
12753   sqlite3 *db;            /* The database connection that owns this statement */
12754   Op *aOp;                /* Space to hold the virtual machine's program */
12755   Mem *aMem;              /* The memory locations */
12756   Mem **apArg;            /* Arguments to currently executing user function */
12757   Mem *aColName;          /* Column names to return */
12758   Mem *pResultSet;        /* Pointer to an array of results */
12759   int nMem;               /* Number of memory locations currently allocated */
12760   int nOp;                /* Number of instructions in the program */
12761   int nOpAlloc;           /* Number of slots allocated for aOp[] */
12762   int nLabel;             /* Number of labels used */
12763   int nLabelAlloc;        /* Number of slots allocated in aLabel[] */
12764   int *aLabel;            /* Space to hold the labels */
12765   u16 nResColumn;         /* Number of columns in one row of the result set */
12766   u16 nCursor;            /* Number of slots in apCsr[] */
12767   u32 magic;              /* Magic number for sanity checking */
12768   char *zErrMsg;          /* Error message written here */
12769   Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */
12770   VdbeCursor **apCsr;     /* One element of this array for each open cursor */
12771   Mem *aVar;              /* Values for the OP_Variable opcode. */
12772   char **azVar;           /* Name of variables */
12773   ynVar nVar;             /* Number of entries in aVar[] */
12774   ynVar nzVar;            /* Number of entries in azVar[] */
12775   u32 cacheCtr;           /* VdbeCursor row cache generation counter */
12776   int pc;                 /* The program counter */
12777   int rc;                 /* Value to return */
12778   u8 errorAction;         /* Recovery action to do in case of an error */
12779   u8 explain;             /* True if EXPLAIN present on SQL command */
12780   u8 changeCntOn;         /* True to update the change-counter */
12781   u8 expired;             /* True if the VM needs to be recompiled */
12782   u8 runOnlyOnce;         /* Automatically expire on reset */
12783   u8 minWriteFileFormat;  /* Minimum file format for writable database files */
12784   u8 inVtabMethod;        /* See comments above */
12785   u8 usesStmtJournal;     /* True if uses a statement journal */
12786   u8 readOnly;            /* True for read-only statements */
12787   u8 isPrepareV2;         /* True if prepared with prepare_v2() */
12788   int nChange;            /* Number of db changes made since last reset */
12789   yDbMask btreeMask;      /* Bitmask of db->aDb[] entries referenced */
12790   yDbMask lockMask;       /* Subset of btreeMask that requires a lock */
12791   int iStatement;         /* Statement number (or 0 if has not opened stmt) */
12792   int aCounter[3];        /* Counters used by sqlite3_stmt_status() */
12793 #ifndef SQLITE_OMIT_TRACE
12794   i64 startTime;          /* Time when query started - used for profiling */
12795 #endif
12796   i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
12797   i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
12798   char *zSql;             /* Text of the SQL statement that generated this */
12799   void *pFree;            /* Free this when deleting the vdbe */
12800 #ifdef SQLITE_DEBUG
12801   FILE *trace;            /* Write an execution trace here, if not NULL */
12802 #endif
12803   VdbeFrame *pFrame;      /* Parent frame */
12804   VdbeFrame *pDelFrame;   /* List of frame objects to free on VM reset */
12805   int nFrame;             /* Number of frames in pFrame list */
12806   u32 expmask;            /* Binding to these vars invalidates VM */
12807   SubProgram *pProgram;   /* Linked list of all sub-programs used by VM */
12808 };
12809
12810 /*
12811 ** The following are allowed values for Vdbe.magic
12812 */
12813 #define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
12814 #define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
12815 #define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
12816 #define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
12817
12818 /*
12819 ** Function prototypes
12820 */
12821 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
12822 void sqliteVdbePopStack(Vdbe*,int);
12823 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
12824 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
12825 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
12826 #endif
12827 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
12828 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
12829 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
12830 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
12831 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
12832
12833 int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
12834 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
12835 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);
12836 SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
12837 SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
12838 SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
12839 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
12840 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
12841 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
12842 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
12843 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
12844 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
12845 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
12846 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
12847 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
12848 #ifdef SQLITE_OMIT_FLOATING_POINT
12849 # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
12850 #else
12851 SQLITE_PRIVATE   void sqlite3VdbeMemSetDouble(Mem*, double);
12852 #endif
12853 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
12854 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
12855 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
12856 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
12857 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
12858 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
12859 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
12860 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
12861 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
12862 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
12863 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
12864 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
12865 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
12866 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
12867 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
12868 SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
12869 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
12870 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
12871 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
12872 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
12873 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem);
12874
12875 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
12876 SQLITE_PRIVATE   void sqlite3VdbeEnter(Vdbe*);
12877 SQLITE_PRIVATE   void sqlite3VdbeLeave(Vdbe*);
12878 #else
12879 # define sqlite3VdbeEnter(X)
12880 # define sqlite3VdbeLeave(X)
12881 #endif
12882
12883 #ifdef SQLITE_DEBUG
12884 SQLITE_PRIVATE void sqlite3VdbeMemPrepareToChange(Vdbe*,Mem*);
12885 #endif
12886
12887 #ifndef SQLITE_OMIT_FOREIGN_KEY
12888 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
12889 #else
12890 # define sqlite3VdbeCheckFk(p,i) 0
12891 #endif
12892
12893 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
12894 #ifdef SQLITE_DEBUG
12895 SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
12896 SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
12897 #endif
12898 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
12899
12900 #ifndef SQLITE_OMIT_INCRBLOB
12901 SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
12902 #else
12903   #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
12904 #endif
12905
12906 #endif /* !defined(_VDBEINT_H_) */
12907
12908 /************** End of vdbeInt.h *********************************************/
12909 /************** Continuing where we left off in status.c *********************/
12910
12911 /*
12912 ** Variables in which to record status information.
12913 */
12914 typedef struct sqlite3StatType sqlite3StatType;
12915 static SQLITE_WSD struct sqlite3StatType {
12916   int nowValue[10];         /* Current value */
12917   int mxValue[10];          /* Maximum value */
12918 } sqlite3Stat = { {0,}, {0,} };
12919
12920
12921 /* The "wsdStat" macro will resolve to the status information
12922 ** state vector.  If writable static data is unsupported on the target,
12923 ** we have to locate the state vector at run-time.  In the more common
12924 ** case where writable static data is supported, wsdStat can refer directly
12925 ** to the "sqlite3Stat" state vector declared above.
12926 */
12927 #ifdef SQLITE_OMIT_WSD
12928 # define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
12929 # define wsdStat x[0]
12930 #else
12931 # define wsdStatInit
12932 # define wsdStat sqlite3Stat
12933 #endif
12934
12935 /*
12936 ** Return the current value of a status parameter.
12937 */
12938 SQLITE_PRIVATE int sqlite3StatusValue(int op){
12939   wsdStatInit;
12940   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
12941   return wsdStat.nowValue[op];
12942 }
12943
12944 /*
12945 ** Add N to the value of a status record.  It is assumed that the
12946 ** caller holds appropriate locks.
12947 */
12948 SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
12949   wsdStatInit;
12950   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
12951   wsdStat.nowValue[op] += N;
12952   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
12953     wsdStat.mxValue[op] = wsdStat.nowValue[op];
12954   }
12955 }
12956
12957 /*
12958 ** Set the value of a status to X.
12959 */
12960 SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
12961   wsdStatInit;
12962   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
12963   wsdStat.nowValue[op] = X;
12964   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
12965     wsdStat.mxValue[op] = wsdStat.nowValue[op];
12966   }
12967 }
12968
12969 /*
12970 ** Query status information.
12971 **
12972 ** This implementation assumes that reading or writing an aligned
12973 ** 32-bit integer is an atomic operation.  If that assumption is not true,
12974 ** then this routine is not threadsafe.
12975 */
12976 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
12977   wsdStatInit;
12978   if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
12979     return SQLITE_MISUSE_BKPT;
12980   }
12981   *pCurrent = wsdStat.nowValue[op];
12982   *pHighwater = wsdStat.mxValue[op];
12983   if( resetFlag ){
12984     wsdStat.mxValue[op] = wsdStat.nowValue[op];
12985   }
12986   return SQLITE_OK;
12987 }
12988
12989 /*
12990 ** Query status information for a single database connection
12991 */
12992 SQLITE_API int sqlite3_db_status(
12993   sqlite3 *db,          /* The database connection whose status is desired */
12994   int op,               /* Status verb */
12995   int *pCurrent,        /* Write current value here */
12996   int *pHighwater,      /* Write high-water mark here */
12997   int resetFlag         /* Reset high-water mark if true */
12998 ){
12999   int rc = SQLITE_OK;   /* Return code */
13000   sqlite3_mutex_enter(db->mutex);
13001   switch( op ){
13002     case SQLITE_DBSTATUS_LOOKASIDE_USED: {
13003       *pCurrent = db->lookaside.nOut;
13004       *pHighwater = db->lookaside.mxOut;
13005       if( resetFlag ){
13006         db->lookaside.mxOut = db->lookaside.nOut;
13007       }
13008       break;
13009     }
13010
13011     case SQLITE_DBSTATUS_LOOKASIDE_HIT:
13012     case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
13013     case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
13014       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
13015       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
13016       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
13017       assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
13018       assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
13019       *pCurrent = 0;
13020       *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
13021       if( resetFlag ){
13022         db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
13023       }
13024       break;
13025     }
13026
13027     /* 
13028     ** Return an approximation for the amount of memory currently used
13029     ** by all pagers associated with the given database connection.  The
13030     ** highwater mark is meaningless and is returned as zero.
13031     */
13032     case SQLITE_DBSTATUS_CACHE_USED: {
13033       int totalUsed = 0;
13034       int i;
13035       sqlite3BtreeEnterAll(db);
13036       for(i=0; i<db->nDb; i++){
13037         Btree *pBt = db->aDb[i].pBt;
13038         if( pBt ){
13039           Pager *pPager = sqlite3BtreePager(pBt);
13040           totalUsed += sqlite3PagerMemUsed(pPager);
13041         }
13042       }
13043       sqlite3BtreeLeaveAll(db);
13044       *pCurrent = totalUsed;
13045       *pHighwater = 0;
13046       break;
13047     }
13048
13049     /*
13050     ** *pCurrent gets an accurate estimate of the amount of memory used
13051     ** to store the schema for all databases (main, temp, and any ATTACHed
13052     ** databases.  *pHighwater is set to zero.
13053     */
13054     case SQLITE_DBSTATUS_SCHEMA_USED: {
13055       int i;                      /* Used to iterate through schemas */
13056       int nByte = 0;              /* Used to accumulate return value */
13057
13058       sqlite3BtreeEnterAll(db);
13059       db->pnBytesFreed = &nByte;
13060       for(i=0; i<db->nDb; i++){
13061         Schema *pSchema = db->aDb[i].pSchema;
13062         if( ALWAYS(pSchema!=0) ){
13063           HashElem *p;
13064
13065           nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
13066               pSchema->tblHash.count 
13067             + pSchema->trigHash.count
13068             + pSchema->idxHash.count
13069             + pSchema->fkeyHash.count
13070           );
13071           nByte += sqlite3MallocSize(pSchema->tblHash.ht);
13072           nByte += sqlite3MallocSize(pSchema->trigHash.ht);
13073           nByte += sqlite3MallocSize(pSchema->idxHash.ht);
13074           nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);
13075
13076           for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
13077             sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
13078           }
13079           for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
13080             sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
13081           }
13082         }
13083       }
13084       db->pnBytesFreed = 0;
13085       sqlite3BtreeLeaveAll(db);
13086
13087       *pHighwater = 0;
13088       *pCurrent = nByte;
13089       break;
13090     }
13091
13092     /*
13093     ** *pCurrent gets an accurate estimate of the amount of memory used
13094     ** to store all prepared statements.
13095     ** *pHighwater is set to zero.
13096     */
13097     case SQLITE_DBSTATUS_STMT_USED: {
13098       struct Vdbe *pVdbe;         /* Used to iterate through VMs */
13099       int nByte = 0;              /* Used to accumulate return value */
13100
13101       db->pnBytesFreed = &nByte;
13102       for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
13103         sqlite3VdbeDeleteObject(db, pVdbe);
13104       }
13105       db->pnBytesFreed = 0;
13106
13107       *pHighwater = 0;
13108       *pCurrent = nByte;
13109
13110       break;
13111     }
13112
13113     default: {
13114       rc = SQLITE_ERROR;
13115     }
13116   }
13117   sqlite3_mutex_leave(db->mutex);
13118   return rc;
13119 }
13120
13121 /************** End of status.c **********************************************/
13122 /************** Begin file date.c ********************************************/
13123 /*
13124 ** 2003 October 31
13125 **
13126 ** The author disclaims copyright to this source code.  In place of
13127 ** a legal notice, here is a blessing:
13128 **
13129 **    May you do good and not evil.
13130 **    May you find forgiveness for yourself and forgive others.
13131 **    May you share freely, never taking more than you give.
13132 **
13133 *************************************************************************
13134 ** This file contains the C functions that implement date and time
13135 ** functions for SQLite.  
13136 **
13137 ** There is only one exported symbol in this file - the function
13138 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
13139 ** All other code has file scope.
13140 **
13141 ** SQLite processes all times and dates as Julian Day numbers.  The
13142 ** dates and times are stored as the number of days since noon
13143 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
13144 ** calendar system. 
13145 **
13146 ** 1970-01-01 00:00:00 is JD 2440587.5
13147 ** 2000-01-01 00:00:00 is JD 2451544.5
13148 **
13149 ** This implemention requires years to be expressed as a 4-digit number
13150 ** which means that only dates between 0000-01-01 and 9999-12-31 can
13151 ** be represented, even though julian day numbers allow a much wider
13152 ** range of dates.
13153 **
13154 ** The Gregorian calendar system is used for all dates and times,
13155 ** even those that predate the Gregorian calendar.  Historians usually
13156 ** use the Julian calendar for dates prior to 1582-10-15 and for some
13157 ** dates afterwards, depending on locale.  Beware of this difference.
13158 **
13159 ** The conversion algorithms are implemented based on descriptions
13160 ** in the following text:
13161 **
13162 **      Jean Meeus
13163 **      Astronomical Algorithms, 2nd Edition, 1998
13164 **      ISBM 0-943396-61-1
13165 **      Willmann-Bell, Inc
13166 **      Richmond, Virginia (USA)
13167 */
13168 #include <time.h>
13169
13170 #ifndef SQLITE_OMIT_DATETIME_FUNCS
13171
13172
13173 /*
13174 ** A structure for holding a single date and time.
13175 */
13176 typedef struct DateTime DateTime;
13177 struct DateTime {
13178   sqlite3_int64 iJD; /* The julian day number times 86400000 */
13179   int Y, M, D;       /* Year, month, and day */
13180   int h, m;          /* Hour and minutes */
13181   int tz;            /* Timezone offset in minutes */
13182   double s;          /* Seconds */
13183   char validYMD;     /* True (1) if Y,M,D are valid */
13184   char validHMS;     /* True (1) if h,m,s are valid */
13185   char validJD;      /* True (1) if iJD is valid */
13186   char validTZ;      /* True (1) if tz is valid */
13187 };
13188
13189
13190 /*
13191 ** Convert zDate into one or more integers.  Additional arguments
13192 ** come in groups of 5 as follows:
13193 **
13194 **       N       number of digits in the integer
13195 **       min     minimum allowed value of the integer
13196 **       max     maximum allowed value of the integer
13197 **       nextC   first character after the integer
13198 **       pVal    where to write the integers value.
13199 **
13200 ** Conversions continue until one with nextC==0 is encountered.
13201 ** The function returns the number of successful conversions.
13202 */
13203 static int getDigits(const char *zDate, ...){
13204   va_list ap;
13205   int val;
13206   int N;
13207   int min;
13208   int max;
13209   int nextC;
13210   int *pVal;
13211   int cnt = 0;
13212   va_start(ap, zDate);
13213   do{
13214     N = va_arg(ap, int);
13215     min = va_arg(ap, int);
13216     max = va_arg(ap, int);
13217     nextC = va_arg(ap, int);
13218     pVal = va_arg(ap, int*);
13219     val = 0;
13220     while( N-- ){
13221       if( !sqlite3Isdigit(*zDate) ){
13222         goto end_getDigits;
13223       }
13224       val = val*10 + *zDate - '0';
13225       zDate++;
13226     }
13227     if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
13228       goto end_getDigits;
13229     }
13230     *pVal = val;
13231     zDate++;
13232     cnt++;
13233   }while( nextC );
13234 end_getDigits:
13235   va_end(ap);
13236   return cnt;
13237 }
13238
13239 /*
13240 ** Parse a timezone extension on the end of a date-time.
13241 ** The extension is of the form:
13242 **
13243 **        (+/-)HH:MM
13244 **
13245 ** Or the "zulu" notation:
13246 **
13247 **        Z
13248 **
13249 ** If the parse is successful, write the number of minutes
13250 ** of change in p->tz and return 0.  If a parser error occurs,
13251 ** return non-zero.
13252 **
13253 ** A missing specifier is not considered an error.
13254 */
13255 static int parseTimezone(const char *zDate, DateTime *p){
13256   int sgn = 0;
13257   int nHr, nMn;
13258   int c;
13259   while( sqlite3Isspace(*zDate) ){ zDate++; }
13260   p->tz = 0;
13261   c = *zDate;
13262   if( c=='-' ){
13263     sgn = -1;
13264   }else if( c=='+' ){
13265     sgn = +1;
13266   }else if( c=='Z' || c=='z' ){
13267     zDate++;
13268     goto zulu_time;
13269   }else{
13270     return c!=0;
13271   }
13272   zDate++;
13273   if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
13274     return 1;
13275   }
13276   zDate += 5;
13277   p->tz = sgn*(nMn + nHr*60);
13278 zulu_time:
13279   while( sqlite3Isspace(*zDate) ){ zDate++; }
13280   return *zDate!=0;
13281 }
13282
13283 /*
13284 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
13285 ** The HH, MM, and SS must each be exactly 2 digits.  The
13286 ** fractional seconds FFFF can be one or more digits.
13287 **
13288 ** Return 1 if there is a parsing error and 0 on success.
13289 */
13290 static int parseHhMmSs(const char *zDate, DateTime *p){
13291   int h, m, s;
13292   double ms = 0.0;
13293   if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
13294     return 1;
13295   }
13296   zDate += 5;
13297   if( *zDate==':' ){
13298     zDate++;
13299     if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
13300       return 1;
13301     }
13302     zDate += 2;
13303     if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
13304       double rScale = 1.0;
13305       zDate++;
13306       while( sqlite3Isdigit(*zDate) ){
13307         ms = ms*10.0 + *zDate - '0';
13308         rScale *= 10.0;
13309         zDate++;
13310       }
13311       ms /= rScale;
13312     }
13313   }else{
13314     s = 0;
13315   }
13316   p->validJD = 0;
13317   p->validHMS = 1;
13318   p->h = h;
13319   p->m = m;
13320   p->s = s + ms;
13321   if( parseTimezone(zDate, p) ) return 1;
13322   p->validTZ = (p->tz!=0)?1:0;
13323   return 0;
13324 }
13325
13326 /*
13327 ** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
13328 ** that the YYYY-MM-DD is according to the Gregorian calendar.
13329 **
13330 ** Reference:  Meeus page 61
13331 */
13332 static void computeJD(DateTime *p){
13333   int Y, M, D, A, B, X1, X2;
13334
13335   if( p->validJD ) return;
13336   if( p->validYMD ){
13337     Y = p->Y;
13338     M = p->M;
13339     D = p->D;
13340   }else{
13341     Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
13342     M = 1;
13343     D = 1;
13344   }
13345   if( M<=2 ){
13346     Y--;
13347     M += 12;
13348   }
13349   A = Y/100;
13350   B = 2 - A + (A/4);
13351   X1 = 36525*(Y+4716)/100;
13352   X2 = 306001*(M+1)/10000;
13353   p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
13354   p->validJD = 1;
13355   if( p->validHMS ){
13356     p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
13357     if( p->validTZ ){
13358       p->iJD -= p->tz*60000;
13359       p->validYMD = 0;
13360       p->validHMS = 0;
13361       p->validTZ = 0;
13362     }
13363   }
13364 }
13365
13366 /*
13367 ** Parse dates of the form
13368 **
13369 **     YYYY-MM-DD HH:MM:SS.FFF
13370 **     YYYY-MM-DD HH:MM:SS
13371 **     YYYY-MM-DD HH:MM
13372 **     YYYY-MM-DD
13373 **
13374 ** Write the result into the DateTime structure and return 0
13375 ** on success and 1 if the input string is not a well-formed
13376 ** date.
13377 */
13378 static int parseYyyyMmDd(const char *zDate, DateTime *p){
13379   int Y, M, D, neg;
13380
13381   if( zDate[0]=='-' ){
13382     zDate++;
13383     neg = 1;
13384   }else{
13385     neg = 0;
13386   }
13387   if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
13388     return 1;
13389   }
13390   zDate += 10;
13391   while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
13392   if( parseHhMmSs(zDate, p)==0 ){
13393     /* We got the time */
13394   }else if( *zDate==0 ){
13395     p->validHMS = 0;
13396   }else{
13397     return 1;
13398   }
13399   p->validJD = 0;
13400   p->validYMD = 1;
13401   p->Y = neg ? -Y : Y;
13402   p->M = M;
13403   p->D = D;
13404   if( p->validTZ ){
13405     computeJD(p);
13406   }
13407   return 0;
13408 }
13409
13410 /*
13411 ** Set the time to the current time reported by the VFS
13412 */
13413 static void setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
13414   sqlite3 *db = sqlite3_context_db_handle(context);
13415   sqlite3OsCurrentTimeInt64(db->pVfs, &p->iJD);
13416   p->validJD = 1;
13417 }
13418
13419 /*
13420 ** Attempt to parse the given string into a Julian Day Number.  Return
13421 ** the number of errors.
13422 **
13423 ** The following are acceptable forms for the input string:
13424 **
13425 **      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
13426 **      DDDD.DD 
13427 **      now
13428 **
13429 ** In the first form, the +/-HH:MM is always optional.  The fractional
13430 ** seconds extension (the ".FFF") is optional.  The seconds portion
13431 ** (":SS.FFF") is option.  The year and date can be omitted as long
13432 ** as there is a time string.  The time string can be omitted as long
13433 ** as there is a year and date.
13434 */
13435 static int parseDateOrTime(
13436   sqlite3_context *context, 
13437   const char *zDate, 
13438   DateTime *p
13439 ){
13440   double r;
13441   if( parseYyyyMmDd(zDate,p)==0 ){
13442     return 0;
13443   }else if( parseHhMmSs(zDate, p)==0 ){
13444     return 0;
13445   }else if( sqlite3StrICmp(zDate,"now")==0){
13446     setDateTimeToCurrent(context, p);
13447     return 0;
13448   }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
13449     p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
13450     p->validJD = 1;
13451     return 0;
13452   }
13453   return 1;
13454 }
13455
13456 /*
13457 ** Compute the Year, Month, and Day from the julian day number.
13458 */
13459 static void computeYMD(DateTime *p){
13460   int Z, A, B, C, D, E, X1;
13461   if( p->validYMD ) return;
13462   if( !p->validJD ){
13463     p->Y = 2000;
13464     p->M = 1;
13465     p->D = 1;
13466   }else{
13467     Z = (int)((p->iJD + 43200000)/86400000);
13468     A = (int)((Z - 1867216.25)/36524.25);
13469     A = Z + 1 + A - (A/4);
13470     B = A + 1524;
13471     C = (int)((B - 122.1)/365.25);
13472     D = (36525*C)/100;
13473     E = (int)((B-D)/30.6001);
13474     X1 = (int)(30.6001*E);
13475     p->D = B - D - X1;
13476     p->M = E<14 ? E-1 : E-13;
13477     p->Y = p->M>2 ? C - 4716 : C - 4715;
13478   }
13479   p->validYMD = 1;
13480 }
13481
13482 /*
13483 ** Compute the Hour, Minute, and Seconds from the julian day number.
13484 */
13485 static void computeHMS(DateTime *p){
13486   int s;
13487   if( p->validHMS ) return;
13488   computeJD(p);
13489   s = (int)((p->iJD + 43200000) % 86400000);
13490   p->s = s/1000.0;
13491   s = (int)p->s;
13492   p->s -= s;
13493   p->h = s/3600;
13494   s -= p->h*3600;
13495   p->m = s/60;
13496   p->s += s - p->m*60;
13497   p->validHMS = 1;
13498 }
13499
13500 /*
13501 ** Compute both YMD and HMS
13502 */
13503 static void computeYMD_HMS(DateTime *p){
13504   computeYMD(p);
13505   computeHMS(p);
13506 }
13507
13508 /*
13509 ** Clear the YMD and HMS and the TZ
13510 */
13511 static void clearYMD_HMS_TZ(DateTime *p){
13512   p->validYMD = 0;
13513   p->validHMS = 0;
13514   p->validTZ = 0;
13515 }
13516
13517 /*
13518 ** On recent Windows platforms, the localtime_s() function is available
13519 ** as part of the "Secure CRT". It is essentially equivalent to 
13520 ** localtime_r() available under most POSIX platforms, except that the 
13521 ** order of the parameters is reversed.
13522 **
13523 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
13524 **
13525 ** If the user has not indicated to use localtime_r() or localtime_s()
13526 ** already, check for an MSVC build environment that provides 
13527 ** localtime_s().
13528 */
13529 #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
13530      defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
13531 #define HAVE_LOCALTIME_S 1
13532 #endif
13533
13534 #ifndef SQLITE_OMIT_LOCALTIME
13535 /*
13536 ** The following routine implements the rough equivalent of localtime_r()
13537 ** using whatever operating-system specific localtime facility that
13538 ** is available.  This routine returns 0 on success and
13539 ** non-zero on any kind of error.
13540 **
13541 ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
13542 ** routine will always fail.
13543 */
13544 static int osLocaltime(time_t *t, struct tm *pTm){
13545   int rc;
13546 #if (!defined(HAVE_LOCALTIME_R) || !HAVE_LOCALTIME_R) \
13547       && (!defined(HAVE_LOCALTIME_S) || !HAVE_LOCALTIME_S)
13548   struct tm *pX;
13549   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
13550   sqlite3_mutex_enter(mutex);
13551   pX = localtime(t);
13552 #ifndef SQLITE_OMIT_BUILTIN_TEST
13553   if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
13554 #endif
13555   if( pX ) *pTm = *pX;
13556   sqlite3_mutex_leave(mutex);
13557   rc = pX==0;
13558 #else
13559 #ifndef SQLITE_OMIT_BUILTIN_TEST
13560   if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
13561 #endif
13562 #if defined(HAVE_LOCALTIME_R) && HAVE_LOCALTIME_R
13563   rc = localtime_r(t, pTm)==0;
13564 #else
13565   rc = localtime_s(pTm, t);
13566 #endif /* HAVE_LOCALTIME_R */
13567 #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
13568   return rc;
13569 }
13570 #endif /* SQLITE_OMIT_LOCALTIME */
13571
13572
13573 #ifndef SQLITE_OMIT_LOCALTIME
13574 /*
13575 ** Compute the difference (in milliseconds) between localtime and UTC
13576 ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
13577 ** return this value and set *pRc to SQLITE_OK. 
13578 **
13579 ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
13580 ** is undefined in this case.
13581 */
13582 static sqlite3_int64 localtimeOffset(
13583   DateTime *p,                    /* Date at which to calculate offset */
13584   sqlite3_context *pCtx,          /* Write error here if one occurs */
13585   int *pRc                        /* OUT: Error code. SQLITE_OK or ERROR */
13586 ){
13587   DateTime x, y;
13588   time_t t;
13589   struct tm sLocal;
13590
13591   /* Initialize the contents of sLocal to avoid a compiler warning. */
13592   memset(&sLocal, 0, sizeof(sLocal));
13593
13594   x = *p;
13595   computeYMD_HMS(&x);
13596   if( x.Y<1971 || x.Y>=2038 ){
13597     x.Y = 2000;
13598     x.M = 1;
13599     x.D = 1;
13600     x.h = 0;
13601     x.m = 0;
13602     x.s = 0.0;
13603   } else {
13604     int s = (int)(x.s + 0.5);
13605     x.s = s;
13606   }
13607   x.tz = 0;
13608   x.validJD = 0;
13609   computeJD(&x);
13610   t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
13611   if( osLocaltime(&t, &sLocal) ){
13612     sqlite3_result_error(pCtx, "local time unavailable", -1);
13613     *pRc = SQLITE_ERROR;
13614     return 0;
13615   }
13616   y.Y = sLocal.tm_year + 1900;
13617   y.M = sLocal.tm_mon + 1;
13618   y.D = sLocal.tm_mday;
13619   y.h = sLocal.tm_hour;
13620   y.m = sLocal.tm_min;
13621   y.s = sLocal.tm_sec;
13622   y.validYMD = 1;
13623   y.validHMS = 1;
13624   y.validJD = 0;
13625   y.validTZ = 0;
13626   computeJD(&y);
13627   *pRc = SQLITE_OK;
13628   return y.iJD - x.iJD;
13629 }
13630 #endif /* SQLITE_OMIT_LOCALTIME */
13631
13632 /*
13633 ** Process a modifier to a date-time stamp.  The modifiers are
13634 ** as follows:
13635 **
13636 **     NNN days
13637 **     NNN hours
13638 **     NNN minutes
13639 **     NNN.NNNN seconds
13640 **     NNN months
13641 **     NNN years
13642 **     start of month
13643 **     start of year
13644 **     start of week
13645 **     start of day
13646 **     weekday N
13647 **     unixepoch
13648 **     localtime
13649 **     utc
13650 **
13651 ** Return 0 on success and 1 if there is any kind of error. If the error
13652 ** is in a system call (i.e. localtime()), then an error message is written
13653 ** to context pCtx. If the error is an unrecognized modifier, no error is
13654 ** written to pCtx.
13655 */
13656 static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){
13657   int rc = 1;
13658   int n;
13659   double r;
13660   char *z, zBuf[30];
13661   z = zBuf;
13662   for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
13663     z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
13664   }
13665   z[n] = 0;
13666   switch( z[0] ){
13667 #ifndef SQLITE_OMIT_LOCALTIME
13668     case 'l': {
13669       /*    localtime
13670       **
13671       ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
13672       ** show local time.
13673       */
13674       if( strcmp(z, "localtime")==0 ){
13675         computeJD(p);
13676         p->iJD += localtimeOffset(p, pCtx, &rc);
13677         clearYMD_HMS_TZ(p);
13678       }
13679       break;
13680     }
13681 #endif
13682     case 'u': {
13683       /*
13684       **    unixepoch
13685       **
13686       ** Treat the current value of p->iJD as the number of
13687       ** seconds since 1970.  Convert to a real julian day number.
13688       */
13689       if( strcmp(z, "unixepoch")==0 && p->validJD ){
13690         p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
13691         clearYMD_HMS_TZ(p);
13692         rc = 0;
13693       }
13694 #ifndef SQLITE_OMIT_LOCALTIME
13695       else if( strcmp(z, "utc")==0 ){
13696         sqlite3_int64 c1;
13697         computeJD(p);
13698         c1 = localtimeOffset(p, pCtx, &rc);
13699         if( rc==SQLITE_OK ){
13700           p->iJD -= c1;
13701           clearYMD_HMS_TZ(p);
13702           p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
13703         }
13704       }
13705 #endif
13706       break;
13707     }
13708     case 'w': {
13709       /*
13710       **    weekday N
13711       **
13712       ** Move the date to the same time on the next occurrence of
13713       ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
13714       ** date is already on the appropriate weekday, this is a no-op.
13715       */
13716       if( strncmp(z, "weekday ", 8)==0
13717                && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
13718                && (n=(int)r)==r && n>=0 && r<7 ){
13719         sqlite3_int64 Z;
13720         computeYMD_HMS(p);
13721         p->validTZ = 0;
13722         p->validJD = 0;
13723         computeJD(p);
13724         Z = ((p->iJD + 129600000)/86400000) % 7;
13725         if( Z>n ) Z -= 7;
13726         p->iJD += (n - Z)*86400000;
13727         clearYMD_HMS_TZ(p);
13728         rc = 0;
13729       }
13730       break;
13731     }
13732     case 's': {
13733       /*
13734       **    start of TTTTT
13735       **
13736       ** Move the date backwards to the beginning of the current day,
13737       ** or month or year.
13738       */
13739       if( strncmp(z, "start of ", 9)!=0 ) break;
13740       z += 9;
13741       computeYMD(p);
13742       p->validHMS = 1;
13743       p->h = p->m = 0;
13744       p->s = 0.0;
13745       p->validTZ = 0;
13746       p->validJD = 0;
13747       if( strcmp(z,"month")==0 ){
13748         p->D = 1;
13749         rc = 0;
13750       }else if( strcmp(z,"year")==0 ){
13751         computeYMD(p);
13752         p->M = 1;
13753         p->D = 1;
13754         rc = 0;
13755       }else if( strcmp(z,"day")==0 ){
13756         rc = 0;
13757       }
13758       break;
13759     }
13760     case '+':
13761     case '-':
13762     case '0':
13763     case '1':
13764     case '2':
13765     case '3':
13766     case '4':
13767     case '5':
13768     case '6':
13769     case '7':
13770     case '8':
13771     case '9': {
13772       double rRounder;
13773       for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
13774       if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
13775         rc = 1;
13776         break;
13777       }
13778       if( z[n]==':' ){
13779         /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
13780         ** specified number of hours, minutes, seconds, and fractional seconds
13781         ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
13782         ** omitted.
13783         */
13784         const char *z2 = z;
13785         DateTime tx;
13786         sqlite3_int64 day;
13787         if( !sqlite3Isdigit(*z2) ) z2++;
13788         memset(&tx, 0, sizeof(tx));
13789         if( parseHhMmSs(z2, &tx) ) break;
13790         computeJD(&tx);
13791         tx.iJD -= 43200000;
13792         day = tx.iJD/86400000;
13793         tx.iJD -= day*86400000;
13794         if( z[0]=='-' ) tx.iJD = -tx.iJD;
13795         computeJD(p);
13796         clearYMD_HMS_TZ(p);
13797         p->iJD += tx.iJD;
13798         rc = 0;
13799         break;
13800       }
13801       z += n;
13802       while( sqlite3Isspace(*z) ) z++;
13803       n = sqlite3Strlen30(z);
13804       if( n>10 || n<3 ) break;
13805       if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
13806       computeJD(p);
13807       rc = 0;
13808       rRounder = r<0 ? -0.5 : +0.5;
13809       if( n==3 && strcmp(z,"day")==0 ){
13810         p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
13811       }else if( n==4 && strcmp(z,"hour")==0 ){
13812         p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
13813       }else if( n==6 && strcmp(z,"minute")==0 ){
13814         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
13815       }else if( n==6 && strcmp(z,"second")==0 ){
13816         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
13817       }else if( n==5 && strcmp(z,"month")==0 ){
13818         int x, y;
13819         computeYMD_HMS(p);
13820         p->M += (int)r;
13821         x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
13822         p->Y += x;
13823         p->M -= x*12;
13824         p->validJD = 0;
13825         computeJD(p);
13826         y = (int)r;
13827         if( y!=r ){
13828           p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
13829         }
13830       }else if( n==4 && strcmp(z,"year")==0 ){
13831         int y = (int)r;
13832         computeYMD_HMS(p);
13833         p->Y += y;
13834         p->validJD = 0;
13835         computeJD(p);
13836         if( y!=r ){
13837           p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
13838         }
13839       }else{
13840         rc = 1;
13841       }
13842       clearYMD_HMS_TZ(p);
13843       break;
13844     }
13845     default: {
13846       break;
13847     }
13848   }
13849   return rc;
13850 }
13851
13852 /*
13853 ** Process time function arguments.  argv[0] is a date-time stamp.
13854 ** argv[1] and following are modifiers.  Parse them all and write
13855 ** the resulting time into the DateTime structure p.  Return 0
13856 ** on success and 1 if there are any errors.
13857 **
13858 ** If there are zero parameters (if even argv[0] is undefined)
13859 ** then assume a default value of "now" for argv[0].
13860 */
13861 static int isDate(
13862   sqlite3_context *context, 
13863   int argc, 
13864   sqlite3_value **argv, 
13865   DateTime *p
13866 ){
13867   int i;
13868   const unsigned char *z;
13869   int eType;
13870   memset(p, 0, sizeof(*p));
13871   if( argc==0 ){
13872     setDateTimeToCurrent(context, p);
13873   }else if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
13874                    || eType==SQLITE_INTEGER ){
13875     p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
13876     p->validJD = 1;
13877   }else{
13878     z = sqlite3_value_text(argv[0]);
13879     if( !z || parseDateOrTime(context, (char*)z, p) ){
13880       return 1;
13881     }
13882   }
13883   for(i=1; i<argc; i++){
13884     z = sqlite3_value_text(argv[i]);
13885     if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
13886   }
13887   return 0;
13888 }
13889
13890
13891 /*
13892 ** The following routines implement the various date and time functions
13893 ** of SQLite.
13894 */
13895
13896 /*
13897 **    julianday( TIMESTRING, MOD, MOD, ...)
13898 **
13899 ** Return the julian day number of the date specified in the arguments
13900 */
13901 static void juliandayFunc(
13902   sqlite3_context *context,
13903   int argc,
13904   sqlite3_value **argv
13905 ){
13906   DateTime x;
13907   if( isDate(context, argc, argv, &x)==0 ){
13908     computeJD(&x);
13909     sqlite3_result_double(context, x.iJD/86400000.0);
13910   }
13911 }
13912
13913 /*
13914 **    datetime( TIMESTRING, MOD, MOD, ...)
13915 **
13916 ** Return YYYY-MM-DD HH:MM:SS
13917 */
13918 static void datetimeFunc(
13919   sqlite3_context *context,
13920   int argc,
13921   sqlite3_value **argv
13922 ){
13923   DateTime x;
13924   if( isDate(context, argc, argv, &x)==0 ){
13925     char zBuf[100];
13926     computeYMD_HMS(&x);
13927     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
13928                      x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
13929     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
13930   }
13931 }
13932
13933 /*
13934 **    time( TIMESTRING, MOD, MOD, ...)
13935 **
13936 ** Return HH:MM:SS
13937 */
13938 static void timeFunc(
13939   sqlite3_context *context,
13940   int argc,
13941   sqlite3_value **argv
13942 ){
13943   DateTime x;
13944   if( isDate(context, argc, argv, &x)==0 ){
13945     char zBuf[100];
13946     computeHMS(&x);
13947     sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
13948     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
13949   }
13950 }
13951
13952 /*
13953 **    date( TIMESTRING, MOD, MOD, ...)
13954 **
13955 ** Return YYYY-MM-DD
13956 */
13957 static void dateFunc(
13958   sqlite3_context *context,
13959   int argc,
13960   sqlite3_value **argv
13961 ){
13962   DateTime x;
13963   if( isDate(context, argc, argv, &x)==0 ){
13964     char zBuf[100];
13965     computeYMD(&x);
13966     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
13967     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
13968   }
13969 }
13970
13971 /*
13972 **    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
13973 **
13974 ** Return a string described by FORMAT.  Conversions as follows:
13975 **
13976 **   %d  day of month
13977 **   %f  ** fractional seconds  SS.SSS
13978 **   %H  hour 00-24
13979 **   %j  day of year 000-366
13980 **   %J  ** Julian day number
13981 **   %m  month 01-12
13982 **   %M  minute 00-59
13983 **   %s  seconds since 1970-01-01
13984 **   %S  seconds 00-59
13985 **   %w  day of week 0-6  sunday==0
13986 **   %W  week of year 00-53
13987 **   %Y  year 0000-9999
13988 **   %%  %
13989 */
13990 static void strftimeFunc(
13991   sqlite3_context *context,
13992   int argc,
13993   sqlite3_value **argv
13994 ){
13995   DateTime x;
13996   u64 n;
13997   size_t i,j;
13998   char *z;
13999   sqlite3 *db;
14000   const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
14001   char zBuf[100];
14002   if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
14003   db = sqlite3_context_db_handle(context);
14004   for(i=0, n=1; zFmt[i]; i++, n++){
14005     if( zFmt[i]=='%' ){
14006       switch( zFmt[i+1] ){
14007         case 'd':
14008         case 'H':
14009         case 'm':
14010         case 'M':
14011         case 'S':
14012         case 'W':
14013           n++;
14014           /* fall thru */
14015         case 'w':
14016         case '%':
14017           break;
14018         case 'f':
14019           n += 8;
14020           break;
14021         case 'j':
14022           n += 3;
14023           break;
14024         case 'Y':
14025           n += 8;
14026           break;
14027         case 's':
14028         case 'J':
14029           n += 50;
14030           break;
14031         default:
14032           return;  /* ERROR.  return a NULL */
14033       }
14034       i++;
14035     }
14036   }
14037   testcase( n==sizeof(zBuf)-1 );
14038   testcase( n==sizeof(zBuf) );
14039   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
14040   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
14041   if( n<sizeof(zBuf) ){
14042     z = zBuf;
14043   }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
14044     sqlite3_result_error_toobig(context);
14045     return;
14046   }else{
14047     z = sqlite3DbMallocRaw(db, (int)n);
14048     if( z==0 ){
14049       sqlite3_result_error_nomem(context);
14050       return;
14051     }
14052   }
14053   computeJD(&x);
14054   computeYMD_HMS(&x);
14055   for(i=j=0; zFmt[i]; i++){
14056     if( zFmt[i]!='%' ){
14057       z[j++] = zFmt[i];
14058     }else{
14059       i++;
14060       switch( zFmt[i] ){
14061         case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
14062         case 'f': {
14063           double s = x.s;
14064           if( s>59.999 ) s = 59.999;
14065           sqlite3_snprintf(7, &z[j],"%06.3f", s);
14066           j += sqlite3Strlen30(&z[j]);
14067           break;
14068         }
14069         case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
14070         case 'W': /* Fall thru */
14071         case 'j': {
14072           int nDay;             /* Number of days since 1st day of year */
14073           DateTime y = x;
14074           y.validJD = 0;
14075           y.M = 1;
14076           y.D = 1;
14077           computeJD(&y);
14078           nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
14079           if( zFmt[i]=='W' ){
14080             int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
14081             wd = (int)(((x.iJD+43200000)/86400000)%7);
14082             sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
14083             j += 2;
14084           }else{
14085             sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
14086             j += 3;
14087           }
14088           break;
14089         }
14090         case 'J': {
14091           sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
14092           j+=sqlite3Strlen30(&z[j]);
14093           break;
14094         }
14095         case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
14096         case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
14097         case 's': {
14098           sqlite3_snprintf(30,&z[j],"%lld",
14099                            (i64)(x.iJD/1000 - 21086676*(i64)10000));
14100           j += sqlite3Strlen30(&z[j]);
14101           break;
14102         }
14103         case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
14104         case 'w': {
14105           z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
14106           break;
14107         }
14108         case 'Y': {
14109           sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
14110           break;
14111         }
14112         default:   z[j++] = '%'; break;
14113       }
14114     }
14115   }
14116   z[j] = 0;
14117   sqlite3_result_text(context, z, -1,
14118                       z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
14119 }
14120
14121 /*
14122 ** current_time()
14123 **
14124 ** This function returns the same value as time('now').
14125 */
14126 static void ctimeFunc(
14127   sqlite3_context *context,
14128   int NotUsed,
14129   sqlite3_value **NotUsed2
14130 ){
14131   UNUSED_PARAMETER2(NotUsed, NotUsed2);
14132   timeFunc(context, 0, 0);
14133 }
14134
14135 /*
14136 ** current_date()
14137 **
14138 ** This function returns the same value as date('now').
14139 */
14140 static void cdateFunc(
14141   sqlite3_context *context,
14142   int NotUsed,
14143   sqlite3_value **NotUsed2
14144 ){
14145   UNUSED_PARAMETER2(NotUsed, NotUsed2);
14146   dateFunc(context, 0, 0);
14147 }
14148
14149 /*
14150 ** current_timestamp()
14151 **
14152 ** This function returns the same value as datetime('now').
14153 */
14154 static void ctimestampFunc(
14155   sqlite3_context *context,
14156   int NotUsed,
14157   sqlite3_value **NotUsed2
14158 ){
14159   UNUSED_PARAMETER2(NotUsed, NotUsed2);
14160   datetimeFunc(context, 0, 0);
14161 }
14162 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
14163
14164 #ifdef SQLITE_OMIT_DATETIME_FUNCS
14165 /*
14166 ** If the library is compiled to omit the full-scale date and time
14167 ** handling (to get a smaller binary), the following minimal version
14168 ** of the functions current_time(), current_date() and current_timestamp()
14169 ** are included instead. This is to support column declarations that
14170 ** include "DEFAULT CURRENT_TIME" etc.
14171 **
14172 ** This function uses the C-library functions time(), gmtime()
14173 ** and strftime(). The format string to pass to strftime() is supplied
14174 ** as the user-data for the function.
14175 */
14176 static void currentTimeFunc(
14177   sqlite3_context *context,
14178   int argc,
14179   sqlite3_value **argv
14180 ){
14181   time_t t;
14182   char *zFormat = (char *)sqlite3_user_data(context);
14183   sqlite3 *db;
14184   sqlite3_int64 iT;
14185   char zBuf[20];
14186
14187   UNUSED_PARAMETER(argc);
14188   UNUSED_PARAMETER(argv);
14189
14190   db = sqlite3_context_db_handle(context);
14191   sqlite3OsCurrentTimeInt64(db->pVfs, &iT);
14192   t = iT/1000 - 10000*(sqlite3_int64)21086676;
14193 #ifdef HAVE_GMTIME_R
14194   {
14195     struct tm sNow;
14196     gmtime_r(&t, &sNow);
14197     strftime(zBuf, 20, zFormat, &sNow);
14198   }
14199 #else
14200   {
14201     struct tm *pTm;
14202     sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
14203     pTm = gmtime(&t);
14204     strftime(zBuf, 20, zFormat, pTm);
14205     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
14206   }
14207 #endif
14208
14209   sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
14210 }
14211 #endif
14212
14213 /*
14214 ** This function registered all of the above C functions as SQL
14215 ** functions.  This should be the only routine in this file with
14216 ** external linkage.
14217 */
14218 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
14219   static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
14220 #ifndef SQLITE_OMIT_DATETIME_FUNCS
14221     FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
14222     FUNCTION(date,             -1, 0, 0, dateFunc      ),
14223     FUNCTION(time,             -1, 0, 0, timeFunc      ),
14224     FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
14225     FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
14226     FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
14227     FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
14228     FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
14229 #else
14230     STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
14231     STR_FUNCTION(current_date,      0, "%Y-%m-%d",          0, currentTimeFunc),
14232     STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
14233 #endif
14234   };
14235   int i;
14236   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
14237   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
14238
14239   for(i=0; i<ArraySize(aDateTimeFuncs); i++){
14240     sqlite3FuncDefInsert(pHash, &aFunc[i]);
14241   }
14242 }
14243
14244 /************** End of date.c ************************************************/
14245 /************** Begin file os.c **********************************************/
14246 /*
14247 ** 2005 November 29
14248 **
14249 ** The author disclaims copyright to this source code.  In place of
14250 ** a legal notice, here is a blessing:
14251 **
14252 **    May you do good and not evil.
14253 **    May you find forgiveness for yourself and forgive others.
14254 **    May you share freely, never taking more than you give.
14255 **
14256 ******************************************************************************
14257 **
14258 ** This file contains OS interface code that is common to all
14259 ** architectures.
14260 */
14261 #define _SQLITE_OS_C_ 1
14262 #undef _SQLITE_OS_C_
14263
14264 /*
14265 ** The default SQLite sqlite3_vfs implementations do not allocate
14266 ** memory (actually, os_unix.c allocates a small amount of memory
14267 ** from within OsOpen()), but some third-party implementations may.
14268 ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
14269 ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
14270 **
14271 ** The following functions are instrumented for malloc() failure 
14272 ** testing:
14273 **
14274 **     sqlite3OsOpen()
14275 **     sqlite3OsRead()
14276 **     sqlite3OsWrite()
14277 **     sqlite3OsSync()
14278 **     sqlite3OsLock()
14279 **
14280 */
14281 #if defined(SQLITE_TEST)
14282 SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
14283   #define DO_OS_MALLOC_TEST(x)                                       \
14284   if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) {  \
14285     void *pTstAlloc = sqlite3Malloc(10);                             \
14286     if (!pTstAlloc) return SQLITE_IOERR_NOMEM;                       \
14287     sqlite3_free(pTstAlloc);                                         \
14288   }
14289 #else
14290   #define DO_OS_MALLOC_TEST(x)
14291 #endif
14292
14293 /*
14294 ** The following routines are convenience wrappers around methods
14295 ** of the sqlite3_file object.  This is mostly just syntactic sugar. All
14296 ** of this would be completely automatic if SQLite were coded using
14297 ** C++ instead of plain old C.
14298 */
14299 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
14300   int rc = SQLITE_OK;
14301   if( pId->pMethods ){
14302     rc = pId->pMethods->xClose(pId);
14303     pId->pMethods = 0;
14304   }
14305   return rc;
14306 }
14307 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
14308   DO_OS_MALLOC_TEST(id);
14309   return id->pMethods->xRead(id, pBuf, amt, offset);
14310 }
14311 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
14312   DO_OS_MALLOC_TEST(id);
14313   return id->pMethods->xWrite(id, pBuf, amt, offset);
14314 }
14315 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
14316   return id->pMethods->xTruncate(id, size);
14317 }
14318 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
14319   DO_OS_MALLOC_TEST(id);
14320   return id->pMethods->xSync(id, flags);
14321 }
14322 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
14323   DO_OS_MALLOC_TEST(id);
14324   return id->pMethods->xFileSize(id, pSize);
14325 }
14326 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
14327   DO_OS_MALLOC_TEST(id);
14328   return id->pMethods->xLock(id, lockType);
14329 }
14330 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
14331   return id->pMethods->xUnlock(id, lockType);
14332 }
14333 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
14334   DO_OS_MALLOC_TEST(id);
14335   return id->pMethods->xCheckReservedLock(id, pResOut);
14336 }
14337 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
14338   return id->pMethods->xFileControl(id, op, pArg);
14339 }
14340 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
14341   int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
14342   return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
14343 }
14344 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
14345   return id->pMethods->xDeviceCharacteristics(id);
14346 }
14347 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
14348   return id->pMethods->xShmLock(id, offset, n, flags);
14349 }
14350 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
14351   id->pMethods->xShmBarrier(id);
14352 }
14353 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
14354   return id->pMethods->xShmUnmap(id, deleteFlag);
14355 }
14356 SQLITE_PRIVATE int sqlite3OsShmMap(
14357   sqlite3_file *id,               /* Database file handle */
14358   int iPage,
14359   int pgsz,
14360   int bExtend,                    /* True to extend file if necessary */
14361   void volatile **pp              /* OUT: Pointer to mapping */
14362 ){
14363   return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
14364 }
14365
14366 /*
14367 ** The next group of routines are convenience wrappers around the
14368 ** VFS methods.
14369 */
14370 SQLITE_PRIVATE int sqlite3OsOpen(
14371   sqlite3_vfs *pVfs, 
14372   const char *zPath, 
14373   sqlite3_file *pFile, 
14374   int flags, 
14375   int *pFlagsOut
14376 ){
14377   int rc;
14378   DO_OS_MALLOC_TEST(0);
14379   /* 0x87f3f is a mask of SQLITE_OPEN_ flags that are valid to be passed
14380   ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
14381   ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
14382   ** reaching the VFS. */
14383   rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f3f, pFlagsOut);
14384   assert( rc==SQLITE_OK || pFile->pMethods==0 );
14385   return rc;
14386 }
14387 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
14388   return pVfs->xDelete(pVfs, zPath, dirSync);
14389 }
14390 SQLITE_PRIVATE int sqlite3OsAccess(
14391   sqlite3_vfs *pVfs, 
14392   const char *zPath, 
14393   int flags, 
14394   int *pResOut
14395 ){
14396   DO_OS_MALLOC_TEST(0);
14397   return pVfs->xAccess(pVfs, zPath, flags, pResOut);
14398 }
14399 SQLITE_PRIVATE int sqlite3OsFullPathname(
14400   sqlite3_vfs *pVfs, 
14401   const char *zPath, 
14402   int nPathOut, 
14403   char *zPathOut
14404 ){
14405   zPathOut[0] = 0;
14406   return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
14407 }
14408 #ifndef SQLITE_OMIT_LOAD_EXTENSION
14409 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
14410   return pVfs->xDlOpen(pVfs, zPath);
14411 }
14412 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
14413   pVfs->xDlError(pVfs, nByte, zBufOut);
14414 }
14415 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
14416   return pVfs->xDlSym(pVfs, pHdle, zSym);
14417 }
14418 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
14419   pVfs->xDlClose(pVfs, pHandle);
14420 }
14421 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
14422 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
14423   return pVfs->xRandomness(pVfs, nByte, zBufOut);
14424 }
14425 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
14426   return pVfs->xSleep(pVfs, nMicro);
14427 }
14428 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
14429   int rc;
14430   /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
14431   ** method to get the current date and time if that method is available
14432   ** (if iVersion is 2 or greater and the function pointer is not NULL) and
14433   ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
14434   ** unavailable.
14435   */
14436   if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
14437     rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
14438   }else{
14439     double r;
14440     rc = pVfs->xCurrentTime(pVfs, &r);
14441     *pTimeOut = (sqlite3_int64)(r*86400000.0);
14442   }
14443   return rc;
14444 }
14445
14446 SQLITE_PRIVATE int sqlite3OsOpenMalloc(
14447   sqlite3_vfs *pVfs, 
14448   const char *zFile, 
14449   sqlite3_file **ppFile, 
14450   int flags,
14451   int *pOutFlags
14452 ){
14453   int rc = SQLITE_NOMEM;
14454   sqlite3_file *pFile;
14455   pFile = (sqlite3_file *)sqlite3Malloc(pVfs->szOsFile);
14456   if( pFile ){
14457     rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
14458     if( rc!=SQLITE_OK ){
14459       sqlite3_free(pFile);
14460     }else{
14461       *ppFile = pFile;
14462     }
14463   }
14464   return rc;
14465 }
14466 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
14467   int rc = SQLITE_OK;
14468   assert( pFile );
14469   rc = sqlite3OsClose(pFile);
14470   sqlite3_free(pFile);
14471   return rc;
14472 }
14473
14474 /*
14475 ** This function is a wrapper around the OS specific implementation of
14476 ** sqlite3_os_init(). The purpose of the wrapper is to provide the
14477 ** ability to simulate a malloc failure, so that the handling of an
14478 ** error in sqlite3_os_init() by the upper layers can be tested.
14479 */
14480 SQLITE_PRIVATE int sqlite3OsInit(void){
14481   void *p = sqlite3_malloc(10);
14482   if( p==0 ) return SQLITE_NOMEM;
14483   sqlite3_free(p);
14484   return sqlite3_os_init();
14485 }
14486
14487 /*
14488 ** The list of all registered VFS implementations.
14489 */
14490 static sqlite3_vfs * SQLITE_WSD vfsList = 0;
14491 #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
14492
14493 /*
14494 ** Locate a VFS by name.  If no name is given, simply return the
14495 ** first VFS on the list.
14496 */
14497 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
14498   sqlite3_vfs *pVfs = 0;
14499 #if SQLITE_THREADSAFE
14500   sqlite3_mutex *mutex;
14501 #endif
14502 #ifndef SQLITE_OMIT_AUTOINIT
14503   int rc = sqlite3_initialize();
14504   if( rc ) return 0;
14505 #endif
14506 #if SQLITE_THREADSAFE
14507   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
14508 #endif
14509   sqlite3_mutex_enter(mutex);
14510   for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
14511     if( zVfs==0 ) break;
14512     if( strcmp(zVfs, pVfs->zName)==0 ) break;
14513   }
14514   sqlite3_mutex_leave(mutex);
14515   return pVfs;
14516 }
14517
14518 /*
14519 ** Unlink a VFS from the linked list
14520 */
14521 static void vfsUnlink(sqlite3_vfs *pVfs){
14522   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
14523   if( pVfs==0 ){
14524     /* No-op */
14525   }else if( vfsList==pVfs ){
14526     vfsList = pVfs->pNext;
14527   }else if( vfsList ){
14528     sqlite3_vfs *p = vfsList;
14529     while( p->pNext && p->pNext!=pVfs ){
14530       p = p->pNext;
14531     }
14532     if( p->pNext==pVfs ){
14533       p->pNext = pVfs->pNext;
14534     }
14535   }
14536 }
14537
14538 /*
14539 ** Register a VFS with the system.  It is harmless to register the same
14540 ** VFS multiple times.  The new VFS becomes the default if makeDflt is
14541 ** true.
14542 */
14543 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
14544   sqlite3_mutex *mutex = 0;
14545 #ifndef SQLITE_OMIT_AUTOINIT
14546   int rc = sqlite3_initialize();
14547   if( rc ) return rc;
14548 #endif
14549   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
14550   sqlite3_mutex_enter(mutex);
14551   vfsUnlink(pVfs);
14552   if( makeDflt || vfsList==0 ){
14553     pVfs->pNext = vfsList;
14554     vfsList = pVfs;
14555   }else{
14556     pVfs->pNext = vfsList->pNext;
14557     vfsList->pNext = pVfs;
14558   }
14559   assert(vfsList);
14560   sqlite3_mutex_leave(mutex);
14561   return SQLITE_OK;
14562 }
14563
14564 /*
14565 ** Unregister a VFS so that it is no longer accessible.
14566 */
14567 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
14568 #if SQLITE_THREADSAFE
14569   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
14570 #endif
14571   sqlite3_mutex_enter(mutex);
14572   vfsUnlink(pVfs);
14573   sqlite3_mutex_leave(mutex);
14574   return SQLITE_OK;
14575 }
14576
14577 /************** End of os.c **************************************************/
14578 /************** Begin file fault.c *******************************************/
14579 /*
14580 ** 2008 Jan 22
14581 **
14582 ** The author disclaims copyright to this source code.  In place of
14583 ** a legal notice, here is a blessing:
14584 **
14585 **    May you do good and not evil.
14586 **    May you find forgiveness for yourself and forgive others.
14587 **    May you share freely, never taking more than you give.
14588 **
14589 *************************************************************************
14590 **
14591 ** This file contains code to support the concept of "benign" 
14592 ** malloc failures (when the xMalloc() or xRealloc() method of the
14593 ** sqlite3_mem_methods structure fails to allocate a block of memory
14594 ** and returns 0). 
14595 **
14596 ** Most malloc failures are non-benign. After they occur, SQLite
14597 ** abandons the current operation and returns an error code (usually
14598 ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
14599 ** fatal. For example, if a malloc fails while resizing a hash table, this 
14600 ** is completely recoverable simply by not carrying out the resize. The 
14601 ** hash table will continue to function normally.  So a malloc failure 
14602 ** during a hash table resize is a benign fault.
14603 */
14604
14605
14606 #ifndef SQLITE_OMIT_BUILTIN_TEST
14607
14608 /*
14609 ** Global variables.
14610 */
14611 typedef struct BenignMallocHooks BenignMallocHooks;
14612 static SQLITE_WSD struct BenignMallocHooks {
14613   void (*xBenignBegin)(void);
14614   void (*xBenignEnd)(void);
14615 } sqlite3Hooks = { 0, 0 };
14616
14617 /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
14618 ** structure.  If writable static data is unsupported on the target,
14619 ** we have to locate the state vector at run-time.  In the more common
14620 ** case where writable static data is supported, wsdHooks can refer directly
14621 ** to the "sqlite3Hooks" state vector declared above.
14622 */
14623 #ifdef SQLITE_OMIT_WSD
14624 # define wsdHooksInit \
14625   BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
14626 # define wsdHooks x[0]
14627 #else
14628 # define wsdHooksInit
14629 # define wsdHooks sqlite3Hooks
14630 #endif
14631
14632
14633 /*
14634 ** Register hooks to call when sqlite3BeginBenignMalloc() and
14635 ** sqlite3EndBenignMalloc() are called, respectively.
14636 */
14637 SQLITE_PRIVATE void sqlite3BenignMallocHooks(
14638   void (*xBenignBegin)(void),
14639   void (*xBenignEnd)(void)
14640 ){
14641   wsdHooksInit;
14642   wsdHooks.xBenignBegin = xBenignBegin;
14643   wsdHooks.xBenignEnd = xBenignEnd;
14644 }
14645
14646 /*
14647 ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
14648 ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
14649 ** indicates that subsequent malloc failures are non-benign.
14650 */
14651 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
14652   wsdHooksInit;
14653   if( wsdHooks.xBenignBegin ){
14654     wsdHooks.xBenignBegin();
14655   }
14656 }
14657 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
14658   wsdHooksInit;
14659   if( wsdHooks.xBenignEnd ){
14660     wsdHooks.xBenignEnd();
14661   }
14662 }
14663
14664 #endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
14665
14666 /************** End of fault.c ***********************************************/
14667 /************** Begin file mem0.c ********************************************/
14668 /*
14669 ** 2008 October 28
14670 **
14671 ** The author disclaims copyright to this source code.  In place of
14672 ** a legal notice, here is a blessing:
14673 **
14674 **    May you do good and not evil.
14675 **    May you find forgiveness for yourself and forgive others.
14676 **    May you share freely, never taking more than you give.
14677 **
14678 *************************************************************************
14679 **
14680 ** This file contains a no-op memory allocation drivers for use when
14681 ** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
14682 ** here always fail.  SQLite will not operate with these drivers.  These
14683 ** are merely placeholders.  Real drivers must be substituted using
14684 ** sqlite3_config() before SQLite will operate.
14685 */
14686
14687 /*
14688 ** This version of the memory allocator is the default.  It is
14689 ** used when no other memory allocator is specified using compile-time
14690 ** macros.
14691 */
14692 #ifdef SQLITE_ZERO_MALLOC
14693
14694 /*
14695 ** No-op versions of all memory allocation routines
14696 */
14697 static void *sqlite3MemMalloc(int nByte){ return 0; }
14698 static void sqlite3MemFree(void *pPrior){ return; }
14699 static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
14700 static int sqlite3MemSize(void *pPrior){ return 0; }
14701 static int sqlite3MemRoundup(int n){ return n; }
14702 static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
14703 static void sqlite3MemShutdown(void *NotUsed){ return; }
14704
14705 /*
14706 ** This routine is the only routine in this file with external linkage.
14707 **
14708 ** Populate the low-level memory allocation function pointers in
14709 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
14710 */
14711 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
14712   static const sqlite3_mem_methods defaultMethods = {
14713      sqlite3MemMalloc,
14714      sqlite3MemFree,
14715      sqlite3MemRealloc,
14716      sqlite3MemSize,
14717      sqlite3MemRoundup,
14718      sqlite3MemInit,
14719      sqlite3MemShutdown,
14720      0
14721   };
14722   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
14723 }
14724
14725 #endif /* SQLITE_ZERO_MALLOC */
14726
14727 /************** End of mem0.c ************************************************/
14728 /************** Begin file mem1.c ********************************************/
14729 /*
14730 ** 2007 August 14
14731 **
14732 ** The author disclaims copyright to this source code.  In place of
14733 ** a legal notice, here is a blessing:
14734 **
14735 **    May you do good and not evil.
14736 **    May you find forgiveness for yourself and forgive others.
14737 **    May you share freely, never taking more than you give.
14738 **
14739 *************************************************************************
14740 **
14741 ** This file contains low-level memory allocation drivers for when
14742 ** SQLite will use the standard C-library malloc/realloc/free interface
14743 ** to obtain the memory it needs.
14744 **
14745 ** This file contains implementations of the low-level memory allocation
14746 ** routines specified in the sqlite3_mem_methods object.
14747 */
14748
14749 /*
14750 ** This version of the memory allocator is the default.  It is
14751 ** used when no other memory allocator is specified using compile-time
14752 ** macros.
14753 */
14754 #ifdef SQLITE_SYSTEM_MALLOC
14755
14756 /*
14757 ** Like malloc(), but remember the size of the allocation
14758 ** so that we can find it later using sqlite3MemSize().
14759 **
14760 ** For this low-level routine, we are guaranteed that nByte>0 because
14761 ** cases of nByte<=0 will be intercepted and dealt with by higher level
14762 ** routines.
14763 */
14764 static void *sqlite3MemMalloc(int nByte){
14765   sqlite3_int64 *p;
14766   assert( nByte>0 );
14767   nByte = ROUND8(nByte);
14768   p = malloc( nByte+8 );
14769   if( p ){
14770     p[0] = nByte;
14771     p++;
14772   }else{
14773     testcase( sqlite3GlobalConfig.xLog!=0 );
14774     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
14775   }
14776   return (void *)p;
14777 }
14778
14779 /*
14780 ** Like free() but works for allocations obtained from sqlite3MemMalloc()
14781 ** or sqlite3MemRealloc().
14782 **
14783 ** For this low-level routine, we already know that pPrior!=0 since
14784 ** cases where pPrior==0 will have been intecepted and dealt with
14785 ** by higher-level routines.
14786 */
14787 static void sqlite3MemFree(void *pPrior){
14788   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
14789   assert( pPrior!=0 );
14790   p--;
14791   free(p);
14792 }
14793
14794 /*
14795 ** Report the allocated size of a prior return from xMalloc()
14796 ** or xRealloc().
14797 */
14798 static int sqlite3MemSize(void *pPrior){
14799   sqlite3_int64 *p;
14800   if( pPrior==0 ) return 0;
14801   p = (sqlite3_int64*)pPrior;
14802   p--;
14803   return (int)p[0];
14804 }
14805
14806 /*
14807 ** Like realloc().  Resize an allocation previously obtained from
14808 ** sqlite3MemMalloc().
14809 **
14810 ** For this low-level interface, we know that pPrior!=0.  Cases where
14811 ** pPrior==0 while have been intercepted by higher-level routine and
14812 ** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
14813 ** cases where nByte<=0 will have been intercepted by higher-level
14814 ** routines and redirected to xFree.
14815 */
14816 static void *sqlite3MemRealloc(void *pPrior, int nByte){
14817   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
14818   assert( pPrior!=0 && nByte>0 );
14819   assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
14820   p--;
14821   p = realloc(p, nByte+8 );
14822   if( p ){
14823     p[0] = nByte;
14824     p++;
14825   }else{
14826     testcase( sqlite3GlobalConfig.xLog!=0 );
14827     sqlite3_log(SQLITE_NOMEM,
14828       "failed memory resize %u to %u bytes",
14829       sqlite3MemSize(pPrior), nByte);
14830   }
14831   return (void*)p;
14832 }
14833
14834 /*
14835 ** Round up a request size to the next valid allocation size.
14836 */
14837 static int sqlite3MemRoundup(int n){
14838   return ROUND8(n);
14839 }
14840
14841 /*
14842 ** Initialize this module.
14843 */
14844 static int sqlite3MemInit(void *NotUsed){
14845   UNUSED_PARAMETER(NotUsed);
14846   return SQLITE_OK;
14847 }
14848
14849 /*
14850 ** Deinitialize this module.
14851 */
14852 static void sqlite3MemShutdown(void *NotUsed){
14853   UNUSED_PARAMETER(NotUsed);
14854   return;
14855 }
14856
14857 /*
14858 ** This routine is the only routine in this file with external linkage.
14859 **
14860 ** Populate the low-level memory allocation function pointers in
14861 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
14862 */
14863 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
14864   static const sqlite3_mem_methods defaultMethods = {
14865      sqlite3MemMalloc,
14866      sqlite3MemFree,
14867      sqlite3MemRealloc,
14868      sqlite3MemSize,
14869      sqlite3MemRoundup,
14870      sqlite3MemInit,
14871      sqlite3MemShutdown,
14872      0
14873   };
14874   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
14875 }
14876
14877 #endif /* SQLITE_SYSTEM_MALLOC */
14878
14879 /************** End of mem1.c ************************************************/
14880 /************** Begin file mem2.c ********************************************/
14881 /*
14882 ** 2007 August 15
14883 **
14884 ** The author disclaims copyright to this source code.  In place of
14885 ** a legal notice, here is a blessing:
14886 **
14887 **    May you do good and not evil.
14888 **    May you find forgiveness for yourself and forgive others.
14889 **    May you share freely, never taking more than you give.
14890 **
14891 *************************************************************************
14892 **
14893 ** This file contains low-level memory allocation drivers for when
14894 ** SQLite will use the standard C-library malloc/realloc/free interface
14895 ** to obtain the memory it needs while adding lots of additional debugging
14896 ** information to each allocation in order to help detect and fix memory
14897 ** leaks and memory usage errors.
14898 **
14899 ** This file contains implementations of the low-level memory allocation
14900 ** routines specified in the sqlite3_mem_methods object.
14901 */
14902
14903 /*
14904 ** This version of the memory allocator is used only if the
14905 ** SQLITE_MEMDEBUG macro is defined
14906 */
14907 #ifdef SQLITE_MEMDEBUG
14908
14909 /*
14910 ** The backtrace functionality is only available with GLIBC
14911 */
14912 #ifdef __GLIBC__
14913   extern int backtrace(void**,int);
14914   extern void backtrace_symbols_fd(void*const*,int,int);
14915 #else
14916 # define backtrace(A,B) 1
14917 # define backtrace_symbols_fd(A,B,C)
14918 #endif
14919
14920 /*
14921 ** Each memory allocation looks like this:
14922 **
14923 **  ------------------------------------------------------------------------
14924 **  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
14925 **  ------------------------------------------------------------------------
14926 **
14927 ** The application code sees only a pointer to the allocation.  We have
14928 ** to back up from the allocation pointer to find the MemBlockHdr.  The
14929 ** MemBlockHdr tells us the size of the allocation and the number of
14930 ** backtrace pointers.  There is also a guard word at the end of the
14931 ** MemBlockHdr.
14932 */
14933 struct MemBlockHdr {
14934   i64 iSize;                          /* Size of this allocation */
14935   struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
14936   char nBacktrace;                    /* Number of backtraces on this alloc */
14937   char nBacktraceSlots;               /* Available backtrace slots */
14938   u8 nTitle;                          /* Bytes of title; includes '\0' */
14939   u8 eType;                           /* Allocation type code */
14940   int iForeGuard;                     /* Guard word for sanity */
14941 };
14942
14943 /*
14944 ** Guard words
14945 */
14946 #define FOREGUARD 0x80F5E153
14947 #define REARGUARD 0xE4676B53
14948
14949 /*
14950 ** Number of malloc size increments to track.
14951 */
14952 #define NCSIZE  1000
14953
14954 /*
14955 ** All of the static variables used by this module are collected
14956 ** into a single structure named "mem".  This is to keep the
14957 ** static variables organized and to reduce namespace pollution
14958 ** when this module is combined with other in the amalgamation.
14959 */
14960 static struct {
14961   
14962   /*
14963   ** Mutex to control access to the memory allocation subsystem.
14964   */
14965   sqlite3_mutex *mutex;
14966
14967   /*
14968   ** Head and tail of a linked list of all outstanding allocations
14969   */
14970   struct MemBlockHdr *pFirst;
14971   struct MemBlockHdr *pLast;
14972   
14973   /*
14974   ** The number of levels of backtrace to save in new allocations.
14975   */
14976   int nBacktrace;
14977   void (*xBacktrace)(int, int, void **);
14978
14979   /*
14980   ** Title text to insert in front of each block
14981   */
14982   int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
14983   char zTitle[100];  /* The title text */
14984
14985   /* 
14986   ** sqlite3MallocDisallow() increments the following counter.
14987   ** sqlite3MallocAllow() decrements it.
14988   */
14989   int disallow; /* Do not allow memory allocation */
14990
14991   /*
14992   ** Gather statistics on the sizes of memory allocations.
14993   ** nAlloc[i] is the number of allocation attempts of i*8
14994   ** bytes.  i==NCSIZE is the number of allocation attempts for
14995   ** sizes more than NCSIZE*8 bytes.
14996   */
14997   int nAlloc[NCSIZE];      /* Total number of allocations */
14998   int nCurrent[NCSIZE];    /* Current number of allocations */
14999   int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
15000
15001 } mem;
15002
15003
15004 /*
15005 ** Adjust memory usage statistics
15006 */
15007 static void adjustStats(int iSize, int increment){
15008   int i = ROUND8(iSize)/8;
15009   if( i>NCSIZE-1 ){
15010     i = NCSIZE - 1;
15011   }
15012   if( increment>0 ){
15013     mem.nAlloc[i]++;
15014     mem.nCurrent[i]++;
15015     if( mem.nCurrent[i]>mem.mxCurrent[i] ){
15016       mem.mxCurrent[i] = mem.nCurrent[i];
15017     }
15018   }else{
15019     mem.nCurrent[i]--;
15020     assert( mem.nCurrent[i]>=0 );
15021   }
15022 }
15023
15024 /*
15025 ** Given an allocation, find the MemBlockHdr for that allocation.
15026 **
15027 ** This routine checks the guards at either end of the allocation and
15028 ** if they are incorrect it asserts.
15029 */
15030 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
15031   struct MemBlockHdr *p;
15032   int *pInt;
15033   u8 *pU8;
15034   int nReserve;
15035
15036   p = (struct MemBlockHdr*)pAllocation;
15037   p--;
15038   assert( p->iForeGuard==(int)FOREGUARD );
15039   nReserve = ROUND8(p->iSize);
15040   pInt = (int*)pAllocation;
15041   pU8 = (u8*)pAllocation;
15042   assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
15043   /* This checks any of the "extra" bytes allocated due
15044   ** to rounding up to an 8 byte boundary to ensure 
15045   ** they haven't been overwritten.
15046   */
15047   while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
15048   return p;
15049 }
15050
15051 /*
15052 ** Return the number of bytes currently allocated at address p.
15053 */
15054 static int sqlite3MemSize(void *p){
15055   struct MemBlockHdr *pHdr;
15056   if( !p ){
15057     return 0;
15058   }
15059   pHdr = sqlite3MemsysGetHeader(p);
15060   return pHdr->iSize;
15061 }
15062
15063 /*
15064 ** Initialize the memory allocation subsystem.
15065 */
15066 static int sqlite3MemInit(void *NotUsed){
15067   UNUSED_PARAMETER(NotUsed);
15068   assert( (sizeof(struct MemBlockHdr)&7) == 0 );
15069   if( !sqlite3GlobalConfig.bMemstat ){
15070     /* If memory status is enabled, then the malloc.c wrapper will already
15071     ** hold the STATIC_MEM mutex when the routines here are invoked. */
15072     mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
15073   }
15074   return SQLITE_OK;
15075 }
15076
15077 /*
15078 ** Deinitialize the memory allocation subsystem.
15079 */
15080 static void sqlite3MemShutdown(void *NotUsed){
15081   UNUSED_PARAMETER(NotUsed);
15082   mem.mutex = 0;
15083 }
15084
15085 /*
15086 ** Round up a request size to the next valid allocation size.
15087 */
15088 static int sqlite3MemRoundup(int n){
15089   return ROUND8(n);
15090 }
15091
15092 /*
15093 ** Fill a buffer with pseudo-random bytes.  This is used to preset
15094 ** the content of a new memory allocation to unpredictable values and
15095 ** to clear the content of a freed allocation to unpredictable values.
15096 */
15097 static void randomFill(char *pBuf, int nByte){
15098   unsigned int x, y, r;
15099   x = SQLITE_PTR_TO_INT(pBuf);
15100   y = nByte | 1;
15101   while( nByte >= 4 ){
15102     x = (x>>1) ^ (-(x&1) & 0xd0000001);
15103     y = y*1103515245 + 12345;
15104     r = x ^ y;
15105     *(int*)pBuf = r;
15106     pBuf += 4;
15107     nByte -= 4;
15108   }
15109   while( nByte-- > 0 ){
15110     x = (x>>1) ^ (-(x&1) & 0xd0000001);
15111     y = y*1103515245 + 12345;
15112     r = x ^ y;
15113     *(pBuf++) = r & 0xff;
15114   }
15115 }
15116
15117 /*
15118 ** Allocate nByte bytes of memory.
15119 */
15120 static void *sqlite3MemMalloc(int nByte){
15121   struct MemBlockHdr *pHdr;
15122   void **pBt;
15123   char *z;
15124   int *pInt;
15125   void *p = 0;
15126   int totalSize;
15127   int nReserve;
15128   sqlite3_mutex_enter(mem.mutex);
15129   assert( mem.disallow==0 );
15130   nReserve = ROUND8(nByte);
15131   totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
15132                mem.nBacktrace*sizeof(void*) + mem.nTitle;
15133   p = malloc(totalSize);
15134   if( p ){
15135     z = p;
15136     pBt = (void**)&z[mem.nTitle];
15137     pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
15138     pHdr->pNext = 0;
15139     pHdr->pPrev = mem.pLast;
15140     if( mem.pLast ){
15141       mem.pLast->pNext = pHdr;
15142     }else{
15143       mem.pFirst = pHdr;
15144     }
15145     mem.pLast = pHdr;
15146     pHdr->iForeGuard = FOREGUARD;
15147     pHdr->eType = MEMTYPE_HEAP;
15148     pHdr->nBacktraceSlots = mem.nBacktrace;
15149     pHdr->nTitle = mem.nTitle;
15150     if( mem.nBacktrace ){
15151       void *aAddr[40];
15152       pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
15153       memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
15154       assert(pBt[0]);
15155       if( mem.xBacktrace ){
15156         mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
15157       }
15158     }else{
15159       pHdr->nBacktrace = 0;
15160     }
15161     if( mem.nTitle ){
15162       memcpy(z, mem.zTitle, mem.nTitle);
15163     }
15164     pHdr->iSize = nByte;
15165     adjustStats(nByte, +1);
15166     pInt = (int*)&pHdr[1];
15167     pInt[nReserve/sizeof(int)] = REARGUARD;
15168     randomFill((char*)pInt, nByte);
15169     memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
15170     p = (void*)pInt;
15171   }
15172   sqlite3_mutex_leave(mem.mutex);
15173   return p; 
15174 }
15175
15176 /*
15177 ** Free memory.
15178 */
15179 static void sqlite3MemFree(void *pPrior){
15180   struct MemBlockHdr *pHdr;
15181   void **pBt;
15182   char *z;
15183   assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0 
15184        || mem.mutex!=0 );
15185   pHdr = sqlite3MemsysGetHeader(pPrior);
15186   pBt = (void**)pHdr;
15187   pBt -= pHdr->nBacktraceSlots;
15188   sqlite3_mutex_enter(mem.mutex);
15189   if( pHdr->pPrev ){
15190     assert( pHdr->pPrev->pNext==pHdr );
15191     pHdr->pPrev->pNext = pHdr->pNext;
15192   }else{
15193     assert( mem.pFirst==pHdr );
15194     mem.pFirst = pHdr->pNext;
15195   }
15196   if( pHdr->pNext ){
15197     assert( pHdr->pNext->pPrev==pHdr );
15198     pHdr->pNext->pPrev = pHdr->pPrev;
15199   }else{
15200     assert( mem.pLast==pHdr );
15201     mem.pLast = pHdr->pPrev;
15202   }
15203   z = (char*)pBt;
15204   z -= pHdr->nTitle;
15205   adjustStats(pHdr->iSize, -1);
15206   randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
15207                 pHdr->iSize + sizeof(int) + pHdr->nTitle);
15208   free(z);
15209   sqlite3_mutex_leave(mem.mutex);  
15210 }
15211
15212 /*
15213 ** Change the size of an existing memory allocation.
15214 **
15215 ** For this debugging implementation, we *always* make a copy of the
15216 ** allocation into a new place in memory.  In this way, if the 
15217 ** higher level code is using pointer to the old allocation, it is 
15218 ** much more likely to break and we are much more liking to find
15219 ** the error.
15220 */
15221 static void *sqlite3MemRealloc(void *pPrior, int nByte){
15222   struct MemBlockHdr *pOldHdr;
15223   void *pNew;
15224   assert( mem.disallow==0 );
15225   assert( (nByte & 7)==0 );     /* EV: R-46199-30249 */
15226   pOldHdr = sqlite3MemsysGetHeader(pPrior);
15227   pNew = sqlite3MemMalloc(nByte);
15228   if( pNew ){
15229     memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
15230     if( nByte>pOldHdr->iSize ){
15231       randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - pOldHdr->iSize);
15232     }
15233     sqlite3MemFree(pPrior);
15234   }
15235   return pNew;
15236 }
15237
15238 /*
15239 ** Populate the low-level memory allocation function pointers in
15240 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
15241 */
15242 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
15243   static const sqlite3_mem_methods defaultMethods = {
15244      sqlite3MemMalloc,
15245      sqlite3MemFree,
15246      sqlite3MemRealloc,
15247      sqlite3MemSize,
15248      sqlite3MemRoundup,
15249      sqlite3MemInit,
15250      sqlite3MemShutdown,
15251      0
15252   };
15253   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
15254 }
15255
15256 /*
15257 ** Set the "type" of an allocation.
15258 */
15259 SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
15260   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
15261     struct MemBlockHdr *pHdr;
15262     pHdr = sqlite3MemsysGetHeader(p);
15263     assert( pHdr->iForeGuard==FOREGUARD );
15264     pHdr->eType = eType;
15265   }
15266 }
15267
15268 /*
15269 ** Return TRUE if the mask of type in eType matches the type of the
15270 ** allocation p.  Also return true if p==NULL.
15271 **
15272 ** This routine is designed for use within an assert() statement, to
15273 ** verify the type of an allocation.  For example:
15274 **
15275 **     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
15276 */
15277 SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
15278   int rc = 1;
15279   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
15280     struct MemBlockHdr *pHdr;
15281     pHdr = sqlite3MemsysGetHeader(p);
15282     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
15283     if( (pHdr->eType&eType)==0 ){
15284       rc = 0;
15285     }
15286   }
15287   return rc;
15288 }
15289
15290 /*
15291 ** Return TRUE if the mask of type in eType matches no bits of the type of the
15292 ** allocation p.  Also return true if p==NULL.
15293 **
15294 ** This routine is designed for use within an assert() statement, to
15295 ** verify the type of an allocation.  For example:
15296 **
15297 **     assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
15298 */
15299 SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
15300   int rc = 1;
15301   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
15302     struct MemBlockHdr *pHdr;
15303     pHdr = sqlite3MemsysGetHeader(p);
15304     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
15305     if( (pHdr->eType&eType)!=0 ){
15306       rc = 0;
15307     }
15308   }
15309   return rc;
15310 }
15311
15312 /*
15313 ** Set the number of backtrace levels kept for each allocation.
15314 ** A value of zero turns off backtracing.  The number is always rounded
15315 ** up to a multiple of 2.
15316 */
15317 SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
15318   if( depth<0 ){ depth = 0; }
15319   if( depth>20 ){ depth = 20; }
15320   depth = (depth+1)&0xfe;
15321   mem.nBacktrace = depth;
15322 }
15323
15324 SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
15325   mem.xBacktrace = xBacktrace;
15326 }
15327
15328 /*
15329 ** Set the title string for subsequent allocations.
15330 */
15331 SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
15332   unsigned int n = sqlite3Strlen30(zTitle) + 1;
15333   sqlite3_mutex_enter(mem.mutex);
15334   if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
15335   memcpy(mem.zTitle, zTitle, n);
15336   mem.zTitle[n] = 0;
15337   mem.nTitle = ROUND8(n);
15338   sqlite3_mutex_leave(mem.mutex);
15339 }
15340
15341 SQLITE_PRIVATE void sqlite3MemdebugSync(){
15342   struct MemBlockHdr *pHdr;
15343   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
15344     void **pBt = (void**)pHdr;
15345     pBt -= pHdr->nBacktraceSlots;
15346     mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
15347   }
15348 }
15349
15350 /*
15351 ** Open the file indicated and write a log of all unfreed memory 
15352 ** allocations into that log.
15353 */
15354 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
15355   FILE *out;
15356   struct MemBlockHdr *pHdr;
15357   void **pBt;
15358   int i;
15359   out = fopen(zFilename, "w");
15360   if( out==0 ){
15361     fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
15362                     zFilename);
15363     return;
15364   }
15365   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
15366     char *z = (char*)pHdr;
15367     z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
15368     fprintf(out, "**** %lld bytes at %p from %s ****\n", 
15369             pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
15370     if( pHdr->nBacktrace ){
15371       fflush(out);
15372       pBt = (void**)pHdr;
15373       pBt -= pHdr->nBacktraceSlots;
15374       backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
15375       fprintf(out, "\n");
15376     }
15377   }
15378   fprintf(out, "COUNTS:\n");
15379   for(i=0; i<NCSIZE-1; i++){
15380     if( mem.nAlloc[i] ){
15381       fprintf(out, "   %5d: %10d %10d %10d\n", 
15382             i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
15383     }
15384   }
15385   if( mem.nAlloc[NCSIZE-1] ){
15386     fprintf(out, "   %5d: %10d %10d %10d\n",
15387              NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
15388              mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
15389   }
15390   fclose(out);
15391 }
15392
15393 /*
15394 ** Return the number of times sqlite3MemMalloc() has been called.
15395 */
15396 SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
15397   int i;
15398   int nTotal = 0;
15399   for(i=0; i<NCSIZE; i++){
15400     nTotal += mem.nAlloc[i];
15401   }
15402   return nTotal;
15403 }
15404
15405
15406 #endif /* SQLITE_MEMDEBUG */
15407
15408 /************** End of mem2.c ************************************************/
15409 /************** Begin file mem3.c ********************************************/
15410 /*
15411 ** 2007 October 14
15412 **
15413 ** The author disclaims copyright to this source code.  In place of
15414 ** a legal notice, here is a blessing:
15415 **
15416 **    May you do good and not evil.
15417 **    May you find forgiveness for yourself and forgive others.
15418 **    May you share freely, never taking more than you give.
15419 **
15420 *************************************************************************
15421 ** This file contains the C functions that implement a memory
15422 ** allocation subsystem for use by SQLite. 
15423 **
15424 ** This version of the memory allocation subsystem omits all
15425 ** use of malloc(). The SQLite user supplies a block of memory
15426 ** before calling sqlite3_initialize() from which allocations
15427 ** are made and returned by the xMalloc() and xRealloc() 
15428 ** implementations. Once sqlite3_initialize() has been called,
15429 ** the amount of memory available to SQLite is fixed and cannot
15430 ** be changed.
15431 **
15432 ** This version of the memory allocation subsystem is included
15433 ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
15434 */
15435
15436 /*
15437 ** This version of the memory allocator is only built into the library
15438 ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
15439 ** mean that the library will use a memory-pool by default, just that
15440 ** it is available. The mempool allocator is activated by calling
15441 ** sqlite3_config().
15442 */
15443 #ifdef SQLITE_ENABLE_MEMSYS3
15444
15445 /*
15446 ** Maximum size (in Mem3Blocks) of a "small" chunk.
15447 */
15448 #define MX_SMALL 10
15449
15450
15451 /*
15452 ** Number of freelist hash slots
15453 */
15454 #define N_HASH  61
15455
15456 /*
15457 ** A memory allocation (also called a "chunk") consists of two or 
15458 ** more blocks where each block is 8 bytes.  The first 8 bytes are 
15459 ** a header that is not returned to the user.
15460 **
15461 ** A chunk is two or more blocks that is either checked out or
15462 ** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
15463 ** size of the allocation in blocks if the allocation is free.
15464 ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
15465 ** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
15466 ** is true if the previous chunk is checked out and false if the
15467 ** previous chunk is free.  The u.hdr.prevSize field is the size of
15468 ** the previous chunk in blocks if the previous chunk is on the
15469 ** freelist. If the previous chunk is checked out, then
15470 ** u.hdr.prevSize can be part of the data for that chunk and should
15471 ** not be read or written.
15472 **
15473 ** We often identify a chunk by its index in mem3.aPool[].  When
15474 ** this is done, the chunk index refers to the second block of
15475 ** the chunk.  In this way, the first chunk has an index of 1.
15476 ** A chunk index of 0 means "no such chunk" and is the equivalent
15477 ** of a NULL pointer.
15478 **
15479 ** The second block of free chunks is of the form u.list.  The
15480 ** two fields form a double-linked list of chunks of related sizes.
15481 ** Pointers to the head of the list are stored in mem3.aiSmall[] 
15482 ** for smaller chunks and mem3.aiHash[] for larger chunks.
15483 **
15484 ** The second block of a chunk is user data if the chunk is checked 
15485 ** out.  If a chunk is checked out, the user data may extend into
15486 ** the u.hdr.prevSize value of the following chunk.
15487 */
15488 typedef struct Mem3Block Mem3Block;
15489 struct Mem3Block {
15490   union {
15491     struct {
15492       u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
15493       u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
15494     } hdr;
15495     struct {
15496       u32 next;       /* Index in mem3.aPool[] of next free chunk */
15497       u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
15498     } list;
15499   } u;
15500 };
15501
15502 /*
15503 ** All of the static variables used by this module are collected
15504 ** into a single structure named "mem3".  This is to keep the
15505 ** static variables organized and to reduce namespace pollution
15506 ** when this module is combined with other in the amalgamation.
15507 */
15508 static SQLITE_WSD struct Mem3Global {
15509   /*
15510   ** Memory available for allocation. nPool is the size of the array
15511   ** (in Mem3Blocks) pointed to by aPool less 2.
15512   */
15513   u32 nPool;
15514   Mem3Block *aPool;
15515
15516   /*
15517   ** True if we are evaluating an out-of-memory callback.
15518   */
15519   int alarmBusy;
15520   
15521   /*
15522   ** Mutex to control access to the memory allocation subsystem.
15523   */
15524   sqlite3_mutex *mutex;
15525   
15526   /*
15527   ** The minimum amount of free space that we have seen.
15528   */
15529   u32 mnMaster;
15530
15531   /*
15532   ** iMaster is the index of the master chunk.  Most new allocations
15533   ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
15534   ** of the current master.  iMaster is 0 if there is not master chunk.
15535   ** The master chunk is not in either the aiHash[] or aiSmall[].
15536   */
15537   u32 iMaster;
15538   u32 szMaster;
15539
15540   /*
15541   ** Array of lists of free blocks according to the block size 
15542   ** for smaller chunks, or a hash on the block size for larger
15543   ** chunks.
15544   */
15545   u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
15546   u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
15547 } mem3 = { 97535575 };
15548
15549 #define mem3 GLOBAL(struct Mem3Global, mem3)
15550
15551 /*
15552 ** Unlink the chunk at mem3.aPool[i] from list it is currently
15553 ** on.  *pRoot is the list that i is a member of.
15554 */
15555 static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
15556   u32 next = mem3.aPool[i].u.list.next;
15557   u32 prev = mem3.aPool[i].u.list.prev;
15558   assert( sqlite3_mutex_held(mem3.mutex) );
15559   if( prev==0 ){
15560     *pRoot = next;
15561   }else{
15562     mem3.aPool[prev].u.list.next = next;
15563   }
15564   if( next ){
15565     mem3.aPool[next].u.list.prev = prev;
15566   }
15567   mem3.aPool[i].u.list.next = 0;
15568   mem3.aPool[i].u.list.prev = 0;
15569 }
15570
15571 /*
15572 ** Unlink the chunk at index i from 
15573 ** whatever list is currently a member of.
15574 */
15575 static void memsys3Unlink(u32 i){
15576   u32 size, hash;
15577   assert( sqlite3_mutex_held(mem3.mutex) );
15578   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
15579   assert( i>=1 );
15580   size = mem3.aPool[i-1].u.hdr.size4x/4;
15581   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
15582   assert( size>=2 );
15583   if( size <= MX_SMALL ){
15584     memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
15585   }else{
15586     hash = size % N_HASH;
15587     memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
15588   }
15589 }
15590
15591 /*
15592 ** Link the chunk at mem3.aPool[i] so that is on the list rooted
15593 ** at *pRoot.
15594 */
15595 static void memsys3LinkIntoList(u32 i, u32 *pRoot){
15596   assert( sqlite3_mutex_held(mem3.mutex) );
15597   mem3.aPool[i].u.list.next = *pRoot;
15598   mem3.aPool[i].u.list.prev = 0;
15599   if( *pRoot ){
15600     mem3.aPool[*pRoot].u.list.prev = i;
15601   }
15602   *pRoot = i;
15603 }
15604
15605 /*
15606 ** Link the chunk at index i into either the appropriate
15607 ** small chunk list, or into the large chunk hash table.
15608 */
15609 static void memsys3Link(u32 i){
15610   u32 size, hash;
15611   assert( sqlite3_mutex_held(mem3.mutex) );
15612   assert( i>=1 );
15613   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
15614   size = mem3.aPool[i-1].u.hdr.size4x/4;
15615   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
15616   assert( size>=2 );
15617   if( size <= MX_SMALL ){
15618     memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
15619   }else{
15620     hash = size % N_HASH;
15621     memsys3LinkIntoList(i, &mem3.aiHash[hash]);
15622   }
15623 }
15624
15625 /*
15626 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
15627 ** will already be held (obtained by code in malloc.c) if
15628 ** sqlite3GlobalConfig.bMemStat is true.
15629 */
15630 static void memsys3Enter(void){
15631   if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
15632     mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
15633   }
15634   sqlite3_mutex_enter(mem3.mutex);
15635 }
15636 static void memsys3Leave(void){
15637   sqlite3_mutex_leave(mem3.mutex);
15638 }
15639
15640 /*
15641 ** Called when we are unable to satisfy an allocation of nBytes.
15642 */
15643 static void memsys3OutOfMemory(int nByte){
15644   if( !mem3.alarmBusy ){
15645     mem3.alarmBusy = 1;
15646     assert( sqlite3_mutex_held(mem3.mutex) );
15647     sqlite3_mutex_leave(mem3.mutex);
15648     sqlite3_release_memory(nByte);
15649     sqlite3_mutex_enter(mem3.mutex);
15650     mem3.alarmBusy = 0;
15651   }
15652 }
15653
15654
15655 /*
15656 ** Chunk i is a free chunk that has been unlinked.  Adjust its 
15657 ** size parameters for check-out and return a pointer to the 
15658 ** user portion of the chunk.
15659 */
15660 static void *memsys3Checkout(u32 i, u32 nBlock){
15661   u32 x;
15662   assert( sqlite3_mutex_held(mem3.mutex) );
15663   assert( i>=1 );
15664   assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
15665   assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
15666   x = mem3.aPool[i-1].u.hdr.size4x;
15667   mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
15668   mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
15669   mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
15670   return &mem3.aPool[i];
15671 }
15672
15673 /*
15674 ** Carve a piece off of the end of the mem3.iMaster free chunk.
15675 ** Return a pointer to the new allocation.  Or, if the master chunk
15676 ** is not large enough, return 0.
15677 */
15678 static void *memsys3FromMaster(u32 nBlock){
15679   assert( sqlite3_mutex_held(mem3.mutex) );
15680   assert( mem3.szMaster>=nBlock );
15681   if( nBlock>=mem3.szMaster-1 ){
15682     /* Use the entire master */
15683     void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
15684     mem3.iMaster = 0;
15685     mem3.szMaster = 0;
15686     mem3.mnMaster = 0;
15687     return p;
15688   }else{
15689     /* Split the master block.  Return the tail. */
15690     u32 newi, x;
15691     newi = mem3.iMaster + mem3.szMaster - nBlock;
15692     assert( newi > mem3.iMaster+1 );
15693     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
15694     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
15695     mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
15696     mem3.szMaster -= nBlock;
15697     mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
15698     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
15699     mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
15700     if( mem3.szMaster < mem3.mnMaster ){
15701       mem3.mnMaster = mem3.szMaster;
15702     }
15703     return (void*)&mem3.aPool[newi];
15704   }
15705 }
15706
15707 /*
15708 ** *pRoot is the head of a list of free chunks of the same size
15709 ** or same size hash.  In other words, *pRoot is an entry in either
15710 ** mem3.aiSmall[] or mem3.aiHash[].  
15711 **
15712 ** This routine examines all entries on the given list and tries
15713 ** to coalesce each entries with adjacent free chunks.  
15714 **
15715 ** If it sees a chunk that is larger than mem3.iMaster, it replaces 
15716 ** the current mem3.iMaster with the new larger chunk.  In order for
15717 ** this mem3.iMaster replacement to work, the master chunk must be
15718 ** linked into the hash tables.  That is not the normal state of
15719 ** affairs, of course.  The calling routine must link the master
15720 ** chunk before invoking this routine, then must unlink the (possibly
15721 ** changed) master chunk once this routine has finished.
15722 */
15723 static void memsys3Merge(u32 *pRoot){
15724   u32 iNext, prev, size, i, x;
15725
15726   assert( sqlite3_mutex_held(mem3.mutex) );
15727   for(i=*pRoot; i>0; i=iNext){
15728     iNext = mem3.aPool[i].u.list.next;
15729     size = mem3.aPool[i-1].u.hdr.size4x;
15730     assert( (size&1)==0 );
15731     if( (size&2)==0 ){
15732       memsys3UnlinkFromList(i, pRoot);
15733       assert( i > mem3.aPool[i-1].u.hdr.prevSize );
15734       prev = i - mem3.aPool[i-1].u.hdr.prevSize;
15735       if( prev==iNext ){
15736         iNext = mem3.aPool[prev].u.list.next;
15737       }
15738       memsys3Unlink(prev);
15739       size = i + size/4 - prev;
15740       x = mem3.aPool[prev-1].u.hdr.size4x & 2;
15741       mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
15742       mem3.aPool[prev+size-1].u.hdr.prevSize = size;
15743       memsys3Link(prev);
15744       i = prev;
15745     }else{
15746       size /= 4;
15747     }
15748     if( size>mem3.szMaster ){
15749       mem3.iMaster = i;
15750       mem3.szMaster = size;
15751     }
15752   }
15753 }
15754
15755 /*
15756 ** Return a block of memory of at least nBytes in size.
15757 ** Return NULL if unable.
15758 **
15759 ** This function assumes that the necessary mutexes, if any, are
15760 ** already held by the caller. Hence "Unsafe".
15761 */
15762 static void *memsys3MallocUnsafe(int nByte){
15763   u32 i;
15764   u32 nBlock;
15765   u32 toFree;
15766
15767   assert( sqlite3_mutex_held(mem3.mutex) );
15768   assert( sizeof(Mem3Block)==8 );
15769   if( nByte<=12 ){
15770     nBlock = 2;
15771   }else{
15772     nBlock = (nByte + 11)/8;
15773   }
15774   assert( nBlock>=2 );
15775
15776   /* STEP 1:
15777   ** Look for an entry of the correct size in either the small
15778   ** chunk table or in the large chunk hash table.  This is
15779   ** successful most of the time (about 9 times out of 10).
15780   */
15781   if( nBlock <= MX_SMALL ){
15782     i = mem3.aiSmall[nBlock-2];
15783     if( i>0 ){
15784       memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
15785       return memsys3Checkout(i, nBlock);
15786     }
15787   }else{
15788     int hash = nBlock % N_HASH;
15789     for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
15790       if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
15791         memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
15792         return memsys3Checkout(i, nBlock);
15793       }
15794     }
15795   }
15796
15797   /* STEP 2:
15798   ** Try to satisfy the allocation by carving a piece off of the end
15799   ** of the master chunk.  This step usually works if step 1 fails.
15800   */
15801   if( mem3.szMaster>=nBlock ){
15802     return memsys3FromMaster(nBlock);
15803   }
15804
15805
15806   /* STEP 3:  
15807   ** Loop through the entire memory pool.  Coalesce adjacent free
15808   ** chunks.  Recompute the master chunk as the largest free chunk.
15809   ** Then try again to satisfy the allocation by carving a piece off
15810   ** of the end of the master chunk.  This step happens very
15811   ** rarely (we hope!)
15812   */
15813   for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
15814     memsys3OutOfMemory(toFree);
15815     if( mem3.iMaster ){
15816       memsys3Link(mem3.iMaster);
15817       mem3.iMaster = 0;
15818       mem3.szMaster = 0;
15819     }
15820     for(i=0; i<N_HASH; i++){
15821       memsys3Merge(&mem3.aiHash[i]);
15822     }
15823     for(i=0; i<MX_SMALL-1; i++){
15824       memsys3Merge(&mem3.aiSmall[i]);
15825     }
15826     if( mem3.szMaster ){
15827       memsys3Unlink(mem3.iMaster);
15828       if( mem3.szMaster>=nBlock ){
15829         return memsys3FromMaster(nBlock);
15830       }
15831     }
15832   }
15833
15834   /* If none of the above worked, then we fail. */
15835   return 0;
15836 }
15837
15838 /*
15839 ** Free an outstanding memory allocation.
15840 **
15841 ** This function assumes that the necessary mutexes, if any, are
15842 ** already held by the caller. Hence "Unsafe".
15843 */
15844 void memsys3FreeUnsafe(void *pOld){
15845   Mem3Block *p = (Mem3Block*)pOld;
15846   int i;
15847   u32 size, x;
15848   assert( sqlite3_mutex_held(mem3.mutex) );
15849   assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
15850   i = p - mem3.aPool;
15851   assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
15852   size = mem3.aPool[i-1].u.hdr.size4x/4;
15853   assert( i+size<=mem3.nPool+1 );
15854   mem3.aPool[i-1].u.hdr.size4x &= ~1;
15855   mem3.aPool[i+size-1].u.hdr.prevSize = size;
15856   mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
15857   memsys3Link(i);
15858
15859   /* Try to expand the master using the newly freed chunk */
15860   if( mem3.iMaster ){
15861     while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
15862       size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
15863       mem3.iMaster -= size;
15864       mem3.szMaster += size;
15865       memsys3Unlink(mem3.iMaster);
15866       x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
15867       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
15868       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
15869     }
15870     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
15871     while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
15872       memsys3Unlink(mem3.iMaster+mem3.szMaster);
15873       mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
15874       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
15875       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
15876     }
15877   }
15878 }
15879
15880 /*
15881 ** Return the size of an outstanding allocation, in bytes.  The
15882 ** size returned omits the 8-byte header overhead.  This only
15883 ** works for chunks that are currently checked out.
15884 */
15885 static int memsys3Size(void *p){
15886   Mem3Block *pBlock;
15887   if( p==0 ) return 0;
15888   pBlock = (Mem3Block*)p;
15889   assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
15890   return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
15891 }
15892
15893 /*
15894 ** Round up a request size to the next valid allocation size.
15895 */
15896 static int memsys3Roundup(int n){
15897   if( n<=12 ){
15898     return 12;
15899   }else{
15900     return ((n+11)&~7) - 4;
15901   }
15902 }
15903
15904 /*
15905 ** Allocate nBytes of memory.
15906 */
15907 static void *memsys3Malloc(int nBytes){
15908   sqlite3_int64 *p;
15909   assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
15910   memsys3Enter();
15911   p = memsys3MallocUnsafe(nBytes);
15912   memsys3Leave();
15913   return (void*)p; 
15914 }
15915
15916 /*
15917 ** Free memory.
15918 */
15919 void memsys3Free(void *pPrior){
15920   assert( pPrior );
15921   memsys3Enter();
15922   memsys3FreeUnsafe(pPrior);
15923   memsys3Leave();
15924 }
15925
15926 /*
15927 ** Change the size of an existing memory allocation
15928 */
15929 void *memsys3Realloc(void *pPrior, int nBytes){
15930   int nOld;
15931   void *p;
15932   if( pPrior==0 ){
15933     return sqlite3_malloc(nBytes);
15934   }
15935   if( nBytes<=0 ){
15936     sqlite3_free(pPrior);
15937     return 0;
15938   }
15939   nOld = memsys3Size(pPrior);
15940   if( nBytes<=nOld && nBytes>=nOld-128 ){
15941     return pPrior;
15942   }
15943   memsys3Enter();
15944   p = memsys3MallocUnsafe(nBytes);
15945   if( p ){
15946     if( nOld<nBytes ){
15947       memcpy(p, pPrior, nOld);
15948     }else{
15949       memcpy(p, pPrior, nBytes);
15950     }
15951     memsys3FreeUnsafe(pPrior);
15952   }
15953   memsys3Leave();
15954   return p;
15955 }
15956
15957 /*
15958 ** Initialize this module.
15959 */
15960 static int memsys3Init(void *NotUsed){
15961   UNUSED_PARAMETER(NotUsed);
15962   if( !sqlite3GlobalConfig.pHeap ){
15963     return SQLITE_ERROR;
15964   }
15965
15966   /* Store a pointer to the memory block in global structure mem3. */
15967   assert( sizeof(Mem3Block)==8 );
15968   mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
15969   mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
15970
15971   /* Initialize the master block. */
15972   mem3.szMaster = mem3.nPool;
15973   mem3.mnMaster = mem3.szMaster;
15974   mem3.iMaster = 1;
15975   mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
15976   mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
15977   mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
15978
15979   return SQLITE_OK;
15980 }
15981
15982 /*
15983 ** Deinitialize this module.
15984 */
15985 static void memsys3Shutdown(void *NotUsed){
15986   UNUSED_PARAMETER(NotUsed);
15987   mem3.mutex = 0;
15988   return;
15989 }
15990
15991
15992
15993 /*
15994 ** Open the file indicated and write a log of all unfreed memory 
15995 ** allocations into that log.
15996 */
15997 SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
15998 #ifdef SQLITE_DEBUG
15999   FILE *out;
16000   u32 i, j;
16001   u32 size;
16002   if( zFilename==0 || zFilename[0]==0 ){
16003     out = stdout;
16004   }else{
16005     out = fopen(zFilename, "w");
16006     if( out==0 ){
16007       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
16008                       zFilename);
16009       return;
16010     }
16011   }
16012   memsys3Enter();
16013   fprintf(out, "CHUNKS:\n");
16014   for(i=1; i<=mem3.nPool; i+=size/4){
16015     size = mem3.aPool[i-1].u.hdr.size4x;
16016     if( size/4<=1 ){
16017       fprintf(out, "%p size error\n", &mem3.aPool[i]);
16018       assert( 0 );
16019       break;
16020     }
16021     if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
16022       fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
16023       assert( 0 );
16024       break;
16025     }
16026     if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
16027       fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
16028       assert( 0 );
16029       break;
16030     }
16031     if( size&1 ){
16032       fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
16033     }else{
16034       fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
16035                   i==mem3.iMaster ? " **master**" : "");
16036     }
16037   }
16038   for(i=0; i<MX_SMALL-1; i++){
16039     if( mem3.aiSmall[i]==0 ) continue;
16040     fprintf(out, "small(%2d):", i);
16041     for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
16042       fprintf(out, " %p(%d)", &mem3.aPool[j],
16043               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
16044     }
16045     fprintf(out, "\n"); 
16046   }
16047   for(i=0; i<N_HASH; i++){
16048     if( mem3.aiHash[i]==0 ) continue;
16049     fprintf(out, "hash(%2d):", i);
16050     for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
16051       fprintf(out, " %p(%d)", &mem3.aPool[j],
16052               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
16053     }
16054     fprintf(out, "\n"); 
16055   }
16056   fprintf(out, "master=%d\n", mem3.iMaster);
16057   fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
16058   fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
16059   sqlite3_mutex_leave(mem3.mutex);
16060   if( out==stdout ){
16061     fflush(stdout);
16062   }else{
16063     fclose(out);
16064   }
16065 #else
16066   UNUSED_PARAMETER(zFilename);
16067 #endif
16068 }
16069
16070 /*
16071 ** This routine is the only routine in this file with external 
16072 ** linkage.
16073 **
16074 ** Populate the low-level memory allocation function pointers in
16075 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
16076 ** arguments specify the block of memory to manage.
16077 **
16078 ** This routine is only called by sqlite3_config(), and therefore
16079 ** is not required to be threadsafe (it is not).
16080 */
16081 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
16082   static const sqlite3_mem_methods mempoolMethods = {
16083      memsys3Malloc,
16084      memsys3Free,
16085      memsys3Realloc,
16086      memsys3Size,
16087      memsys3Roundup,
16088      memsys3Init,
16089      memsys3Shutdown,
16090      0
16091   };
16092   return &mempoolMethods;
16093 }
16094
16095 #endif /* SQLITE_ENABLE_MEMSYS3 */
16096
16097 /************** End of mem3.c ************************************************/
16098 /************** Begin file mem5.c ********************************************/
16099 /*
16100 ** 2007 October 14
16101 **
16102 ** The author disclaims copyright to this source code.  In place of
16103 ** a legal notice, here is a blessing:
16104 **
16105 **    May you do good and not evil.
16106 **    May you find forgiveness for yourself and forgive others.
16107 **    May you share freely, never taking more than you give.
16108 **
16109 *************************************************************************
16110 ** This file contains the C functions that implement a memory
16111 ** allocation subsystem for use by SQLite. 
16112 **
16113 ** This version of the memory allocation subsystem omits all
16114 ** use of malloc(). The application gives SQLite a block of memory
16115 ** before calling sqlite3_initialize() from which allocations
16116 ** are made and returned by the xMalloc() and xRealloc() 
16117 ** implementations. Once sqlite3_initialize() has been called,
16118 ** the amount of memory available to SQLite is fixed and cannot
16119 ** be changed.
16120 **
16121 ** This version of the memory allocation subsystem is included
16122 ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
16123 **
16124 ** This memory allocator uses the following algorithm:
16125 **
16126 **   1.  All memory allocations sizes are rounded up to a power of 2.
16127 **
16128 **   2.  If two adjacent free blocks are the halves of a larger block,
16129 **       then the two blocks are coalesed into the single larger block.
16130 **
16131 **   3.  New memory is allocated from the first available free block.
16132 **
16133 ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
16134 ** Concerning Dynamic Storage Allocation". Journal of the Association for
16135 ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
16136 ** 
16137 ** Let n be the size of the largest allocation divided by the minimum
16138 ** allocation size (after rounding all sizes up to a power of 2.)  Let M
16139 ** be the maximum amount of memory ever outstanding at one time.  Let
16140 ** N be the total amount of memory available for allocation.  Robson
16141 ** proved that this memory allocator will never breakdown due to 
16142 ** fragmentation as long as the following constraint holds:
16143 **
16144 **      N >=  M*(1 + log2(n)/2) - n + 1
16145 **
16146 ** The sqlite3_status() logic tracks the maximum values of n and M so
16147 ** that an application can, at any time, verify this constraint.
16148 */
16149
16150 /*
16151 ** This version of the memory allocator is used only when 
16152 ** SQLITE_ENABLE_MEMSYS5 is defined.
16153 */
16154 #ifdef SQLITE_ENABLE_MEMSYS5
16155
16156 /*
16157 ** A minimum allocation is an instance of the following structure.
16158 ** Larger allocations are an array of these structures where the
16159 ** size of the array is a power of 2.
16160 **
16161 ** The size of this object must be a power of two.  That fact is
16162 ** verified in memsys5Init().
16163 */
16164 typedef struct Mem5Link Mem5Link;
16165 struct Mem5Link {
16166   int next;       /* Index of next free chunk */
16167   int prev;       /* Index of previous free chunk */
16168 };
16169
16170 /*
16171 ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
16172 ** mem5.szAtom is always at least 8 and 32-bit integers are used,
16173 ** it is not actually possible to reach this limit.
16174 */
16175 #define LOGMAX 30
16176
16177 /*
16178 ** Masks used for mem5.aCtrl[] elements.
16179 */
16180 #define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
16181 #define CTRL_FREE     0x20    /* True if not checked out */
16182
16183 /*
16184 ** All of the static variables used by this module are collected
16185 ** into a single structure named "mem5".  This is to keep the
16186 ** static variables organized and to reduce namespace pollution
16187 ** when this module is combined with other in the amalgamation.
16188 */
16189 static SQLITE_WSD struct Mem5Global {
16190   /*
16191   ** Memory available for allocation
16192   */
16193   int szAtom;      /* Smallest possible allocation in bytes */
16194   int nBlock;      /* Number of szAtom sized blocks in zPool */
16195   u8 *zPool;       /* Memory available to be allocated */
16196   
16197   /*
16198   ** Mutex to control access to the memory allocation subsystem.
16199   */
16200   sqlite3_mutex *mutex;
16201
16202   /*
16203   ** Performance statistics
16204   */
16205   u64 nAlloc;         /* Total number of calls to malloc */
16206   u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
16207   u64 totalExcess;    /* Total internal fragmentation */
16208   u32 currentOut;     /* Current checkout, including internal fragmentation */
16209   u32 currentCount;   /* Current number of distinct checkouts */
16210   u32 maxOut;         /* Maximum instantaneous currentOut */
16211   u32 maxCount;       /* Maximum instantaneous currentCount */
16212   u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
16213   
16214   /*
16215   ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
16216   ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
16217   ** and so forth.
16218   */
16219   int aiFreelist[LOGMAX+1];
16220
16221   /*
16222   ** Space for tracking which blocks are checked out and the size
16223   ** of each block.  One byte per block.
16224   */
16225   u8 *aCtrl;
16226
16227 } mem5;
16228
16229 /*
16230 ** Access the static variable through a macro for SQLITE_OMIT_WSD
16231 */
16232 #define mem5 GLOBAL(struct Mem5Global, mem5)
16233
16234 /*
16235 ** Assuming mem5.zPool is divided up into an array of Mem5Link
16236 ** structures, return a pointer to the idx-th such lik.
16237 */
16238 #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
16239
16240 /*
16241 ** Unlink the chunk at mem5.aPool[i] from list it is currently
16242 ** on.  It should be found on mem5.aiFreelist[iLogsize].
16243 */
16244 static void memsys5Unlink(int i, int iLogsize){
16245   int next, prev;
16246   assert( i>=0 && i<mem5.nBlock );
16247   assert( iLogsize>=0 && iLogsize<=LOGMAX );
16248   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
16249
16250   next = MEM5LINK(i)->next;
16251   prev = MEM5LINK(i)->prev;
16252   if( prev<0 ){
16253     mem5.aiFreelist[iLogsize] = next;
16254   }else{
16255     MEM5LINK(prev)->next = next;
16256   }
16257   if( next>=0 ){
16258     MEM5LINK(next)->prev = prev;
16259   }
16260 }
16261
16262 /*
16263 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
16264 ** free list.
16265 */
16266 static void memsys5Link(int i, int iLogsize){
16267   int x;
16268   assert( sqlite3_mutex_held(mem5.mutex) );
16269   assert( i>=0 && i<mem5.nBlock );
16270   assert( iLogsize>=0 && iLogsize<=LOGMAX );
16271   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
16272
16273   x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
16274   MEM5LINK(i)->prev = -1;
16275   if( x>=0 ){
16276     assert( x<mem5.nBlock );
16277     MEM5LINK(x)->prev = i;
16278   }
16279   mem5.aiFreelist[iLogsize] = i;
16280 }
16281
16282 /*
16283 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
16284 ** will already be held (obtained by code in malloc.c) if
16285 ** sqlite3GlobalConfig.bMemStat is true.
16286 */
16287 static void memsys5Enter(void){
16288   sqlite3_mutex_enter(mem5.mutex);
16289 }
16290 static void memsys5Leave(void){
16291   sqlite3_mutex_leave(mem5.mutex);
16292 }
16293
16294 /*
16295 ** Return the size of an outstanding allocation, in bytes.  The
16296 ** size returned omits the 8-byte header overhead.  This only
16297 ** works for chunks that are currently checked out.
16298 */
16299 static int memsys5Size(void *p){
16300   int iSize = 0;
16301   if( p ){
16302     int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;
16303     assert( i>=0 && i<mem5.nBlock );
16304     iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
16305   }
16306   return iSize;
16307 }
16308
16309 /*
16310 ** Find the first entry on the freelist iLogsize.  Unlink that
16311 ** entry and return its index. 
16312 */
16313 static int memsys5UnlinkFirst(int iLogsize){
16314   int i;
16315   int iFirst;
16316
16317   assert( iLogsize>=0 && iLogsize<=LOGMAX );
16318   i = iFirst = mem5.aiFreelist[iLogsize];
16319   assert( iFirst>=0 );
16320   while( i>0 ){
16321     if( i<iFirst ) iFirst = i;
16322     i = MEM5LINK(i)->next;
16323   }
16324   memsys5Unlink(iFirst, iLogsize);
16325   return iFirst;
16326 }
16327
16328 /*
16329 ** Return a block of memory of at least nBytes in size.
16330 ** Return NULL if unable.  Return NULL if nBytes==0.
16331 **
16332 ** The caller guarantees that nByte positive.
16333 **
16334 ** The caller has obtained a mutex prior to invoking this
16335 ** routine so there is never any chance that two or more
16336 ** threads can be in this routine at the same time.
16337 */
16338 static void *memsys5MallocUnsafe(int nByte){
16339   int i;           /* Index of a mem5.aPool[] slot */
16340   int iBin;        /* Index into mem5.aiFreelist[] */
16341   int iFullSz;     /* Size of allocation rounded up to power of 2 */
16342   int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
16343
16344   /* nByte must be a positive */
16345   assert( nByte>0 );
16346
16347   /* Keep track of the maximum allocation request.  Even unfulfilled
16348   ** requests are counted */
16349   if( (u32)nByte>mem5.maxRequest ){
16350     mem5.maxRequest = nByte;
16351   }
16352
16353   /* Abort if the requested allocation size is larger than the largest
16354   ** power of two that we can represent using 32-bit signed integers.
16355   */
16356   if( nByte > 0x40000000 ){
16357     return 0;
16358   }
16359
16360   /* Round nByte up to the next valid power of two */
16361   for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
16362
16363   /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
16364   ** block.  If not, then split a block of the next larger power of
16365   ** two in order to create a new free block of size iLogsize.
16366   */
16367   for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
16368   if( iBin>LOGMAX ){
16369     testcase( sqlite3GlobalConfig.xLog!=0 );
16370     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
16371     return 0;
16372   }
16373   i = memsys5UnlinkFirst(iBin);
16374   while( iBin>iLogsize ){
16375     int newSize;
16376
16377     iBin--;
16378     newSize = 1 << iBin;
16379     mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
16380     memsys5Link(i+newSize, iBin);
16381   }
16382   mem5.aCtrl[i] = iLogsize;
16383
16384   /* Update allocator performance statistics. */
16385   mem5.nAlloc++;
16386   mem5.totalAlloc += iFullSz;
16387   mem5.totalExcess += iFullSz - nByte;
16388   mem5.currentCount++;
16389   mem5.currentOut += iFullSz;
16390   if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
16391   if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
16392
16393   /* Return a pointer to the allocated memory. */
16394   return (void*)&mem5.zPool[i*mem5.szAtom];
16395 }
16396
16397 /*
16398 ** Free an outstanding memory allocation.
16399 */
16400 static void memsys5FreeUnsafe(void *pOld){
16401   u32 size, iLogsize;
16402   int iBlock;
16403
16404   /* Set iBlock to the index of the block pointed to by pOld in 
16405   ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
16406   */
16407   iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;
16408
16409   /* Check that the pointer pOld points to a valid, non-free block. */
16410   assert( iBlock>=0 && iBlock<mem5.nBlock );
16411   assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
16412   assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
16413
16414   iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
16415   size = 1<<iLogsize;
16416   assert( iBlock+size-1<(u32)mem5.nBlock );
16417
16418   mem5.aCtrl[iBlock] |= CTRL_FREE;
16419   mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
16420   assert( mem5.currentCount>0 );
16421   assert( mem5.currentOut>=(size*mem5.szAtom) );
16422   mem5.currentCount--;
16423   mem5.currentOut -= size*mem5.szAtom;
16424   assert( mem5.currentOut>0 || mem5.currentCount==0 );
16425   assert( mem5.currentCount>0 || mem5.currentOut==0 );
16426
16427   mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
16428   while( ALWAYS(iLogsize<LOGMAX) ){
16429     int iBuddy;
16430     if( (iBlock>>iLogsize) & 1 ){
16431       iBuddy = iBlock - size;
16432     }else{
16433       iBuddy = iBlock + size;
16434     }
16435     assert( iBuddy>=0 );
16436     if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
16437     if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
16438     memsys5Unlink(iBuddy, iLogsize);
16439     iLogsize++;
16440     if( iBuddy<iBlock ){
16441       mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
16442       mem5.aCtrl[iBlock] = 0;
16443       iBlock = iBuddy;
16444     }else{
16445       mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
16446       mem5.aCtrl[iBuddy] = 0;
16447     }
16448     size *= 2;
16449   }
16450   memsys5Link(iBlock, iLogsize);
16451 }
16452
16453 /*
16454 ** Allocate nBytes of memory
16455 */
16456 static void *memsys5Malloc(int nBytes){
16457   sqlite3_int64 *p = 0;
16458   if( nBytes>0 ){
16459     memsys5Enter();
16460     p = memsys5MallocUnsafe(nBytes);
16461     memsys5Leave();
16462   }
16463   return (void*)p; 
16464 }
16465
16466 /*
16467 ** Free memory.
16468 **
16469 ** The outer layer memory allocator prevents this routine from
16470 ** being called with pPrior==0.
16471 */
16472 static void memsys5Free(void *pPrior){
16473   assert( pPrior!=0 );
16474   memsys5Enter();
16475   memsys5FreeUnsafe(pPrior);
16476   memsys5Leave();  
16477 }
16478
16479 /*
16480 ** Change the size of an existing memory allocation.
16481 **
16482 ** The outer layer memory allocator prevents this routine from
16483 ** being called with pPrior==0.  
16484 **
16485 ** nBytes is always a value obtained from a prior call to
16486 ** memsys5Round().  Hence nBytes is always a non-negative power
16487 ** of two.  If nBytes==0 that means that an oversize allocation
16488 ** (an allocation larger than 0x40000000) was requested and this
16489 ** routine should return 0 without freeing pPrior.
16490 */
16491 static void *memsys5Realloc(void *pPrior, int nBytes){
16492   int nOld;
16493   void *p;
16494   assert( pPrior!=0 );
16495   assert( (nBytes&(nBytes-1))==0 );  /* EV: R-46199-30249 */
16496   assert( nBytes>=0 );
16497   if( nBytes==0 ){
16498     return 0;
16499   }
16500   nOld = memsys5Size(pPrior);
16501   if( nBytes<=nOld ){
16502     return pPrior;
16503   }
16504   memsys5Enter();
16505   p = memsys5MallocUnsafe(nBytes);
16506   if( p ){
16507     memcpy(p, pPrior, nOld);
16508     memsys5FreeUnsafe(pPrior);
16509   }
16510   memsys5Leave();
16511   return p;
16512 }
16513
16514 /*
16515 ** Round up a request size to the next valid allocation size.  If
16516 ** the allocation is too large to be handled by this allocation system,
16517 ** return 0.
16518 **
16519 ** All allocations must be a power of two and must be expressed by a
16520 ** 32-bit signed integer.  Hence the largest allocation is 0x40000000
16521 ** or 1073741824 bytes.
16522 */
16523 static int memsys5Roundup(int n){
16524   int iFullSz;
16525   if( n > 0x40000000 ) return 0;
16526   for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
16527   return iFullSz;
16528 }
16529
16530 /*
16531 ** Return the ceiling of the logarithm base 2 of iValue.
16532 **
16533 ** Examples:   memsys5Log(1) -> 0
16534 **             memsys5Log(2) -> 1
16535 **             memsys5Log(4) -> 2
16536 **             memsys5Log(5) -> 3
16537 **             memsys5Log(8) -> 3
16538 **             memsys5Log(9) -> 4
16539 */
16540 static int memsys5Log(int iValue){
16541   int iLog;
16542   for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
16543   return iLog;
16544 }
16545
16546 /*
16547 ** Initialize the memory allocator.
16548 **
16549 ** This routine is not threadsafe.  The caller must be holding a mutex
16550 ** to prevent multiple threads from entering at the same time.
16551 */
16552 static int memsys5Init(void *NotUsed){
16553   int ii;            /* Loop counter */
16554   int nByte;         /* Number of bytes of memory available to this allocator */
16555   u8 *zByte;         /* Memory usable by this allocator */
16556   int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
16557   int iOffset;       /* An offset into mem5.aCtrl[] */
16558
16559   UNUSED_PARAMETER(NotUsed);
16560
16561   /* For the purposes of this routine, disable the mutex */
16562   mem5.mutex = 0;
16563
16564   /* The size of a Mem5Link object must be a power of two.  Verify that
16565   ** this is case.
16566   */
16567   assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
16568
16569   nByte = sqlite3GlobalConfig.nHeap;
16570   zByte = (u8*)sqlite3GlobalConfig.pHeap;
16571   assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */
16572
16573   /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
16574   nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
16575   mem5.szAtom = (1<<nMinLog);
16576   while( (int)sizeof(Mem5Link)>mem5.szAtom ){
16577     mem5.szAtom = mem5.szAtom << 1;
16578   }
16579
16580   mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
16581   mem5.zPool = zByte;
16582   mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
16583
16584   for(ii=0; ii<=LOGMAX; ii++){
16585     mem5.aiFreelist[ii] = -1;
16586   }
16587
16588   iOffset = 0;
16589   for(ii=LOGMAX; ii>=0; ii--){
16590     int nAlloc = (1<<ii);
16591     if( (iOffset+nAlloc)<=mem5.nBlock ){
16592       mem5.aCtrl[iOffset] = ii | CTRL_FREE;
16593       memsys5Link(iOffset, ii);
16594       iOffset += nAlloc;
16595     }
16596     assert((iOffset+nAlloc)>mem5.nBlock);
16597   }
16598
16599   /* If a mutex is required for normal operation, allocate one */
16600   if( sqlite3GlobalConfig.bMemstat==0 ){
16601     mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
16602   }
16603
16604   return SQLITE_OK;
16605 }
16606
16607 /*
16608 ** Deinitialize this module.
16609 */
16610 static void memsys5Shutdown(void *NotUsed){
16611   UNUSED_PARAMETER(NotUsed);
16612   mem5.mutex = 0;
16613   return;
16614 }
16615
16616 #ifdef SQLITE_TEST
16617 /*
16618 ** Open the file indicated and write a log of all unfreed memory 
16619 ** allocations into that log.
16620 */
16621 SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
16622   FILE *out;
16623   int i, j, n;
16624   int nMinLog;
16625
16626   if( zFilename==0 || zFilename[0]==0 ){
16627     out = stdout;
16628   }else{
16629     out = fopen(zFilename, "w");
16630     if( out==0 ){
16631       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
16632                       zFilename);
16633       return;
16634     }
16635   }
16636   memsys5Enter();
16637   nMinLog = memsys5Log(mem5.szAtom);
16638   for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
16639     for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
16640     fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
16641   }
16642   fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
16643   fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
16644   fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
16645   fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
16646   fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
16647   fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
16648   fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
16649   fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
16650   memsys5Leave();
16651   if( out==stdout ){
16652     fflush(stdout);
16653   }else{
16654     fclose(out);
16655   }
16656 }
16657 #endif
16658
16659 /*
16660 ** This routine is the only routine in this file with external 
16661 ** linkage. It returns a pointer to a static sqlite3_mem_methods
16662 ** struct populated with the memsys5 methods.
16663 */
16664 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
16665   static const sqlite3_mem_methods memsys5Methods = {
16666      memsys5Malloc,
16667      memsys5Free,
16668      memsys5Realloc,
16669      memsys5Size,
16670      memsys5Roundup,
16671      memsys5Init,
16672      memsys5Shutdown,
16673      0
16674   };
16675   return &memsys5Methods;
16676 }
16677
16678 #endif /* SQLITE_ENABLE_MEMSYS5 */
16679
16680 /************** End of mem5.c ************************************************/
16681 /************** Begin file mutex.c *******************************************/
16682 /*
16683 ** 2007 August 14
16684 **
16685 ** The author disclaims copyright to this source code.  In place of
16686 ** a legal notice, here is a blessing:
16687 **
16688 **    May you do good and not evil.
16689 **    May you find forgiveness for yourself and forgive others.
16690 **    May you share freely, never taking more than you give.
16691 **
16692 *************************************************************************
16693 ** This file contains the C functions that implement mutexes.
16694 **
16695 ** This file contains code that is common across all mutex implementations.
16696 */
16697
16698 #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
16699 /*
16700 ** For debugging purposes, record when the mutex subsystem is initialized
16701 ** and uninitialized so that we can assert() if there is an attempt to
16702 ** allocate a mutex while the system is uninitialized.
16703 */
16704 static SQLITE_WSD int mutexIsInit = 0;
16705 #endif /* SQLITE_DEBUG */
16706
16707
16708 #ifndef SQLITE_MUTEX_OMIT
16709 /*
16710 ** Initialize the mutex system.
16711 */
16712 SQLITE_PRIVATE int sqlite3MutexInit(void){ 
16713   int rc = SQLITE_OK;
16714   if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
16715     /* If the xMutexAlloc method has not been set, then the user did not
16716     ** install a mutex implementation via sqlite3_config() prior to 
16717     ** sqlite3_initialize() being called. This block copies pointers to
16718     ** the default implementation into the sqlite3GlobalConfig structure.
16719     */
16720     sqlite3_mutex_methods const *pFrom;
16721     sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
16722
16723     if( sqlite3GlobalConfig.bCoreMutex ){
16724       pFrom = sqlite3DefaultMutex();
16725     }else{
16726       pFrom = sqlite3NoopMutex();
16727     }
16728     memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
16729     memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
16730            sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
16731     pTo->xMutexAlloc = pFrom->xMutexAlloc;
16732   }
16733   rc = sqlite3GlobalConfig.mutex.xMutexInit();
16734
16735 #ifdef SQLITE_DEBUG
16736   GLOBAL(int, mutexIsInit) = 1;
16737 #endif
16738
16739   return rc;
16740 }
16741
16742 /*
16743 ** Shutdown the mutex system. This call frees resources allocated by
16744 ** sqlite3MutexInit().
16745 */
16746 SQLITE_PRIVATE int sqlite3MutexEnd(void){
16747   int rc = SQLITE_OK;
16748   if( sqlite3GlobalConfig.mutex.xMutexEnd ){
16749     rc = sqlite3GlobalConfig.mutex.xMutexEnd();
16750   }
16751
16752 #ifdef SQLITE_DEBUG
16753   GLOBAL(int, mutexIsInit) = 0;
16754 #endif
16755
16756   return rc;
16757 }
16758
16759 /*
16760 ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
16761 */
16762 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
16763 #ifndef SQLITE_OMIT_AUTOINIT
16764   if( sqlite3_initialize() ) return 0;
16765 #endif
16766   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
16767 }
16768
16769 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
16770   if( !sqlite3GlobalConfig.bCoreMutex ){
16771     return 0;
16772   }
16773   assert( GLOBAL(int, mutexIsInit) );
16774   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
16775 }
16776
16777 /*
16778 ** Free a dynamic mutex.
16779 */
16780 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
16781   if( p ){
16782     sqlite3GlobalConfig.mutex.xMutexFree(p);
16783   }
16784 }
16785
16786 /*
16787 ** Obtain the mutex p. If some other thread already has the mutex, block
16788 ** until it can be obtained.
16789 */
16790 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
16791   if( p ){
16792     sqlite3GlobalConfig.mutex.xMutexEnter(p);
16793   }
16794 }
16795
16796 /*
16797 ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
16798 ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
16799 */
16800 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
16801   int rc = SQLITE_OK;
16802   if( p ){
16803     return sqlite3GlobalConfig.mutex.xMutexTry(p);
16804   }
16805   return rc;
16806 }
16807
16808 /*
16809 ** The sqlite3_mutex_leave() routine exits a mutex that was previously
16810 ** entered by the same thread.  The behavior is undefined if the mutex 
16811 ** is not currently entered. If a NULL pointer is passed as an argument
16812 ** this function is a no-op.
16813 */
16814 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
16815   if( p ){
16816     sqlite3GlobalConfig.mutex.xMutexLeave(p);
16817   }
16818 }
16819
16820 #ifndef NDEBUG
16821 /*
16822 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
16823 ** intended for use inside assert() statements.
16824 */
16825 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
16826   return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
16827 }
16828 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
16829   return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
16830 }
16831 #endif
16832
16833 #endif /* SQLITE_MUTEX_OMIT */
16834
16835 /************** End of mutex.c ***********************************************/
16836 /************** Begin file mutex_noop.c **************************************/
16837 /*
16838 ** 2008 October 07
16839 **
16840 ** The author disclaims copyright to this source code.  In place of
16841 ** a legal notice, here is a blessing:
16842 **
16843 **    May you do good and not evil.
16844 **    May you find forgiveness for yourself and forgive others.
16845 **    May you share freely, never taking more than you give.
16846 **
16847 *************************************************************************
16848 ** This file contains the C functions that implement mutexes.
16849 **
16850 ** This implementation in this file does not provide any mutual
16851 ** exclusion and is thus suitable for use only in applications
16852 ** that use SQLite in a single thread.  The routines defined
16853 ** here are place-holders.  Applications can substitute working
16854 ** mutex routines at start-time using the
16855 **
16856 **     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
16857 **
16858 ** interface.
16859 **
16860 ** If compiled with SQLITE_DEBUG, then additional logic is inserted
16861 ** that does error checking on mutexes to make sure they are being
16862 ** called correctly.
16863 */
16864
16865 #ifndef SQLITE_MUTEX_OMIT
16866
16867 #ifndef SQLITE_DEBUG
16868 /*
16869 ** Stub routines for all mutex methods.
16870 **
16871 ** This routines provide no mutual exclusion or error checking.
16872 */
16873 static int noopMutexInit(void){ return SQLITE_OK; }
16874 static int noopMutexEnd(void){ return SQLITE_OK; }
16875 static sqlite3_mutex *noopMutexAlloc(int id){ 
16876   UNUSED_PARAMETER(id);
16877   return (sqlite3_mutex*)8; 
16878 }
16879 static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
16880 static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
16881 static int noopMutexTry(sqlite3_mutex *p){
16882   UNUSED_PARAMETER(p);
16883   return SQLITE_OK;
16884 }
16885 static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
16886
16887 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
16888   static const sqlite3_mutex_methods sMutex = {
16889     noopMutexInit,
16890     noopMutexEnd,
16891     noopMutexAlloc,
16892     noopMutexFree,
16893     noopMutexEnter,
16894     noopMutexTry,
16895     noopMutexLeave,
16896
16897     0,
16898     0,
16899   };
16900
16901   return &sMutex;
16902 }
16903 #endif /* !SQLITE_DEBUG */
16904
16905 #ifdef SQLITE_DEBUG
16906 /*
16907 ** In this implementation, error checking is provided for testing
16908 ** and debugging purposes.  The mutexes still do not provide any
16909 ** mutual exclusion.
16910 */
16911
16912 /*
16913 ** The mutex object
16914 */
16915 typedef struct sqlite3_debug_mutex {
16916   int id;     /* The mutex type */
16917   int cnt;    /* Number of entries without a matching leave */
16918 } sqlite3_debug_mutex;
16919
16920 /*
16921 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
16922 ** intended for use inside assert() statements.
16923 */
16924 static int debugMutexHeld(sqlite3_mutex *pX){
16925   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16926   return p==0 || p->cnt>0;
16927 }
16928 static int debugMutexNotheld(sqlite3_mutex *pX){
16929   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16930   return p==0 || p->cnt==0;
16931 }
16932
16933 /*
16934 ** Initialize and deinitialize the mutex subsystem.
16935 */
16936 static int debugMutexInit(void){ return SQLITE_OK; }
16937 static int debugMutexEnd(void){ return SQLITE_OK; }
16938
16939 /*
16940 ** The sqlite3_mutex_alloc() routine allocates a new
16941 ** mutex and returns a pointer to it.  If it returns NULL
16942 ** that means that a mutex could not be allocated. 
16943 */
16944 static sqlite3_mutex *debugMutexAlloc(int id){
16945   static sqlite3_debug_mutex aStatic[6];
16946   sqlite3_debug_mutex *pNew = 0;
16947   switch( id ){
16948     case SQLITE_MUTEX_FAST:
16949     case SQLITE_MUTEX_RECURSIVE: {
16950       pNew = sqlite3Malloc(sizeof(*pNew));
16951       if( pNew ){
16952         pNew->id = id;
16953         pNew->cnt = 0;
16954       }
16955       break;
16956     }
16957     default: {
16958       assert( id-2 >= 0 );
16959       assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
16960       pNew = &aStatic[id-2];
16961       pNew->id = id;
16962       break;
16963     }
16964   }
16965   return (sqlite3_mutex*)pNew;
16966 }
16967
16968 /*
16969 ** This routine deallocates a previously allocated mutex.
16970 */
16971 static void debugMutexFree(sqlite3_mutex *pX){
16972   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16973   assert( p->cnt==0 );
16974   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
16975   sqlite3_free(p);
16976 }
16977
16978 /*
16979 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
16980 ** to enter a mutex.  If another thread is already within the mutex,
16981 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
16982 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
16983 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
16984 ** be entered multiple times by the same thread.  In such cases the,
16985 ** mutex must be exited an equal number of times before another thread
16986 ** can enter.  If the same thread tries to enter any other kind of mutex
16987 ** more than once, the behavior is undefined.
16988 */
16989 static void debugMutexEnter(sqlite3_mutex *pX){
16990   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16991   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
16992   p->cnt++;
16993 }
16994 static int debugMutexTry(sqlite3_mutex *pX){
16995   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16996   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
16997   p->cnt++;
16998   return SQLITE_OK;
16999 }
17000
17001 /*
17002 ** The sqlite3_mutex_leave() routine exits a mutex that was
17003 ** previously entered by the same thread.  The behavior
17004 ** is undefined if the mutex is not currently entered or
17005 ** is not currently allocated.  SQLite will never do either.
17006 */
17007 static void debugMutexLeave(sqlite3_mutex *pX){
17008   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17009   assert( debugMutexHeld(pX) );
17010   p->cnt--;
17011   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
17012 }
17013
17014 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
17015   static const sqlite3_mutex_methods sMutex = {
17016     debugMutexInit,
17017     debugMutexEnd,
17018     debugMutexAlloc,
17019     debugMutexFree,
17020     debugMutexEnter,
17021     debugMutexTry,
17022     debugMutexLeave,
17023
17024     debugMutexHeld,
17025     debugMutexNotheld
17026   };
17027
17028   return &sMutex;
17029 }
17030 #endif /* SQLITE_DEBUG */
17031
17032 /*
17033 ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
17034 ** is used regardless of the run-time threadsafety setting.
17035 */
17036 #ifdef SQLITE_MUTEX_NOOP
17037 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
17038   return sqlite3NoopMutex();
17039 }
17040 #endif /* SQLITE_MUTEX_NOOP */
17041 #endif /* SQLITE_MUTEX_OMIT */
17042
17043 /************** End of mutex_noop.c ******************************************/
17044 /************** Begin file mutex_os2.c ***************************************/
17045 /*
17046 ** 2007 August 28
17047 **
17048 ** The author disclaims copyright to this source code.  In place of
17049 ** a legal notice, here is a blessing:
17050 **
17051 **    May you do good and not evil.
17052 **    May you find forgiveness for yourself and forgive others.
17053 **    May you share freely, never taking more than you give.
17054 **
17055 *************************************************************************
17056 ** This file contains the C functions that implement mutexes for OS/2
17057 */
17058
17059 /*
17060 ** The code in this file is only used if SQLITE_MUTEX_OS2 is defined.
17061 ** See the mutex.h file for details.
17062 */
17063 #ifdef SQLITE_MUTEX_OS2
17064
17065 /********************** OS/2 Mutex Implementation **********************
17066 **
17067 ** This implementation of mutexes is built using the OS/2 API.
17068 */
17069
17070 /*
17071 ** The mutex object
17072 ** Each recursive mutex is an instance of the following structure.
17073 */
17074 struct sqlite3_mutex {
17075   HMTX mutex;       /* Mutex controlling the lock */
17076   int  id;          /* Mutex type */
17077 #ifdef SQLITE_DEBUG
17078  int   trace;       /* True to trace changes */
17079 #endif
17080 };
17081
17082 #ifdef SQLITE_DEBUG
17083 #define SQLITE3_MUTEX_INITIALIZER { 0, 0, 0 }
17084 #else
17085 #define SQLITE3_MUTEX_INITIALIZER { 0, 0 }
17086 #endif
17087
17088 /*
17089 ** Initialize and deinitialize the mutex subsystem.
17090 */
17091 static int os2MutexInit(void){ return SQLITE_OK; }
17092 static int os2MutexEnd(void){ return SQLITE_OK; }
17093
17094 /*
17095 ** The sqlite3_mutex_alloc() routine allocates a new
17096 ** mutex and returns a pointer to it.  If it returns NULL
17097 ** that means that a mutex could not be allocated. 
17098 ** SQLite will unwind its stack and return an error.  The argument
17099 ** to sqlite3_mutex_alloc() is one of these integer constants:
17100 **
17101 ** <ul>
17102 ** <li>  SQLITE_MUTEX_FAST
17103 ** <li>  SQLITE_MUTEX_RECURSIVE
17104 ** <li>  SQLITE_MUTEX_STATIC_MASTER
17105 ** <li>  SQLITE_MUTEX_STATIC_MEM
17106 ** <li>  SQLITE_MUTEX_STATIC_MEM2
17107 ** <li>  SQLITE_MUTEX_STATIC_PRNG
17108 ** <li>  SQLITE_MUTEX_STATIC_LRU
17109 ** <li>  SQLITE_MUTEX_STATIC_LRU2
17110 ** </ul>
17111 **
17112 ** The first two constants cause sqlite3_mutex_alloc() to create
17113 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
17114 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
17115 ** The mutex implementation does not need to make a distinction
17116 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
17117 ** not want to.  But SQLite will only request a recursive mutex in
17118 ** cases where it really needs one.  If a faster non-recursive mutex
17119 ** implementation is available on the host platform, the mutex subsystem
17120 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
17121 **
17122 ** The other allowed parameters to sqlite3_mutex_alloc() each return
17123 ** a pointer to a static preexisting mutex.  Six static mutexes are
17124 ** used by the current version of SQLite.  Future versions of SQLite
17125 ** may add additional static mutexes.  Static mutexes are for internal
17126 ** use by SQLite only.  Applications that use SQLite mutexes should
17127 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
17128 ** SQLITE_MUTEX_RECURSIVE.
17129 **
17130 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
17131 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
17132 ** returns a different mutex on every call.  But for the static
17133 ** mutex types, the same mutex is returned on every call that has
17134 ** the same type number.
17135 */
17136 static sqlite3_mutex *os2MutexAlloc(int iType){
17137   sqlite3_mutex *p = NULL;
17138   switch( iType ){
17139     case SQLITE_MUTEX_FAST:
17140     case SQLITE_MUTEX_RECURSIVE: {
17141       p = sqlite3MallocZero( sizeof(*p) );
17142       if( p ){
17143         p->id = iType;
17144         if( DosCreateMutexSem( 0, &p->mutex, 0, FALSE ) != NO_ERROR ){
17145           sqlite3_free( p );
17146           p = NULL;
17147         }
17148       }
17149       break;
17150     }
17151     default: {
17152       static volatile int isInit = 0;
17153       static sqlite3_mutex staticMutexes[6] = {
17154         SQLITE3_MUTEX_INITIALIZER,
17155         SQLITE3_MUTEX_INITIALIZER,
17156         SQLITE3_MUTEX_INITIALIZER,
17157         SQLITE3_MUTEX_INITIALIZER,
17158         SQLITE3_MUTEX_INITIALIZER,
17159         SQLITE3_MUTEX_INITIALIZER,
17160       };
17161       if ( !isInit ){
17162         APIRET rc;
17163         PTIB ptib;
17164         PPIB ppib;
17165         HMTX mutex;
17166         char name[32];
17167         DosGetInfoBlocks( &ptib, &ppib );
17168         sqlite3_snprintf( sizeof(name), name, "\\SEM32\\SQLITE%04x",
17169                           ppib->pib_ulpid );
17170         while( !isInit ){
17171           mutex = 0;
17172           rc = DosCreateMutexSem( name, &mutex, 0, FALSE);
17173           if( rc == NO_ERROR ){
17174             unsigned int i;
17175             if( !isInit ){
17176               for( i = 0; i < sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++ ){
17177                 DosCreateMutexSem( 0, &staticMutexes[i].mutex, 0, FALSE );
17178               }
17179               isInit = 1;
17180             }
17181             DosCloseMutexSem( mutex );
17182           }else if( rc == ERROR_DUPLICATE_NAME ){
17183             DosSleep( 1 );
17184           }else{
17185             return p;
17186           }
17187         }
17188       }
17189       assert( iType-2 >= 0 );
17190       assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
17191       p = &staticMutexes[iType-2];
17192       p->id = iType;
17193       break;
17194     }
17195   }
17196   return p;
17197 }
17198
17199
17200 /*
17201 ** This routine deallocates a previously allocated mutex.
17202 ** SQLite is careful to deallocate every mutex that it allocates.
17203 */
17204 static void os2MutexFree(sqlite3_mutex *p){
17205 #ifdef SQLITE_DEBUG
17206   TID tid;
17207   PID pid;
17208   ULONG ulCount;
17209   DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
17210   assert( ulCount==0 );
17211   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
17212 #endif
17213   DosCloseMutexSem( p->mutex );
17214   sqlite3_free( p );
17215 }
17216
17217 #ifdef SQLITE_DEBUG
17218 /*
17219 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17220 ** intended for use inside assert() statements.
17221 */
17222 static int os2MutexHeld(sqlite3_mutex *p){
17223   TID tid;
17224   PID pid;
17225   ULONG ulCount;
17226   PTIB ptib;
17227   DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
17228   if( ulCount==0 || ( ulCount>1 && p->id!=SQLITE_MUTEX_RECURSIVE ) )
17229     return 0;
17230   DosGetInfoBlocks(&ptib, NULL);
17231   return tid==ptib->tib_ptib2->tib2_ultid;
17232 }
17233 static int os2MutexNotheld(sqlite3_mutex *p){
17234   TID tid;
17235   PID pid;
17236   ULONG ulCount;
17237   PTIB ptib;
17238   DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
17239   if( ulCount==0 )
17240     return 1;
17241   DosGetInfoBlocks(&ptib, NULL);
17242   return tid!=ptib->tib_ptib2->tib2_ultid;
17243 }
17244 static void os2MutexTrace(sqlite3_mutex *p, char *pAction){
17245   TID   tid;
17246   PID   pid;
17247   ULONG ulCount;
17248   DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
17249   printf("%s mutex %p (%d) with nRef=%ld\n", pAction, (void*)p, p->trace, ulCount);
17250 }
17251 #endif
17252
17253 /*
17254 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
17255 ** to enter a mutex.  If another thread is already within the mutex,
17256 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
17257 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
17258 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
17259 ** be entered multiple times by the same thread.  In such cases the,
17260 ** mutex must be exited an equal number of times before another thread
17261 ** can enter.  If the same thread tries to enter any other kind of mutex
17262 ** more than once, the behavior is undefined.
17263 */
17264 static void os2MutexEnter(sqlite3_mutex *p){
17265   assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
17266   DosRequestMutexSem(p->mutex, SEM_INDEFINITE_WAIT);
17267 #ifdef SQLITE_DEBUG
17268   if( p->trace ) os2MutexTrace(p, "enter");
17269 #endif
17270 }
17271 static int os2MutexTry(sqlite3_mutex *p){
17272   int rc = SQLITE_BUSY;
17273   assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
17274   if( DosRequestMutexSem(p->mutex, SEM_IMMEDIATE_RETURN) == NO_ERROR ) {
17275     rc = SQLITE_OK;
17276 #ifdef SQLITE_DEBUG
17277     if( p->trace ) os2MutexTrace(p, "try");
17278 #endif
17279   }
17280   return rc;
17281 }
17282
17283 /*
17284 ** The sqlite3_mutex_leave() routine exits a mutex that was
17285 ** previously entered by the same thread.  The behavior
17286 ** is undefined if the mutex is not currently entered or
17287 ** is not currently allocated.  SQLite will never do either.
17288 */
17289 static void os2MutexLeave(sqlite3_mutex *p){
17290   assert( os2MutexHeld(p) );
17291   DosReleaseMutexSem(p->mutex);
17292 #ifdef SQLITE_DEBUG
17293   if( p->trace ) os2MutexTrace(p, "leave");
17294 #endif
17295 }
17296
17297 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
17298   static const sqlite3_mutex_methods sMutex = {
17299     os2MutexInit,
17300     os2MutexEnd,
17301     os2MutexAlloc,
17302     os2MutexFree,
17303     os2MutexEnter,
17304     os2MutexTry,
17305     os2MutexLeave,
17306 #ifdef SQLITE_DEBUG
17307     os2MutexHeld,
17308     os2MutexNotheld
17309 #else
17310     0,
17311     0
17312 #endif
17313   };
17314
17315   return &sMutex;
17316 }
17317 #endif /* SQLITE_MUTEX_OS2 */
17318
17319 /************** End of mutex_os2.c *******************************************/
17320 /************** Begin file mutex_unix.c **************************************/
17321 /*
17322 ** 2007 August 28
17323 **
17324 ** The author disclaims copyright to this source code.  In place of
17325 ** a legal notice, here is a blessing:
17326 **
17327 **    May you do good and not evil.
17328 **    May you find forgiveness for yourself and forgive others.
17329 **    May you share freely, never taking more than you give.
17330 **
17331 *************************************************************************
17332 ** This file contains the C functions that implement mutexes for pthreads
17333 */
17334
17335 /*
17336 ** The code in this file is only used if we are compiling threadsafe
17337 ** under unix with pthreads.
17338 **
17339 ** Note that this implementation requires a version of pthreads that
17340 ** supports recursive mutexes.
17341 */
17342 #ifdef SQLITE_MUTEX_PTHREADS
17343
17344 #include <pthread.h>
17345
17346 /*
17347 ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
17348 ** are necessary under two condidtions:  (1) Debug builds and (2) using
17349 ** home-grown mutexes.  Encapsulate these conditions into a single #define.
17350 */
17351 #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
17352 # define SQLITE_MUTEX_NREF 1
17353 #else
17354 # define SQLITE_MUTEX_NREF 0
17355 #endif
17356
17357 /*
17358 ** Each recursive mutex is an instance of the following structure.
17359 */
17360 struct sqlite3_mutex {
17361   pthread_mutex_t mutex;     /* Mutex controlling the lock */
17362 #if SQLITE_MUTEX_NREF
17363   int id;                    /* Mutex type */
17364   volatile int nRef;         /* Number of entrances */
17365   volatile pthread_t owner;  /* Thread that is within this mutex */
17366   int trace;                 /* True to trace changes */
17367 #endif
17368 };
17369 #if SQLITE_MUTEX_NREF
17370 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
17371 #else
17372 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
17373 #endif
17374
17375 /*
17376 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17377 ** intended for use only inside assert() statements.  On some platforms,
17378 ** there might be race conditions that can cause these routines to
17379 ** deliver incorrect results.  In particular, if pthread_equal() is
17380 ** not an atomic operation, then these routines might delivery
17381 ** incorrect results.  On most platforms, pthread_equal() is a 
17382 ** comparison of two integers and is therefore atomic.  But we are
17383 ** told that HPUX is not such a platform.  If so, then these routines
17384 ** will not always work correctly on HPUX.
17385 **
17386 ** On those platforms where pthread_equal() is not atomic, SQLite
17387 ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
17388 ** make sure no assert() statements are evaluated and hence these
17389 ** routines are never called.
17390 */
17391 #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
17392 static int pthreadMutexHeld(sqlite3_mutex *p){
17393   return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
17394 }
17395 static int pthreadMutexNotheld(sqlite3_mutex *p){
17396   return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
17397 }
17398 #endif
17399
17400 /*
17401 ** Initialize and deinitialize the mutex subsystem.
17402 */
17403 static int pthreadMutexInit(void){ return SQLITE_OK; }
17404 static int pthreadMutexEnd(void){ return SQLITE_OK; }
17405
17406 /*
17407 ** The sqlite3_mutex_alloc() routine allocates a new
17408 ** mutex and returns a pointer to it.  If it returns NULL
17409 ** that means that a mutex could not be allocated.  SQLite
17410 ** will unwind its stack and return an error.  The argument
17411 ** to sqlite3_mutex_alloc() is one of these integer constants:
17412 **
17413 ** <ul>
17414 ** <li>  SQLITE_MUTEX_FAST
17415 ** <li>  SQLITE_MUTEX_RECURSIVE
17416 ** <li>  SQLITE_MUTEX_STATIC_MASTER
17417 ** <li>  SQLITE_MUTEX_STATIC_MEM
17418 ** <li>  SQLITE_MUTEX_STATIC_MEM2
17419 ** <li>  SQLITE_MUTEX_STATIC_PRNG
17420 ** <li>  SQLITE_MUTEX_STATIC_LRU
17421 ** <li>  SQLITE_MUTEX_STATIC_PMEM
17422 ** </ul>
17423 **
17424 ** The first two constants cause sqlite3_mutex_alloc() to create
17425 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
17426 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
17427 ** The mutex implementation does not need to make a distinction
17428 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
17429 ** not want to.  But SQLite will only request a recursive mutex in
17430 ** cases where it really needs one.  If a faster non-recursive mutex
17431 ** implementation is available on the host platform, the mutex subsystem
17432 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
17433 **
17434 ** The other allowed parameters to sqlite3_mutex_alloc() each return
17435 ** a pointer to a static preexisting mutex.  Six static mutexes are
17436 ** used by the current version of SQLite.  Future versions of SQLite
17437 ** may add additional static mutexes.  Static mutexes are for internal
17438 ** use by SQLite only.  Applications that use SQLite mutexes should
17439 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
17440 ** SQLITE_MUTEX_RECURSIVE.
17441 **
17442 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
17443 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
17444 ** returns a different mutex on every call.  But for the static 
17445 ** mutex types, the same mutex is returned on every call that has
17446 ** the same type number.
17447 */
17448 static sqlite3_mutex *pthreadMutexAlloc(int iType){
17449   static sqlite3_mutex staticMutexes[] = {
17450     SQLITE3_MUTEX_INITIALIZER,
17451     SQLITE3_MUTEX_INITIALIZER,
17452     SQLITE3_MUTEX_INITIALIZER,
17453     SQLITE3_MUTEX_INITIALIZER,
17454     SQLITE3_MUTEX_INITIALIZER,
17455     SQLITE3_MUTEX_INITIALIZER
17456   };
17457   sqlite3_mutex *p;
17458   switch( iType ){
17459     case SQLITE_MUTEX_RECURSIVE: {
17460       p = sqlite3MallocZero( sizeof(*p) );
17461       if( p ){
17462 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
17463         /* If recursive mutexes are not available, we will have to
17464         ** build our own.  See below. */
17465         pthread_mutex_init(&p->mutex, 0);
17466 #else
17467         /* Use a recursive mutex if it is available */
17468         pthread_mutexattr_t recursiveAttr;
17469         pthread_mutexattr_init(&recursiveAttr);
17470         pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
17471         pthread_mutex_init(&p->mutex, &recursiveAttr);
17472         pthread_mutexattr_destroy(&recursiveAttr);
17473 #endif
17474 #if SQLITE_MUTEX_NREF
17475         p->id = iType;
17476 #endif
17477       }
17478       break;
17479     }
17480     case SQLITE_MUTEX_FAST: {
17481       p = sqlite3MallocZero( sizeof(*p) );
17482       if( p ){
17483 #if SQLITE_MUTEX_NREF
17484         p->id = iType;
17485 #endif
17486         pthread_mutex_init(&p->mutex, 0);
17487       }
17488       break;
17489     }
17490     default: {
17491       assert( iType-2 >= 0 );
17492       assert( iType-2 < ArraySize(staticMutexes) );
17493       p = &staticMutexes[iType-2];
17494 #if SQLITE_MUTEX_NREF
17495       p->id = iType;
17496 #endif
17497       break;
17498     }
17499   }
17500   return p;
17501 }
17502
17503
17504 /*
17505 ** This routine deallocates a previously
17506 ** allocated mutex.  SQLite is careful to deallocate every
17507 ** mutex that it allocates.
17508 */
17509 static void pthreadMutexFree(sqlite3_mutex *p){
17510   assert( p->nRef==0 );
17511   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
17512   pthread_mutex_destroy(&p->mutex);
17513   sqlite3_free(p);
17514 }
17515
17516 /*
17517 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
17518 ** to enter a mutex.  If another thread is already within the mutex,
17519 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
17520 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
17521 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
17522 ** be entered multiple times by the same thread.  In such cases the,
17523 ** mutex must be exited an equal number of times before another thread
17524 ** can enter.  If the same thread tries to enter any other kind of mutex
17525 ** more than once, the behavior is undefined.
17526 */
17527 static void pthreadMutexEnter(sqlite3_mutex *p){
17528   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
17529
17530 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
17531   /* If recursive mutexes are not available, then we have to grow
17532   ** our own.  This implementation assumes that pthread_equal()
17533   ** is atomic - that it cannot be deceived into thinking self
17534   ** and p->owner are equal if p->owner changes between two values
17535   ** that are not equal to self while the comparison is taking place.
17536   ** This implementation also assumes a coherent cache - that 
17537   ** separate processes cannot read different values from the same
17538   ** address at the same time.  If either of these two conditions
17539   ** are not met, then the mutexes will fail and problems will result.
17540   */
17541   {
17542     pthread_t self = pthread_self();
17543     if( p->nRef>0 && pthread_equal(p->owner, self) ){
17544       p->nRef++;
17545     }else{
17546       pthread_mutex_lock(&p->mutex);
17547       assert( p->nRef==0 );
17548       p->owner = self;
17549       p->nRef = 1;
17550     }
17551   }
17552 #else
17553   /* Use the built-in recursive mutexes if they are available.
17554   */
17555   pthread_mutex_lock(&p->mutex);
17556 #if SQLITE_MUTEX_NREF
17557   assert( p->nRef>0 || p->owner==0 );
17558   p->owner = pthread_self();
17559   p->nRef++;
17560 #endif
17561 #endif
17562
17563 #ifdef SQLITE_DEBUG
17564   if( p->trace ){
17565     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17566   }
17567 #endif
17568 }
17569 static int pthreadMutexTry(sqlite3_mutex *p){
17570   int rc;
17571   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
17572
17573 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
17574   /* If recursive mutexes are not available, then we have to grow
17575   ** our own.  This implementation assumes that pthread_equal()
17576   ** is atomic - that it cannot be deceived into thinking self
17577   ** and p->owner are equal if p->owner changes between two values
17578   ** that are not equal to self while the comparison is taking place.
17579   ** This implementation also assumes a coherent cache - that 
17580   ** separate processes cannot read different values from the same
17581   ** address at the same time.  If either of these two conditions
17582   ** are not met, then the mutexes will fail and problems will result.
17583   */
17584   {
17585     pthread_t self = pthread_self();
17586     if( p->nRef>0 && pthread_equal(p->owner, self) ){
17587       p->nRef++;
17588       rc = SQLITE_OK;
17589     }else if( pthread_mutex_trylock(&p->mutex)==0 ){
17590       assert( p->nRef==0 );
17591       p->owner = self;
17592       p->nRef = 1;
17593       rc = SQLITE_OK;
17594     }else{
17595       rc = SQLITE_BUSY;
17596     }
17597   }
17598 #else
17599   /* Use the built-in recursive mutexes if they are available.
17600   */
17601   if( pthread_mutex_trylock(&p->mutex)==0 ){
17602 #if SQLITE_MUTEX_NREF
17603     p->owner = pthread_self();
17604     p->nRef++;
17605 #endif
17606     rc = SQLITE_OK;
17607   }else{
17608     rc = SQLITE_BUSY;
17609   }
17610 #endif
17611
17612 #ifdef SQLITE_DEBUG
17613   if( rc==SQLITE_OK && p->trace ){
17614     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17615   }
17616 #endif
17617   return rc;
17618 }
17619
17620 /*
17621 ** The sqlite3_mutex_leave() routine exits a mutex that was
17622 ** previously entered by the same thread.  The behavior
17623 ** is undefined if the mutex is not currently entered or
17624 ** is not currently allocated.  SQLite will never do either.
17625 */
17626 static void pthreadMutexLeave(sqlite3_mutex *p){
17627   assert( pthreadMutexHeld(p) );
17628 #if SQLITE_MUTEX_NREF
17629   p->nRef--;
17630   if( p->nRef==0 ) p->owner = 0;
17631 #endif
17632   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
17633
17634 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
17635   if( p->nRef==0 ){
17636     pthread_mutex_unlock(&p->mutex);
17637   }
17638 #else
17639   pthread_mutex_unlock(&p->mutex);
17640 #endif
17641
17642 #ifdef SQLITE_DEBUG
17643   if( p->trace ){
17644     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17645   }
17646 #endif
17647 }
17648
17649 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
17650   static const sqlite3_mutex_methods sMutex = {
17651     pthreadMutexInit,
17652     pthreadMutexEnd,
17653     pthreadMutexAlloc,
17654     pthreadMutexFree,
17655     pthreadMutexEnter,
17656     pthreadMutexTry,
17657     pthreadMutexLeave,
17658 #ifdef SQLITE_DEBUG
17659     pthreadMutexHeld,
17660     pthreadMutexNotheld
17661 #else
17662     0,
17663     0
17664 #endif
17665   };
17666
17667   return &sMutex;
17668 }
17669
17670 #endif /* SQLITE_MUTEX_PTHREAD */
17671
17672 /************** End of mutex_unix.c ******************************************/
17673 /************** Begin file mutex_w32.c ***************************************/
17674 /*
17675 ** 2007 August 14
17676 **
17677 ** The author disclaims copyright to this source code.  In place of
17678 ** a legal notice, here is a blessing:
17679 **
17680 **    May you do good and not evil.
17681 **    May you find forgiveness for yourself and forgive others.
17682 **    May you share freely, never taking more than you give.
17683 **
17684 *************************************************************************
17685 ** This file contains the C functions that implement mutexes for win32
17686 */
17687
17688 /*
17689 ** The code in this file is only used if we are compiling multithreaded
17690 ** on a win32 system.
17691 */
17692 #ifdef SQLITE_MUTEX_W32
17693
17694 /*
17695 ** Each recursive mutex is an instance of the following structure.
17696 */
17697 struct sqlite3_mutex {
17698   CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
17699   int id;                    /* Mutex type */
17700 #ifdef SQLITE_DEBUG
17701   volatile int nRef;         /* Number of enterances */
17702   volatile DWORD owner;      /* Thread holding this mutex */
17703   int trace;                 /* True to trace changes */
17704 #endif
17705 };
17706 #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
17707 #ifdef SQLITE_DEBUG
17708 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0, 0 }
17709 #else
17710 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
17711 #endif
17712
17713 /*
17714 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
17715 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
17716 **
17717 ** Here is an interesting observation:  Win95, Win98, and WinME lack
17718 ** the LockFileEx() API.  But we can still statically link against that
17719 ** API as long as we don't call it win running Win95/98/ME.  A call to
17720 ** this routine is used to determine if the host is Win95/98/ME or
17721 ** WinNT/2K/XP so that we will know whether or not we can safely call
17722 ** the LockFileEx() API.
17723 **
17724 ** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
17725 ** which is only available if your application was compiled with 
17726 ** _WIN32_WINNT defined to a value >= 0x0400.  Currently, the only
17727 ** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef 
17728 ** this out as well.
17729 */
17730 #if 0
17731 #if SQLITE_OS_WINCE
17732 # define mutexIsNT()  (1)
17733 #else
17734   static int mutexIsNT(void){
17735     static int osType = 0;
17736     if( osType==0 ){
17737       OSVERSIONINFO sInfo;
17738       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
17739       GetVersionEx(&sInfo);
17740       osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
17741     }
17742     return osType==2;
17743   }
17744 #endif /* SQLITE_OS_WINCE */
17745 #endif
17746
17747 #ifdef SQLITE_DEBUG
17748 /*
17749 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17750 ** intended for use only inside assert() statements.
17751 */
17752 static int winMutexHeld(sqlite3_mutex *p){
17753   return p->nRef!=0 && p->owner==GetCurrentThreadId();
17754 }
17755 static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
17756   return p->nRef==0 || p->owner!=tid;
17757 }
17758 static int winMutexNotheld(sqlite3_mutex *p){
17759   DWORD tid = GetCurrentThreadId(); 
17760   return winMutexNotheld2(p, tid);
17761 }
17762 #endif
17763
17764
17765 /*
17766 ** Initialize and deinitialize the mutex subsystem.
17767 */
17768 static sqlite3_mutex winMutex_staticMutexes[6] = {
17769   SQLITE3_MUTEX_INITIALIZER,
17770   SQLITE3_MUTEX_INITIALIZER,
17771   SQLITE3_MUTEX_INITIALIZER,
17772   SQLITE3_MUTEX_INITIALIZER,
17773   SQLITE3_MUTEX_INITIALIZER,
17774   SQLITE3_MUTEX_INITIALIZER
17775 };
17776 static int winMutex_isInit = 0;
17777 /* As winMutexInit() and winMutexEnd() are called as part
17778 ** of the sqlite3_initialize and sqlite3_shutdown()
17779 ** processing, the "interlocked" magic is probably not
17780 ** strictly necessary.
17781 */
17782 static long winMutex_lock = 0;
17783
17784 static int winMutexInit(void){ 
17785   /* The first to increment to 1 does actual initialization */
17786   if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
17787     int i;
17788     for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
17789       InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
17790     }
17791     winMutex_isInit = 1;
17792   }else{
17793     /* Someone else is in the process of initing the static mutexes */
17794     while( !winMutex_isInit ){
17795       Sleep(1);
17796     }
17797   }
17798   return SQLITE_OK; 
17799 }
17800
17801 static int winMutexEnd(void){ 
17802   /* The first to decrement to 0 does actual shutdown 
17803   ** (which should be the last to shutdown.) */
17804   if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
17805     if( winMutex_isInit==1 ){
17806       int i;
17807       for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
17808         DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
17809       }
17810       winMutex_isInit = 0;
17811     }
17812   }
17813   return SQLITE_OK; 
17814 }
17815
17816 /*
17817 ** The sqlite3_mutex_alloc() routine allocates a new
17818 ** mutex and returns a pointer to it.  If it returns NULL
17819 ** that means that a mutex could not be allocated.  SQLite
17820 ** will unwind its stack and return an error.  The argument
17821 ** to sqlite3_mutex_alloc() is one of these integer constants:
17822 **
17823 ** <ul>
17824 ** <li>  SQLITE_MUTEX_FAST
17825 ** <li>  SQLITE_MUTEX_RECURSIVE
17826 ** <li>  SQLITE_MUTEX_STATIC_MASTER
17827 ** <li>  SQLITE_MUTEX_STATIC_MEM
17828 ** <li>  SQLITE_MUTEX_STATIC_MEM2
17829 ** <li>  SQLITE_MUTEX_STATIC_PRNG
17830 ** <li>  SQLITE_MUTEX_STATIC_LRU
17831 ** <li>  SQLITE_MUTEX_STATIC_PMEM
17832 ** </ul>
17833 **
17834 ** The first two constants cause sqlite3_mutex_alloc() to create
17835 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
17836 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
17837 ** The mutex implementation does not need to make a distinction
17838 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
17839 ** not want to.  But SQLite will only request a recursive mutex in
17840 ** cases where it really needs one.  If a faster non-recursive mutex
17841 ** implementation is available on the host platform, the mutex subsystem
17842 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
17843 **
17844 ** The other allowed parameters to sqlite3_mutex_alloc() each return
17845 ** a pointer to a static preexisting mutex.  Six static mutexes are
17846 ** used by the current version of SQLite.  Future versions of SQLite
17847 ** may add additional static mutexes.  Static mutexes are for internal
17848 ** use by SQLite only.  Applications that use SQLite mutexes should
17849 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
17850 ** SQLITE_MUTEX_RECURSIVE.
17851 **
17852 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
17853 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
17854 ** returns a different mutex on every call.  But for the static 
17855 ** mutex types, the same mutex is returned on every call that has
17856 ** the same type number.
17857 */
17858 static sqlite3_mutex *winMutexAlloc(int iType){
17859   sqlite3_mutex *p;
17860
17861   switch( iType ){
17862     case SQLITE_MUTEX_FAST:
17863     case SQLITE_MUTEX_RECURSIVE: {
17864       p = sqlite3MallocZero( sizeof(*p) );
17865       if( p ){  
17866 #ifdef SQLITE_DEBUG
17867         p->id = iType;
17868 #endif
17869         InitializeCriticalSection(&p->mutex);
17870       }
17871       break;
17872     }
17873     default: {
17874       assert( winMutex_isInit==1 );
17875       assert( iType-2 >= 0 );
17876       assert( iType-2 < ArraySize(winMutex_staticMutexes) );
17877       p = &winMutex_staticMutexes[iType-2];
17878 #ifdef SQLITE_DEBUG
17879       p->id = iType;
17880 #endif
17881       break;
17882     }
17883   }
17884   return p;
17885 }
17886
17887
17888 /*
17889 ** This routine deallocates a previously
17890 ** allocated mutex.  SQLite is careful to deallocate every
17891 ** mutex that it allocates.
17892 */
17893 static void winMutexFree(sqlite3_mutex *p){
17894   assert( p );
17895   assert( p->nRef==0 && p->owner==0 );
17896   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
17897   DeleteCriticalSection(&p->mutex);
17898   sqlite3_free(p);
17899 }
17900
17901 /*
17902 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
17903 ** to enter a mutex.  If another thread is already within the mutex,
17904 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
17905 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
17906 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
17907 ** be entered multiple times by the same thread.  In such cases the,
17908 ** mutex must be exited an equal number of times before another thread
17909 ** can enter.  If the same thread tries to enter any other kind of mutex
17910 ** more than once, the behavior is undefined.
17911 */
17912 static void winMutexEnter(sqlite3_mutex *p){
17913 #ifdef SQLITE_DEBUG
17914   DWORD tid = GetCurrentThreadId(); 
17915   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
17916 #endif
17917   EnterCriticalSection(&p->mutex);
17918 #ifdef SQLITE_DEBUG
17919   assert( p->nRef>0 || p->owner==0 );
17920   p->owner = tid; 
17921   p->nRef++;
17922   if( p->trace ){
17923     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17924   }
17925 #endif
17926 }
17927 static int winMutexTry(sqlite3_mutex *p){
17928 #ifndef NDEBUG
17929   DWORD tid = GetCurrentThreadId(); 
17930 #endif
17931   int rc = SQLITE_BUSY;
17932   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
17933   /*
17934   ** The sqlite3_mutex_try() routine is very rarely used, and when it
17935   ** is used it is merely an optimization.  So it is OK for it to always
17936   ** fail.  
17937   **
17938   ** The TryEnterCriticalSection() interface is only available on WinNT.
17939   ** And some windows compilers complain if you try to use it without
17940   ** first doing some #defines that prevent SQLite from building on Win98.
17941   ** For that reason, we will omit this optimization for now.  See
17942   ** ticket #2685.
17943   */
17944 #if 0
17945   if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
17946     p->owner = tid;
17947     p->nRef++;
17948     rc = SQLITE_OK;
17949   }
17950 #else
17951   UNUSED_PARAMETER(p);
17952 #endif
17953 #ifdef SQLITE_DEBUG
17954   if( rc==SQLITE_OK && p->trace ){
17955     printf("try mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17956   }
17957 #endif
17958   return rc;
17959 }
17960
17961 /*
17962 ** The sqlite3_mutex_leave() routine exits a mutex that was
17963 ** previously entered by the same thread.  The behavior
17964 ** is undefined if the mutex is not currently entered or
17965 ** is not currently allocated.  SQLite will never do either.
17966 */
17967 static void winMutexLeave(sqlite3_mutex *p){
17968 #ifndef NDEBUG
17969   DWORD tid = GetCurrentThreadId();
17970   assert( p->nRef>0 );
17971   assert( p->owner==tid );
17972   p->nRef--;
17973   if( p->nRef==0 ) p->owner = 0;
17974   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
17975 #endif
17976   LeaveCriticalSection(&p->mutex);
17977 #ifdef SQLITE_DEBUG
17978   if( p->trace ){
17979     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17980   }
17981 #endif
17982 }
17983
17984 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
17985   static const sqlite3_mutex_methods sMutex = {
17986     winMutexInit,
17987     winMutexEnd,
17988     winMutexAlloc,
17989     winMutexFree,
17990     winMutexEnter,
17991     winMutexTry,
17992     winMutexLeave,
17993 #ifdef SQLITE_DEBUG
17994     winMutexHeld,
17995     winMutexNotheld
17996 #else
17997     0,
17998     0
17999 #endif
18000   };
18001
18002   return &sMutex;
18003 }
18004 #endif /* SQLITE_MUTEX_W32 */
18005
18006 /************** End of mutex_w32.c *******************************************/
18007 /************** Begin file malloc.c ******************************************/
18008 /*
18009 ** 2001 September 15
18010 **
18011 ** The author disclaims copyright to this source code.  In place of
18012 ** a legal notice, here is a blessing:
18013 **
18014 **    May you do good and not evil.
18015 **    May you find forgiveness for yourself and forgive others.
18016 **    May you share freely, never taking more than you give.
18017 **
18018 *************************************************************************
18019 **
18020 ** Memory allocation functions used throughout sqlite.
18021 */
18022
18023 /*
18024 ** Attempt to release up to n bytes of non-essential memory currently
18025 ** held by SQLite. An example of non-essential memory is memory used to
18026 ** cache database pages that are not currently in use.
18027 */
18028 SQLITE_API int sqlite3_release_memory(int n){
18029 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
18030   return sqlite3PcacheReleaseMemory(n);
18031 #else
18032   /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
18033   ** is a no-op returning zero if SQLite is not compiled with
18034   ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
18035   UNUSED_PARAMETER(n);
18036   return 0;
18037 #endif
18038 }
18039
18040 /*
18041 ** An instance of the following object records the location of
18042 ** each unused scratch buffer.
18043 */
18044 typedef struct ScratchFreeslot {
18045   struct ScratchFreeslot *pNext;   /* Next unused scratch buffer */
18046 } ScratchFreeslot;
18047
18048 /*
18049 ** State information local to the memory allocation subsystem.
18050 */
18051 static SQLITE_WSD struct Mem0Global {
18052   sqlite3_mutex *mutex;         /* Mutex to serialize access */
18053
18054   /*
18055   ** The alarm callback and its arguments.  The mem0.mutex lock will
18056   ** be held while the callback is running.  Recursive calls into
18057   ** the memory subsystem are allowed, but no new callbacks will be
18058   ** issued.
18059   */
18060   sqlite3_int64 alarmThreshold;
18061   void (*alarmCallback)(void*, sqlite3_int64,int);
18062   void *alarmArg;
18063
18064   /*
18065   ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
18066   ** (so that a range test can be used to determine if an allocation
18067   ** being freed came from pScratch) and a pointer to the list of
18068   ** unused scratch allocations.
18069   */
18070   void *pScratchEnd;
18071   ScratchFreeslot *pScratchFree;
18072   u32 nScratchFree;
18073
18074   /*
18075   ** True if heap is nearly "full" where "full" is defined by the
18076   ** sqlite3_soft_heap_limit() setting.
18077   */
18078   int nearlyFull;
18079 } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
18080
18081 #define mem0 GLOBAL(struct Mem0Global, mem0)
18082
18083 /*
18084 ** This routine runs when the memory allocator sees that the
18085 ** total memory allocation is about to exceed the soft heap
18086 ** limit.
18087 */
18088 static void softHeapLimitEnforcer(
18089   void *NotUsed, 
18090   sqlite3_int64 NotUsed2,
18091   int allocSize
18092 ){
18093   UNUSED_PARAMETER2(NotUsed, NotUsed2);
18094   sqlite3_release_memory(allocSize);
18095 }
18096
18097 /*
18098 ** Change the alarm callback
18099 */
18100 static int sqlite3MemoryAlarm(
18101   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
18102   void *pArg,
18103   sqlite3_int64 iThreshold
18104 ){
18105   int nUsed;
18106   sqlite3_mutex_enter(mem0.mutex);
18107   mem0.alarmCallback = xCallback;
18108   mem0.alarmArg = pArg;
18109   mem0.alarmThreshold = iThreshold;
18110   nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
18111   mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
18112   sqlite3_mutex_leave(mem0.mutex);
18113   return SQLITE_OK;
18114 }
18115
18116 #ifndef SQLITE_OMIT_DEPRECATED
18117 /*
18118 ** Deprecated external interface.  Internal/core SQLite code
18119 ** should call sqlite3MemoryAlarm.
18120 */
18121 SQLITE_API int sqlite3_memory_alarm(
18122   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
18123   void *pArg,
18124   sqlite3_int64 iThreshold
18125 ){
18126   return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
18127 }
18128 #endif
18129
18130 /*
18131 ** Set the soft heap-size limit for the library. Passing a zero or 
18132 ** negative value indicates no limit.
18133 */
18134 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
18135   sqlite3_int64 priorLimit;
18136   sqlite3_int64 excess;
18137 #ifndef SQLITE_OMIT_AUTOINIT
18138   sqlite3_initialize();
18139 #endif
18140   sqlite3_mutex_enter(mem0.mutex);
18141   priorLimit = mem0.alarmThreshold;
18142   sqlite3_mutex_leave(mem0.mutex);
18143   if( n<0 ) return priorLimit;
18144   if( n>0 ){
18145     sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);
18146   }else{
18147     sqlite3MemoryAlarm(0, 0, 0);
18148   }
18149   excess = sqlite3_memory_used() - n;
18150   if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
18151   return priorLimit;
18152 }
18153 SQLITE_API void sqlite3_soft_heap_limit(int n){
18154   if( n<0 ) n = 0;
18155   sqlite3_soft_heap_limit64(n);
18156 }
18157
18158 /*
18159 ** Initialize the memory allocation subsystem.
18160 */
18161 SQLITE_PRIVATE int sqlite3MallocInit(void){
18162   if( sqlite3GlobalConfig.m.xMalloc==0 ){
18163     sqlite3MemSetDefault();
18164   }
18165   memset(&mem0, 0, sizeof(mem0));
18166   if( sqlite3GlobalConfig.bCoreMutex ){
18167     mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
18168   }
18169   if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
18170       && sqlite3GlobalConfig.nScratch>0 ){
18171     int i, n, sz;
18172     ScratchFreeslot *pSlot;
18173     sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
18174     sqlite3GlobalConfig.szScratch = sz;
18175     pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
18176     n = sqlite3GlobalConfig.nScratch;
18177     mem0.pScratchFree = pSlot;
18178     mem0.nScratchFree = n;
18179     for(i=0; i<n-1; i++){
18180       pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
18181       pSlot = pSlot->pNext;
18182     }
18183     pSlot->pNext = 0;
18184     mem0.pScratchEnd = (void*)&pSlot[1];
18185   }else{
18186     mem0.pScratchEnd = 0;
18187     sqlite3GlobalConfig.pScratch = 0;
18188     sqlite3GlobalConfig.szScratch = 0;
18189     sqlite3GlobalConfig.nScratch = 0;
18190   }
18191   if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
18192       || sqlite3GlobalConfig.nPage<1 ){
18193     sqlite3GlobalConfig.pPage = 0;
18194     sqlite3GlobalConfig.szPage = 0;
18195     sqlite3GlobalConfig.nPage = 0;
18196   }
18197   return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
18198 }
18199
18200 /*
18201 ** Return true if the heap is currently under memory pressure - in other
18202 ** words if the amount of heap used is close to the limit set by
18203 ** sqlite3_soft_heap_limit().
18204 */
18205 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
18206   return mem0.nearlyFull;
18207 }
18208
18209 /*
18210 ** Deinitialize the memory allocation subsystem.
18211 */
18212 SQLITE_PRIVATE void sqlite3MallocEnd(void){
18213   if( sqlite3GlobalConfig.m.xShutdown ){
18214     sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
18215   }
18216   memset(&mem0, 0, sizeof(mem0));
18217 }
18218
18219 /*
18220 ** Return the amount of memory currently checked out.
18221 */
18222 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
18223   int n, mx;
18224   sqlite3_int64 res;
18225   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
18226   res = (sqlite3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
18227   return res;
18228 }
18229
18230 /*
18231 ** Return the maximum amount of memory that has ever been
18232 ** checked out since either the beginning of this process
18233 ** or since the most recent reset.
18234 */
18235 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
18236   int n, mx;
18237   sqlite3_int64 res;
18238   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
18239   res = (sqlite3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
18240   return res;
18241 }
18242
18243 /*
18244 ** Trigger the alarm 
18245 */
18246 static void sqlite3MallocAlarm(int nByte){
18247   void (*xCallback)(void*,sqlite3_int64,int);
18248   sqlite3_int64 nowUsed;
18249   void *pArg;
18250   if( mem0.alarmCallback==0 ) return;
18251   xCallback = mem0.alarmCallback;
18252   nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
18253   pArg = mem0.alarmArg;
18254   mem0.alarmCallback = 0;
18255   sqlite3_mutex_leave(mem0.mutex);
18256   xCallback(pArg, nowUsed, nByte);
18257   sqlite3_mutex_enter(mem0.mutex);
18258   mem0.alarmCallback = xCallback;
18259   mem0.alarmArg = pArg;
18260 }
18261
18262 /*
18263 ** Do a memory allocation with statistics and alarms.  Assume the
18264 ** lock is already held.
18265 */
18266 static int mallocWithAlarm(int n, void **pp){
18267   int nFull;
18268   void *p;
18269   assert( sqlite3_mutex_held(mem0.mutex) );
18270   nFull = sqlite3GlobalConfig.m.xRoundup(n);
18271   sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
18272   if( mem0.alarmCallback!=0 ){
18273     int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
18274     if( nUsed >= mem0.alarmThreshold - nFull ){
18275       mem0.nearlyFull = 1;
18276       sqlite3MallocAlarm(nFull);
18277     }else{
18278       mem0.nearlyFull = 0;
18279     }
18280   }
18281   p = sqlite3GlobalConfig.m.xMalloc(nFull);
18282 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
18283   if( p==0 && mem0.alarmCallback ){
18284     sqlite3MallocAlarm(nFull);
18285     p = sqlite3GlobalConfig.m.xMalloc(nFull);
18286   }
18287 #endif
18288   if( p ){
18289     nFull = sqlite3MallocSize(p);
18290     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
18291     sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1);
18292   }
18293   *pp = p;
18294   return nFull;
18295 }
18296
18297 /*
18298 ** Allocate memory.  This routine is like sqlite3_malloc() except that it
18299 ** assumes the memory subsystem has already been initialized.
18300 */
18301 SQLITE_PRIVATE void *sqlite3Malloc(int n){
18302   void *p;
18303   if( n<=0               /* IMP: R-65312-04917 */ 
18304    || n>=0x7fffff00
18305   ){
18306     /* A memory allocation of a number of bytes which is near the maximum
18307     ** signed integer value might cause an integer overflow inside of the
18308     ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
18309     ** 255 bytes of overhead.  SQLite itself will never use anything near
18310     ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
18311     p = 0;
18312   }else if( sqlite3GlobalConfig.bMemstat ){
18313     sqlite3_mutex_enter(mem0.mutex);
18314     mallocWithAlarm(n, &p);
18315     sqlite3_mutex_leave(mem0.mutex);
18316   }else{
18317     p = sqlite3GlobalConfig.m.xMalloc(n);
18318   }
18319   assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-04675-44850 */
18320   return p;
18321 }
18322
18323 /*
18324 ** This version of the memory allocation is for use by the application.
18325 ** First make sure the memory subsystem is initialized, then do the
18326 ** allocation.
18327 */
18328 SQLITE_API void *sqlite3_malloc(int n){
18329 #ifndef SQLITE_OMIT_AUTOINIT
18330   if( sqlite3_initialize() ) return 0;
18331 #endif
18332   return sqlite3Malloc(n);
18333 }
18334
18335 /*
18336 ** Each thread may only have a single outstanding allocation from
18337 ** xScratchMalloc().  We verify this constraint in the single-threaded
18338 ** case by setting scratchAllocOut to 1 when an allocation
18339 ** is outstanding clearing it when the allocation is freed.
18340 */
18341 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
18342 static int scratchAllocOut = 0;
18343 #endif
18344
18345
18346 /*
18347 ** Allocate memory that is to be used and released right away.
18348 ** This routine is similar to alloca() in that it is not intended
18349 ** for situations where the memory might be held long-term.  This
18350 ** routine is intended to get memory to old large transient data
18351 ** structures that would not normally fit on the stack of an
18352 ** embedded processor.
18353 */
18354 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
18355   void *p;
18356   assert( n>0 );
18357
18358   sqlite3_mutex_enter(mem0.mutex);
18359   if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
18360     p = mem0.pScratchFree;
18361     mem0.pScratchFree = mem0.pScratchFree->pNext;
18362     mem0.nScratchFree--;
18363     sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
18364     sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
18365     sqlite3_mutex_leave(mem0.mutex);
18366   }else{
18367     if( sqlite3GlobalConfig.bMemstat ){
18368       sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
18369       n = mallocWithAlarm(n, &p);
18370       if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
18371       sqlite3_mutex_leave(mem0.mutex);
18372     }else{
18373       sqlite3_mutex_leave(mem0.mutex);
18374       p = sqlite3GlobalConfig.m.xMalloc(n);
18375     }
18376     sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
18377   }
18378   assert( sqlite3_mutex_notheld(mem0.mutex) );
18379
18380
18381 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
18382   /* Verify that no more than two scratch allocations per thread
18383   ** are outstanding at one time.  (This is only checked in the
18384   ** single-threaded case since checking in the multi-threaded case
18385   ** would be much more complicated.) */
18386   assert( scratchAllocOut<=1 );
18387   if( p ) scratchAllocOut++;
18388 #endif
18389
18390   return p;
18391 }
18392 SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
18393   if( p ){
18394
18395 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
18396     /* Verify that no more than two scratch allocation per thread
18397     ** is outstanding at one time.  (This is only checked in the
18398     ** single-threaded case since checking in the multi-threaded case
18399     ** would be much more complicated.) */
18400     assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
18401     scratchAllocOut--;
18402 #endif
18403
18404     if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
18405       /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
18406       ScratchFreeslot *pSlot;
18407       pSlot = (ScratchFreeslot*)p;
18408       sqlite3_mutex_enter(mem0.mutex);
18409       pSlot->pNext = mem0.pScratchFree;
18410       mem0.pScratchFree = pSlot;
18411       mem0.nScratchFree++;
18412       assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
18413       sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
18414       sqlite3_mutex_leave(mem0.mutex);
18415     }else{
18416       /* Release memory back to the heap */
18417       assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
18418       assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
18419       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
18420       if( sqlite3GlobalConfig.bMemstat ){
18421         int iSize = sqlite3MallocSize(p);
18422         sqlite3_mutex_enter(mem0.mutex);
18423         sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
18424         sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
18425         sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
18426         sqlite3GlobalConfig.m.xFree(p);
18427         sqlite3_mutex_leave(mem0.mutex);
18428       }else{
18429         sqlite3GlobalConfig.m.xFree(p);
18430       }
18431     }
18432   }
18433 }
18434
18435 /*
18436 ** TRUE if p is a lookaside memory allocation from db
18437 */
18438 #ifndef SQLITE_OMIT_LOOKASIDE
18439 static int isLookaside(sqlite3 *db, void *p){
18440   return p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
18441 }
18442 #else
18443 #define isLookaside(A,B) 0
18444 #endif
18445
18446 /*
18447 ** Return the size of a memory allocation previously obtained from
18448 ** sqlite3Malloc() or sqlite3_malloc().
18449 */
18450 SQLITE_PRIVATE int sqlite3MallocSize(void *p){
18451   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
18452   assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
18453   return sqlite3GlobalConfig.m.xSize(p);
18454 }
18455 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
18456   assert( db==0 || sqlite3_mutex_held(db->mutex) );
18457   if( db && isLookaside(db, p) ){
18458     return db->lookaside.sz;
18459   }else{
18460     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
18461     assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
18462     assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
18463     return sqlite3GlobalConfig.m.xSize(p);
18464   }
18465 }
18466
18467 /*
18468 ** Free memory previously obtained from sqlite3Malloc().
18469 */
18470 SQLITE_API void sqlite3_free(void *p){
18471   if( p==0 ) return;  /* IMP: R-49053-54554 */
18472   assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
18473   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
18474   if( sqlite3GlobalConfig.bMemstat ){
18475     sqlite3_mutex_enter(mem0.mutex);
18476     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
18477     sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
18478     sqlite3GlobalConfig.m.xFree(p);
18479     sqlite3_mutex_leave(mem0.mutex);
18480   }else{
18481     sqlite3GlobalConfig.m.xFree(p);
18482   }
18483 }
18484
18485 /*
18486 ** Free memory that might be associated with a particular database
18487 ** connection.
18488 */
18489 SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
18490   assert( db==0 || sqlite3_mutex_held(db->mutex) );
18491   if( db ){
18492     if( db->pnBytesFreed ){
18493       *db->pnBytesFreed += sqlite3DbMallocSize(db, p);
18494       return;
18495     }
18496     if( isLookaside(db, p) ){
18497       LookasideSlot *pBuf = (LookasideSlot*)p;
18498       pBuf->pNext = db->lookaside.pFree;
18499       db->lookaside.pFree = pBuf;
18500       db->lookaside.nOut--;
18501       return;
18502     }
18503   }
18504   assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
18505   assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
18506   assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
18507   sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
18508   sqlite3_free(p);
18509 }
18510
18511 /*
18512 ** Change the size of an existing memory allocation
18513 */
18514 SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
18515   int nOld, nNew, nDiff;
18516   void *pNew;
18517   if( pOld==0 ){
18518     return sqlite3Malloc(nBytes); /* IMP: R-28354-25769 */
18519   }
18520   if( nBytes<=0 ){
18521     sqlite3_free(pOld); /* IMP: R-31593-10574 */
18522     return 0;
18523   }
18524   if( nBytes>=0x7fffff00 ){
18525     /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
18526     return 0;
18527   }
18528   nOld = sqlite3MallocSize(pOld);
18529   /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
18530   ** argument to xRealloc is always a value returned by a prior call to
18531   ** xRoundup. */
18532   nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
18533   if( nOld==nNew ){
18534     pNew = pOld;
18535   }else if( sqlite3GlobalConfig.bMemstat ){
18536     sqlite3_mutex_enter(mem0.mutex);
18537     sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
18538     nDiff = nNew - nOld;
18539     if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >= 
18540           mem0.alarmThreshold-nDiff ){
18541       sqlite3MallocAlarm(nDiff);
18542     }
18543     assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
18544     assert( sqlite3MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
18545     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
18546     if( pNew==0 && mem0.alarmCallback ){
18547       sqlite3MallocAlarm(nBytes);
18548       pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
18549     }
18550     if( pNew ){
18551       nNew = sqlite3MallocSize(pNew);
18552       sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
18553     }
18554     sqlite3_mutex_leave(mem0.mutex);
18555   }else{
18556     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
18557   }
18558   assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */
18559   return pNew;
18560 }
18561
18562 /*
18563 ** The public interface to sqlite3Realloc.  Make sure that the memory
18564 ** subsystem is initialized prior to invoking sqliteRealloc.
18565 */
18566 SQLITE_API void *sqlite3_realloc(void *pOld, int n){
18567 #ifndef SQLITE_OMIT_AUTOINIT
18568   if( sqlite3_initialize() ) return 0;
18569 #endif
18570   return sqlite3Realloc(pOld, n);
18571 }
18572
18573
18574 /*
18575 ** Allocate and zero memory.
18576 */ 
18577 SQLITE_PRIVATE void *sqlite3MallocZero(int n){
18578   void *p = sqlite3Malloc(n);
18579   if( p ){
18580     memset(p, 0, n);
18581   }
18582   return p;
18583 }
18584
18585 /*
18586 ** Allocate and zero memory.  If the allocation fails, make
18587 ** the mallocFailed flag in the connection pointer.
18588 */
18589 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
18590   void *p = sqlite3DbMallocRaw(db, n);
18591   if( p ){
18592     memset(p, 0, n);
18593   }
18594   return p;
18595 }
18596
18597 /*
18598 ** Allocate and zero memory.  If the allocation fails, make
18599 ** the mallocFailed flag in the connection pointer.
18600 **
18601 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
18602 ** failure on the same database connection) then always return 0.
18603 ** Hence for a particular database connection, once malloc starts
18604 ** failing, it fails consistently until mallocFailed is reset.
18605 ** This is an important assumption.  There are many places in the
18606 ** code that do things like this:
18607 **
18608 **         int *a = (int*)sqlite3DbMallocRaw(db, 100);
18609 **         int *b = (int*)sqlite3DbMallocRaw(db, 200);
18610 **         if( b ) a[10] = 9;
18611 **
18612 ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
18613 ** that all prior mallocs (ex: "a") worked too.
18614 */
18615 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
18616   void *p;
18617   assert( db==0 || sqlite3_mutex_held(db->mutex) );
18618   assert( db==0 || db->pnBytesFreed==0 );
18619 #ifndef SQLITE_OMIT_LOOKASIDE
18620   if( db ){
18621     LookasideSlot *pBuf;
18622     if( db->mallocFailed ){
18623       return 0;
18624     }
18625     if( db->lookaside.bEnabled ){
18626       if( n>db->lookaside.sz ){
18627         db->lookaside.anStat[1]++;
18628       }else if( (pBuf = db->lookaside.pFree)==0 ){
18629         db->lookaside.anStat[2]++;
18630       }else{
18631         db->lookaside.pFree = pBuf->pNext;
18632         db->lookaside.nOut++;
18633         db->lookaside.anStat[0]++;
18634         if( db->lookaside.nOut>db->lookaside.mxOut ){
18635           db->lookaside.mxOut = db->lookaside.nOut;
18636         }
18637         return (void*)pBuf;
18638       }
18639     }
18640   }
18641 #else
18642   if( db && db->mallocFailed ){
18643     return 0;
18644   }
18645 #endif
18646   p = sqlite3Malloc(n);
18647   if( !p && db ){
18648     db->mallocFailed = 1;
18649   }
18650   sqlite3MemdebugSetType(p, MEMTYPE_DB |
18651          ((db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
18652   return p;
18653 }
18654
18655 /*
18656 ** Resize the block of memory pointed to by p to n bytes. If the
18657 ** resize fails, set the mallocFailed flag in the connection object.
18658 */
18659 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
18660   void *pNew = 0;
18661   assert( db!=0 );
18662   assert( sqlite3_mutex_held(db->mutex) );
18663   if( db->mallocFailed==0 ){
18664     if( p==0 ){
18665       return sqlite3DbMallocRaw(db, n);
18666     }
18667     if( isLookaside(db, p) ){
18668       if( n<=db->lookaside.sz ){
18669         return p;
18670       }
18671       pNew = sqlite3DbMallocRaw(db, n);
18672       if( pNew ){
18673         memcpy(pNew, p, db->lookaside.sz);
18674         sqlite3DbFree(db, p);
18675       }
18676     }else{
18677       assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
18678       assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
18679       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
18680       pNew = sqlite3_realloc(p, n);
18681       if( !pNew ){
18682         sqlite3MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP);
18683         db->mallocFailed = 1;
18684       }
18685       sqlite3MemdebugSetType(pNew, MEMTYPE_DB | 
18686             (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
18687     }
18688   }
18689   return pNew;
18690 }
18691
18692 /*
18693 ** Attempt to reallocate p.  If the reallocation fails, then free p
18694 ** and set the mallocFailed flag in the database connection.
18695 */
18696 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
18697   void *pNew;
18698   pNew = sqlite3DbRealloc(db, p, n);
18699   if( !pNew ){
18700     sqlite3DbFree(db, p);
18701   }
18702   return pNew;
18703 }
18704
18705 /*
18706 ** Make a copy of a string in memory obtained from sqliteMalloc(). These 
18707 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
18708 ** is because when memory debugging is turned on, these two functions are 
18709 ** called via macros that record the current file and line number in the
18710 ** ThreadData structure.
18711 */
18712 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
18713   char *zNew;
18714   size_t n;
18715   if( z==0 ){
18716     return 0;
18717   }
18718   n = sqlite3Strlen30(z) + 1;
18719   assert( (n&0x7fffffff)==n );
18720   zNew = sqlite3DbMallocRaw(db, (int)n);
18721   if( zNew ){
18722     memcpy(zNew, z, n);
18723   }
18724   return zNew;
18725 }
18726 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
18727   char *zNew;
18728   if( z==0 ){
18729     return 0;
18730   }
18731   assert( (n&0x7fffffff)==n );
18732   zNew = sqlite3DbMallocRaw(db, n+1);
18733   if( zNew ){
18734     memcpy(zNew, z, n);
18735     zNew[n] = 0;
18736   }
18737   return zNew;
18738 }
18739
18740 /*
18741 ** Create a string from the zFromat argument and the va_list that follows.
18742 ** Store the string in memory obtained from sqliteMalloc() and make *pz
18743 ** point to that string.
18744 */
18745 SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
18746   va_list ap;
18747   char *z;
18748
18749   va_start(ap, zFormat);
18750   z = sqlite3VMPrintf(db, zFormat, ap);
18751   va_end(ap);
18752   sqlite3DbFree(db, *pz);
18753   *pz = z;
18754 }
18755
18756
18757 /*
18758 ** This function must be called before exiting any API function (i.e. 
18759 ** returning control to the user) that has called sqlite3_malloc or
18760 ** sqlite3_realloc.
18761 **
18762 ** The returned value is normally a copy of the second argument to this
18763 ** function. However, if a malloc() failure has occurred since the previous
18764 ** invocation SQLITE_NOMEM is returned instead. 
18765 **
18766 ** If the first argument, db, is not NULL and a malloc() error has occurred,
18767 ** then the connection error-code (the value returned by sqlite3_errcode())
18768 ** is set to SQLITE_NOMEM.
18769 */
18770 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
18771   /* If the db handle is not NULL, then we must hold the connection handle
18772   ** mutex here. Otherwise the read (and possible write) of db->mallocFailed 
18773   ** is unsafe, as is the call to sqlite3Error().
18774   */
18775   assert( !db || sqlite3_mutex_held(db->mutex) );
18776   if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
18777     sqlite3Error(db, SQLITE_NOMEM, 0);
18778     db->mallocFailed = 0;
18779     rc = SQLITE_NOMEM;
18780   }
18781   return rc & (db ? db->errMask : 0xff);
18782 }
18783
18784 /************** End of malloc.c **********************************************/
18785 /************** Begin file printf.c ******************************************/
18786 /*
18787 ** The "printf" code that follows dates from the 1980's.  It is in
18788 ** the public domain.  The original comments are included here for
18789 ** completeness.  They are very out-of-date but might be useful as
18790 ** an historical reference.  Most of the "enhancements" have been backed
18791 ** out so that the functionality is now the same as standard printf().
18792 **
18793 **************************************************************************
18794 **
18795 ** The following modules is an enhanced replacement for the "printf" subroutines
18796 ** found in the standard C library.  The following enhancements are
18797 ** supported:
18798 **
18799 **      +  Additional functions.  The standard set of "printf" functions
18800 **         includes printf, fprintf, sprintf, vprintf, vfprintf, and
18801 **         vsprintf.  This module adds the following:
18802 **
18803 **           *  snprintf -- Works like sprintf, but has an extra argument
18804 **                          which is the size of the buffer written to.
18805 **
18806 **           *  mprintf --  Similar to sprintf.  Writes output to memory
18807 **                          obtained from malloc.
18808 **
18809 **           *  xprintf --  Calls a function to dispose of output.
18810 **
18811 **           *  nprintf --  No output, but returns the number of characters
18812 **                          that would have been output by printf.
18813 **
18814 **           *  A v- version (ex: vsnprintf) of every function is also
18815 **              supplied.
18816 **
18817 **      +  A few extensions to the formatting notation are supported:
18818 **
18819 **           *  The "=" flag (similar to "-") causes the output to be
18820 **              be centered in the appropriately sized field.
18821 **
18822 **           *  The %b field outputs an integer in binary notation.
18823 **
18824 **           *  The %c field now accepts a precision.  The character output
18825 **              is repeated by the number of times the precision specifies.
18826 **
18827 **           *  The %' field works like %c, but takes as its character the
18828 **              next character of the format string, instead of the next
18829 **              argument.  For example,  printf("%.78'-")  prints 78 minus
18830 **              signs, the same as  printf("%.78c",'-').
18831 **
18832 **      +  When compiled using GCC on a SPARC, this version of printf is
18833 **         faster than the library printf for SUN OS 4.1.
18834 **
18835 **      +  All functions are fully reentrant.
18836 **
18837 */
18838
18839 /*
18840 ** Conversion types fall into various categories as defined by the
18841 ** following enumeration.
18842 */
18843 #define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
18844 #define etFLOAT       2 /* Floating point.  %f */
18845 #define etEXP         3 /* Exponentional notation. %e and %E */
18846 #define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
18847 #define etSIZE        5 /* Return number of characters processed so far. %n */
18848 #define etSTRING      6 /* Strings. %s */
18849 #define etDYNSTRING   7 /* Dynamically allocated strings. %z */
18850 #define etPERCENT     8 /* Percent symbol. %% */
18851 #define etCHARX       9 /* Characters. %c */
18852 /* The rest are extensions, not normally found in printf() */
18853 #define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
18854 #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
18855                           NULL pointers replaced by SQL NULL.  %Q */
18856 #define etTOKEN      12 /* a pointer to a Token structure */
18857 #define etSRCLIST    13 /* a pointer to a SrcList */
18858 #define etPOINTER    14 /* The %p conversion */
18859 #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
18860 #define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
18861
18862 #define etINVALID     0 /* Any unrecognized conversion type */
18863
18864
18865 /*
18866 ** An "etByte" is an 8-bit unsigned value.
18867 */
18868 typedef unsigned char etByte;
18869
18870 /*
18871 ** Each builtin conversion character (ex: the 'd' in "%d") is described
18872 ** by an instance of the following structure
18873 */
18874 typedef struct et_info {   /* Information about each format field */
18875   char fmttype;            /* The format field code letter */
18876   etByte base;             /* The base for radix conversion */
18877   etByte flags;            /* One or more of FLAG_ constants below */
18878   etByte type;             /* Conversion paradigm */
18879   etByte charset;          /* Offset into aDigits[] of the digits string */
18880   etByte prefix;           /* Offset into aPrefix[] of the prefix string */
18881 } et_info;
18882
18883 /*
18884 ** Allowed values for et_info.flags
18885 */
18886 #define FLAG_SIGNED  1     /* True if the value to convert is signed */
18887 #define FLAG_INTERN  2     /* True if for internal use only */
18888 #define FLAG_STRING  4     /* Allow infinity precision */
18889
18890
18891 /*
18892 ** The following table is searched linearly, so it is good to put the
18893 ** most frequently used conversion types first.
18894 */
18895 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
18896 static const char aPrefix[] = "-x0\000X0";
18897 static const et_info fmtinfo[] = {
18898   {  'd', 10, 1, etRADIX,      0,  0 },
18899   {  's',  0, 4, etSTRING,     0,  0 },
18900   {  'g',  0, 1, etGENERIC,    30, 0 },
18901   {  'z',  0, 4, etDYNSTRING,  0,  0 },
18902   {  'q',  0, 4, etSQLESCAPE,  0,  0 },
18903   {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
18904   {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
18905   {  'c',  0, 0, etCHARX,      0,  0 },
18906   {  'o',  8, 0, etRADIX,      0,  2 },
18907   {  'u', 10, 0, etRADIX,      0,  0 },
18908   {  'x', 16, 0, etRADIX,      16, 1 },
18909   {  'X', 16, 0, etRADIX,      0,  4 },
18910 #ifndef SQLITE_OMIT_FLOATING_POINT
18911   {  'f',  0, 1, etFLOAT,      0,  0 },
18912   {  'e',  0, 1, etEXP,        30, 0 },
18913   {  'E',  0, 1, etEXP,        14, 0 },
18914   {  'G',  0, 1, etGENERIC,    14, 0 },
18915 #endif
18916   {  'i', 10, 1, etRADIX,      0,  0 },
18917   {  'n',  0, 0, etSIZE,       0,  0 },
18918   {  '%',  0, 0, etPERCENT,    0,  0 },
18919   {  'p', 16, 0, etPOINTER,    0,  1 },
18920
18921 /* All the rest have the FLAG_INTERN bit set and are thus for internal
18922 ** use only */
18923   {  'T',  0, 2, etTOKEN,      0,  0 },
18924   {  'S',  0, 2, etSRCLIST,    0,  0 },
18925   {  'r', 10, 3, etORDINAL,    0,  0 },
18926 };
18927
18928 /*
18929 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
18930 ** conversions will work.
18931 */
18932 #ifndef SQLITE_OMIT_FLOATING_POINT
18933 /*
18934 ** "*val" is a double such that 0.1 <= *val < 10.0
18935 ** Return the ascii code for the leading digit of *val, then
18936 ** multiply "*val" by 10.0 to renormalize.
18937 **
18938 ** Example:
18939 **     input:     *val = 3.14159
18940 **     output:    *val = 1.4159    function return = '3'
18941 **
18942 ** The counter *cnt is incremented each time.  After counter exceeds
18943 ** 16 (the number of significant digits in a 64-bit float) '0' is
18944 ** always returned.
18945 */
18946 static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
18947   int digit;
18948   LONGDOUBLE_TYPE d;
18949   if( (*cnt)++ >= 16 ) return '0';
18950   digit = (int)*val;
18951   d = digit;
18952   digit += '0';
18953   *val = (*val - d)*10.0;
18954   return (char)digit;
18955 }
18956 #endif /* SQLITE_OMIT_FLOATING_POINT */
18957
18958 /*
18959 ** Append N space characters to the given string buffer.
18960 */
18961 static void appendSpace(StrAccum *pAccum, int N){
18962   static const char zSpaces[] = "                             ";
18963   while( N>=(int)sizeof(zSpaces)-1 ){
18964     sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
18965     N -= sizeof(zSpaces)-1;
18966   }
18967   if( N>0 ){
18968     sqlite3StrAccumAppend(pAccum, zSpaces, N);
18969   }
18970 }
18971
18972 /*
18973 ** On machines with a small stack size, you can redefine the
18974 ** SQLITE_PRINT_BUF_SIZE to be less than 350.
18975 */
18976 #ifndef SQLITE_PRINT_BUF_SIZE
18977 # if defined(SQLITE_SMALL_STACK)
18978 #   define SQLITE_PRINT_BUF_SIZE 50
18979 # else
18980 #   define SQLITE_PRINT_BUF_SIZE 350
18981 # endif
18982 #endif
18983 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
18984
18985 /*
18986 ** The root program.  All variations call this core.
18987 **
18988 ** INPUTS:
18989 **   func   This is a pointer to a function taking three arguments
18990 **            1. A pointer to anything.  Same as the "arg" parameter.
18991 **            2. A pointer to the list of characters to be output
18992 **               (Note, this list is NOT null terminated.)
18993 **            3. An integer number of characters to be output.
18994 **               (Note: This number might be zero.)
18995 **
18996 **   arg    This is the pointer to anything which will be passed as the
18997 **          first argument to "func".  Use it for whatever you like.
18998 **
18999 **   fmt    This is the format string, as in the usual print.
19000 **
19001 **   ap     This is a pointer to a list of arguments.  Same as in
19002 **          vfprint.
19003 **
19004 ** OUTPUTS:
19005 **          The return value is the total number of characters sent to
19006 **          the function "func".  Returns -1 on a error.
19007 **
19008 ** Note that the order in which automatic variables are declared below
19009 ** seems to make a big difference in determining how fast this beast
19010 ** will run.
19011 */
19012 SQLITE_PRIVATE void sqlite3VXPrintf(
19013   StrAccum *pAccum,                  /* Accumulate results here */
19014   int useExtended,                   /* Allow extended %-conversions */
19015   const char *fmt,                   /* Format string */
19016   va_list ap                         /* arguments */
19017 ){
19018   int c;                     /* Next character in the format string */
19019   char *bufpt;               /* Pointer to the conversion buffer */
19020   int precision;             /* Precision of the current field */
19021   int length;                /* Length of the field */
19022   int idx;                   /* A general purpose loop counter */
19023   int width;                 /* Width of the current field */
19024   etByte flag_leftjustify;   /* True if "-" flag is present */
19025   etByte flag_plussign;      /* True if "+" flag is present */
19026   etByte flag_blanksign;     /* True if " " flag is present */
19027   etByte flag_alternateform; /* True if "#" flag is present */
19028   etByte flag_altform2;      /* True if "!" flag is present */
19029   etByte flag_zeropad;       /* True if field width constant starts with zero */
19030   etByte flag_long;          /* True if "l" flag is present */
19031   etByte flag_longlong;      /* True if the "ll" flag is present */
19032   etByte done;               /* Loop termination flag */
19033   sqlite_uint64 longvalue;   /* Value for integer types */
19034   LONGDOUBLE_TYPE realvalue; /* Value for real types */
19035   const et_info *infop;      /* Pointer to the appropriate info structure */
19036   char buf[etBUFSIZE];       /* Conversion buffer */
19037   char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
19038   etByte xtype = 0;          /* Conversion paradigm */
19039   char *zExtra;              /* Extra memory used for etTCLESCAPE conversions */
19040 #ifndef SQLITE_OMIT_FLOATING_POINT
19041   int  exp, e2;              /* exponent of real numbers */
19042   double rounder;            /* Used for rounding floating point values */
19043   etByte flag_dp;            /* True if decimal point should be shown */
19044   etByte flag_rtz;           /* True if trailing zeros should be removed */
19045   etByte flag_exp;           /* True to force display of the exponent */
19046   int nsd;                   /* Number of significant digits returned */
19047 #endif
19048
19049   length = 0;
19050   bufpt = 0;
19051   for(; (c=(*fmt))!=0; ++fmt){
19052     if( c!='%' ){
19053       int amt;
19054       bufpt = (char *)fmt;
19055       amt = 1;
19056       while( (c=(*++fmt))!='%' && c!=0 ) amt++;
19057       sqlite3StrAccumAppend(pAccum, bufpt, amt);
19058       if( c==0 ) break;
19059     }
19060     if( (c=(*++fmt))==0 ){
19061       sqlite3StrAccumAppend(pAccum, "%", 1);
19062       break;
19063     }
19064     /* Find out what flags are present */
19065     flag_leftjustify = flag_plussign = flag_blanksign = 
19066      flag_alternateform = flag_altform2 = flag_zeropad = 0;
19067     done = 0;
19068     do{
19069       switch( c ){
19070         case '-':   flag_leftjustify = 1;     break;
19071         case '+':   flag_plussign = 1;        break;
19072         case ' ':   flag_blanksign = 1;       break;
19073         case '#':   flag_alternateform = 1;   break;
19074         case '!':   flag_altform2 = 1;        break;
19075         case '0':   flag_zeropad = 1;         break;
19076         default:    done = 1;                 break;
19077       }
19078     }while( !done && (c=(*++fmt))!=0 );
19079     /* Get the field width */
19080     width = 0;
19081     if( c=='*' ){
19082       width = va_arg(ap,int);
19083       if( width<0 ){
19084         flag_leftjustify = 1;
19085         width = -width;
19086       }
19087       c = *++fmt;
19088     }else{
19089       while( c>='0' && c<='9' ){
19090         width = width*10 + c - '0';
19091         c = *++fmt;
19092       }
19093     }
19094     if( width > etBUFSIZE-10 ){
19095       width = etBUFSIZE-10;
19096     }
19097     /* Get the precision */
19098     if( c=='.' ){
19099       precision = 0;
19100       c = *++fmt;
19101       if( c=='*' ){
19102         precision = va_arg(ap,int);
19103         if( precision<0 ) precision = -precision;
19104         c = *++fmt;
19105       }else{
19106         while( c>='0' && c<='9' ){
19107           precision = precision*10 + c - '0';
19108           c = *++fmt;
19109         }
19110       }
19111     }else{
19112       precision = -1;
19113     }
19114     /* Get the conversion type modifier */
19115     if( c=='l' ){
19116       flag_long = 1;
19117       c = *++fmt;
19118       if( c=='l' ){
19119         flag_longlong = 1;
19120         c = *++fmt;
19121       }else{
19122         flag_longlong = 0;
19123       }
19124     }else{
19125       flag_long = flag_longlong = 0;
19126     }
19127     /* Fetch the info entry for the field */
19128     infop = &fmtinfo[0];
19129     xtype = etINVALID;
19130     for(idx=0; idx<ArraySize(fmtinfo); idx++){
19131       if( c==fmtinfo[idx].fmttype ){
19132         infop = &fmtinfo[idx];
19133         if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
19134           xtype = infop->type;
19135         }else{
19136           return;
19137         }
19138         break;
19139       }
19140     }
19141     zExtra = 0;
19142
19143
19144     /* Limit the precision to prevent overflowing buf[] during conversion */
19145     if( precision>etBUFSIZE-40 && (infop->flags & FLAG_STRING)==0 ){
19146       precision = etBUFSIZE-40;
19147     }
19148
19149     /*
19150     ** At this point, variables are initialized as follows:
19151     **
19152     **   flag_alternateform          TRUE if a '#' is present.
19153     **   flag_altform2               TRUE if a '!' is present.
19154     **   flag_plussign               TRUE if a '+' is present.
19155     **   flag_leftjustify            TRUE if a '-' is present or if the
19156     **                               field width was negative.
19157     **   flag_zeropad                TRUE if the width began with 0.
19158     **   flag_long                   TRUE if the letter 'l' (ell) prefixed
19159     **                               the conversion character.
19160     **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
19161     **                               the conversion character.
19162     **   flag_blanksign              TRUE if a ' ' is present.
19163     **   width                       The specified field width.  This is
19164     **                               always non-negative.  Zero is the default.
19165     **   precision                   The specified precision.  The default
19166     **                               is -1.
19167     **   xtype                       The class of the conversion.
19168     **   infop                       Pointer to the appropriate info struct.
19169     */
19170     switch( xtype ){
19171       case etPOINTER:
19172         flag_longlong = sizeof(char*)==sizeof(i64);
19173         flag_long = sizeof(char*)==sizeof(long int);
19174         /* Fall through into the next case */
19175       case etORDINAL:
19176       case etRADIX:
19177         if( infop->flags & FLAG_SIGNED ){
19178           i64 v;
19179           if( flag_longlong ){
19180             v = va_arg(ap,i64);
19181           }else if( flag_long ){
19182             v = va_arg(ap,long int);
19183           }else{
19184             v = va_arg(ap,int);
19185           }
19186           if( v<0 ){
19187             if( v==SMALLEST_INT64 ){
19188               longvalue = ((u64)1)<<63;
19189             }else{
19190               longvalue = -v;
19191             }
19192             prefix = '-';
19193           }else{
19194             longvalue = v;
19195             if( flag_plussign )        prefix = '+';
19196             else if( flag_blanksign )  prefix = ' ';
19197             else                       prefix = 0;
19198           }
19199         }else{
19200           if( flag_longlong ){
19201             longvalue = va_arg(ap,u64);
19202           }else if( flag_long ){
19203             longvalue = va_arg(ap,unsigned long int);
19204           }else{
19205             longvalue = va_arg(ap,unsigned int);
19206           }
19207           prefix = 0;
19208         }
19209         if( longvalue==0 ) flag_alternateform = 0;
19210         if( flag_zeropad && precision<width-(prefix!=0) ){
19211           precision = width-(prefix!=0);
19212         }
19213         bufpt = &buf[etBUFSIZE-1];
19214         if( xtype==etORDINAL ){
19215           static const char zOrd[] = "thstndrd";
19216           int x = (int)(longvalue % 10);
19217           if( x>=4 || (longvalue/10)%10==1 ){
19218             x = 0;
19219           }
19220           buf[etBUFSIZE-3] = zOrd[x*2];
19221           buf[etBUFSIZE-2] = zOrd[x*2+1];
19222           bufpt -= 2;
19223         }
19224         {
19225           register const char *cset;      /* Use registers for speed */
19226           register int base;
19227           cset = &aDigits[infop->charset];
19228           base = infop->base;
19229           do{                                           /* Convert to ascii */
19230             *(--bufpt) = cset[longvalue%base];
19231             longvalue = longvalue/base;
19232           }while( longvalue>0 );
19233         }
19234         length = (int)(&buf[etBUFSIZE-1]-bufpt);
19235         for(idx=precision-length; idx>0; idx--){
19236           *(--bufpt) = '0';                             /* Zero pad */
19237         }
19238         if( prefix ) *(--bufpt) = prefix;               /* Add sign */
19239         if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
19240           const char *pre;
19241           char x;
19242           pre = &aPrefix[infop->prefix];
19243           for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
19244         }
19245         length = (int)(&buf[etBUFSIZE-1]-bufpt);
19246         break;
19247       case etFLOAT:
19248       case etEXP:
19249       case etGENERIC:
19250         realvalue = va_arg(ap,double);
19251 #ifdef SQLITE_OMIT_FLOATING_POINT
19252         length = 0;
19253 #else
19254         if( precision<0 ) precision = 6;         /* Set default precision */
19255         if( precision>etBUFSIZE/2-10 ) precision = etBUFSIZE/2-10;
19256         if( realvalue<0.0 ){
19257           realvalue = -realvalue;
19258           prefix = '-';
19259         }else{
19260           if( flag_plussign )          prefix = '+';
19261           else if( flag_blanksign )    prefix = ' ';
19262           else                         prefix = 0;
19263         }
19264         if( xtype==etGENERIC && precision>0 ) precision--;
19265 #if 0
19266         /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */
19267         for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
19268 #else
19269         /* It makes more sense to use 0.5 */
19270         for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
19271 #endif
19272         if( xtype==etFLOAT ) realvalue += rounder;
19273         /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
19274         exp = 0;
19275         if( sqlite3IsNaN((double)realvalue) ){
19276           bufpt = "NaN";
19277           length = 3;
19278           break;
19279         }
19280         if( realvalue>0.0 ){
19281           while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
19282           while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
19283           while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
19284           while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
19285           while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
19286           if( exp>350 ){
19287             if( prefix=='-' ){
19288               bufpt = "-Inf";
19289             }else if( prefix=='+' ){
19290               bufpt = "+Inf";
19291             }else{
19292               bufpt = "Inf";
19293             }
19294             length = sqlite3Strlen30(bufpt);
19295             break;
19296           }
19297         }
19298         bufpt = buf;
19299         /*
19300         ** If the field type is etGENERIC, then convert to either etEXP
19301         ** or etFLOAT, as appropriate.
19302         */
19303         flag_exp = xtype==etEXP;
19304         if( xtype!=etFLOAT ){
19305           realvalue += rounder;
19306           if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
19307         }
19308         if( xtype==etGENERIC ){
19309           flag_rtz = !flag_alternateform;
19310           if( exp<-4 || exp>precision ){
19311             xtype = etEXP;
19312           }else{
19313             precision = precision - exp;
19314             xtype = etFLOAT;
19315           }
19316         }else{
19317           flag_rtz = 0;
19318         }
19319         if( xtype==etEXP ){
19320           e2 = 0;
19321         }else{
19322           e2 = exp;
19323         }
19324         nsd = 0;
19325         flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
19326         /* The sign in front of the number */
19327         if( prefix ){
19328           *(bufpt++) = prefix;
19329         }
19330         /* Digits prior to the decimal point */
19331         if( e2<0 ){
19332           *(bufpt++) = '0';
19333         }else{
19334           for(; e2>=0; e2--){
19335             *(bufpt++) = et_getdigit(&realvalue,&nsd);
19336           }
19337         }
19338         /* The decimal point */
19339         if( flag_dp ){
19340           *(bufpt++) = '.';
19341         }
19342         /* "0" digits after the decimal point but before the first
19343         ** significant digit of the number */
19344         for(e2++; e2<0; precision--, e2++){
19345           assert( precision>0 );
19346           *(bufpt++) = '0';
19347         }
19348         /* Significant digits after the decimal point */
19349         while( (precision--)>0 ){
19350           *(bufpt++) = et_getdigit(&realvalue,&nsd);
19351         }
19352         /* Remove trailing zeros and the "." if no digits follow the "." */
19353         if( flag_rtz && flag_dp ){
19354           while( bufpt[-1]=='0' ) *(--bufpt) = 0;
19355           assert( bufpt>buf );
19356           if( bufpt[-1]=='.' ){
19357             if( flag_altform2 ){
19358               *(bufpt++) = '0';
19359             }else{
19360               *(--bufpt) = 0;
19361             }
19362           }
19363         }
19364         /* Add the "eNNN" suffix */
19365         if( flag_exp || xtype==etEXP ){
19366           *(bufpt++) = aDigits[infop->charset];
19367           if( exp<0 ){
19368             *(bufpt++) = '-'; exp = -exp;
19369           }else{
19370             *(bufpt++) = '+';
19371           }
19372           if( exp>=100 ){
19373             *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
19374             exp %= 100;
19375           }
19376           *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
19377           *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
19378         }
19379         *bufpt = 0;
19380
19381         /* The converted number is in buf[] and zero terminated. Output it.
19382         ** Note that the number is in the usual order, not reversed as with
19383         ** integer conversions. */
19384         length = (int)(bufpt-buf);
19385         bufpt = buf;
19386
19387         /* Special case:  Add leading zeros if the flag_zeropad flag is
19388         ** set and we are not left justified */
19389         if( flag_zeropad && !flag_leftjustify && length < width){
19390           int i;
19391           int nPad = width - length;
19392           for(i=width; i>=nPad; i--){
19393             bufpt[i] = bufpt[i-nPad];
19394           }
19395           i = prefix!=0;
19396           while( nPad-- ) bufpt[i++] = '0';
19397           length = width;
19398         }
19399 #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
19400         break;
19401       case etSIZE:
19402         *(va_arg(ap,int*)) = pAccum->nChar;
19403         length = width = 0;
19404         break;
19405       case etPERCENT:
19406         buf[0] = '%';
19407         bufpt = buf;
19408         length = 1;
19409         break;
19410       case etCHARX:
19411         c = va_arg(ap,int);
19412         buf[0] = (char)c;
19413         if( precision>=0 ){
19414           for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
19415           length = precision;
19416         }else{
19417           length =1;
19418         }
19419         bufpt = buf;
19420         break;
19421       case etSTRING:
19422       case etDYNSTRING:
19423         bufpt = va_arg(ap,char*);
19424         if( bufpt==0 ){
19425           bufpt = "";
19426         }else if( xtype==etDYNSTRING ){
19427           zExtra = bufpt;
19428         }
19429         if( precision>=0 ){
19430           for(length=0; length<precision && bufpt[length]; length++){}
19431         }else{
19432           length = sqlite3Strlen30(bufpt);
19433         }
19434         break;
19435       case etSQLESCAPE:
19436       case etSQLESCAPE2:
19437       case etSQLESCAPE3: {
19438         int i, j, k, n, isnull;
19439         int needQuote;
19440         char ch;
19441         char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
19442         char *escarg = va_arg(ap,char*);
19443         isnull = escarg==0;
19444         if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
19445         k = precision;
19446         for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
19447           if( ch==q )  n++;
19448         }
19449         needQuote = !isnull && xtype==etSQLESCAPE2;
19450         n += i + 1 + needQuote*2;
19451         if( n>etBUFSIZE ){
19452           bufpt = zExtra = sqlite3Malloc( n );
19453           if( bufpt==0 ){
19454             pAccum->mallocFailed = 1;
19455             return;
19456           }
19457         }else{
19458           bufpt = buf;
19459         }
19460         j = 0;
19461         if( needQuote ) bufpt[j++] = q;
19462         k = i;
19463         for(i=0; i<k; i++){
19464           bufpt[j++] = ch = escarg[i];
19465           if( ch==q ) bufpt[j++] = ch;
19466         }
19467         if( needQuote ) bufpt[j++] = q;
19468         bufpt[j] = 0;
19469         length = j;
19470         /* The precision in %q and %Q means how many input characters to
19471         ** consume, not the length of the output...
19472         ** if( precision>=0 && precision<length ) length = precision; */
19473         break;
19474       }
19475       case etTOKEN: {
19476         Token *pToken = va_arg(ap, Token*);
19477         if( pToken ){
19478           sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
19479         }
19480         length = width = 0;
19481         break;
19482       }
19483       case etSRCLIST: {
19484         SrcList *pSrc = va_arg(ap, SrcList*);
19485         int k = va_arg(ap, int);
19486         struct SrcList_item *pItem = &pSrc->a[k];
19487         assert( k>=0 && k<pSrc->nSrc );
19488         if( pItem->zDatabase ){
19489           sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
19490           sqlite3StrAccumAppend(pAccum, ".", 1);
19491         }
19492         sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
19493         length = width = 0;
19494         break;
19495       }
19496       default: {
19497         assert( xtype==etINVALID );
19498         return;
19499       }
19500     }/* End switch over the format type */
19501     /*
19502     ** The text of the conversion is pointed to by "bufpt" and is
19503     ** "length" characters long.  The field width is "width".  Do
19504     ** the output.
19505     */
19506     if( !flag_leftjustify ){
19507       register int nspace;
19508       nspace = width-length;
19509       if( nspace>0 ){
19510         appendSpace(pAccum, nspace);
19511       }
19512     }
19513     if( length>0 ){
19514       sqlite3StrAccumAppend(pAccum, bufpt, length);
19515     }
19516     if( flag_leftjustify ){
19517       register int nspace;
19518       nspace = width-length;
19519       if( nspace>0 ){
19520         appendSpace(pAccum, nspace);
19521       }
19522     }
19523     if( zExtra ){
19524       sqlite3_free(zExtra);
19525     }
19526   }/* End for loop over the format string */
19527 } /* End of function */
19528
19529 /*
19530 ** Append N bytes of text from z to the StrAccum object.
19531 */
19532 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
19533   assert( z!=0 || N==0 );
19534   if( p->tooBig | p->mallocFailed ){
19535     testcase(p->tooBig);
19536     testcase(p->mallocFailed);
19537     return;
19538   }
19539   if( N<0 ){
19540     N = sqlite3Strlen30(z);
19541   }
19542   if( N==0 || NEVER(z==0) ){
19543     return;
19544   }
19545   if( p->nChar+N >= p->nAlloc ){
19546     char *zNew;
19547     if( !p->useMalloc ){
19548       p->tooBig = 1;
19549       N = p->nAlloc - p->nChar - 1;
19550       if( N<=0 ){
19551         return;
19552       }
19553     }else{
19554       char *zOld = (p->zText==p->zBase ? 0 : p->zText);
19555       i64 szNew = p->nChar;
19556       szNew += N + 1;
19557       if( szNew > p->mxAlloc ){
19558         sqlite3StrAccumReset(p);
19559         p->tooBig = 1;
19560         return;
19561       }else{
19562         p->nAlloc = (int)szNew;
19563       }
19564       if( p->useMalloc==1 ){
19565         zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
19566       }else{
19567         zNew = sqlite3_realloc(zOld, p->nAlloc);
19568       }
19569       if( zNew ){
19570         if( zOld==0 ) memcpy(zNew, p->zText, p->nChar);
19571         p->zText = zNew;
19572       }else{
19573         p->mallocFailed = 1;
19574         sqlite3StrAccumReset(p);
19575         return;
19576       }
19577     }
19578   }
19579   memcpy(&p->zText[p->nChar], z, N);
19580   p->nChar += N;
19581 }
19582
19583 /*
19584 ** Finish off a string by making sure it is zero-terminated.
19585 ** Return a pointer to the resulting string.  Return a NULL
19586 ** pointer if any kind of error was encountered.
19587 */
19588 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
19589   if( p->zText ){
19590     p->zText[p->nChar] = 0;
19591     if( p->useMalloc && p->zText==p->zBase ){
19592       if( p->useMalloc==1 ){
19593         p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
19594       }else{
19595         p->zText = sqlite3_malloc(p->nChar+1);
19596       }
19597       if( p->zText ){
19598         memcpy(p->zText, p->zBase, p->nChar+1);
19599       }else{
19600         p->mallocFailed = 1;
19601       }
19602     }
19603   }
19604   return p->zText;
19605 }
19606
19607 /*
19608 ** Reset an StrAccum string.  Reclaim all malloced memory.
19609 */
19610 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
19611   if( p->zText!=p->zBase ){
19612     if( p->useMalloc==1 ){
19613       sqlite3DbFree(p->db, p->zText);
19614     }else{
19615       sqlite3_free(p->zText);
19616     }
19617   }
19618   p->zText = 0;
19619 }
19620
19621 /*
19622 ** Initialize a string accumulator
19623 */
19624 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
19625   p->zText = p->zBase = zBase;
19626   p->db = 0;
19627   p->nChar = 0;
19628   p->nAlloc = n;
19629   p->mxAlloc = mx;
19630   p->useMalloc = 1;
19631   p->tooBig = 0;
19632   p->mallocFailed = 0;
19633 }
19634
19635 /*
19636 ** Print into memory obtained from sqliteMalloc().  Use the internal
19637 ** %-conversion extensions.
19638 */
19639 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
19640   char *z;
19641   char zBase[SQLITE_PRINT_BUF_SIZE];
19642   StrAccum acc;
19643   assert( db!=0 );
19644   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
19645                       db->aLimit[SQLITE_LIMIT_LENGTH]);
19646   acc.db = db;
19647   sqlite3VXPrintf(&acc, 1, zFormat, ap);
19648   z = sqlite3StrAccumFinish(&acc);
19649   if( acc.mallocFailed ){
19650     db->mallocFailed = 1;
19651   }
19652   return z;
19653 }
19654
19655 /*
19656 ** Print into memory obtained from sqliteMalloc().  Use the internal
19657 ** %-conversion extensions.
19658 */
19659 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
19660   va_list ap;
19661   char *z;
19662   va_start(ap, zFormat);
19663   z = sqlite3VMPrintf(db, zFormat, ap);
19664   va_end(ap);
19665   return z;
19666 }
19667
19668 /*
19669 ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
19670 ** the string and before returnning.  This routine is intended to be used
19671 ** to modify an existing string.  For example:
19672 **
19673 **       x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
19674 **
19675 */
19676 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
19677   va_list ap;
19678   char *z;
19679   va_start(ap, zFormat);
19680   z = sqlite3VMPrintf(db, zFormat, ap);
19681   va_end(ap);
19682   sqlite3DbFree(db, zStr);
19683   return z;
19684 }
19685
19686 /*
19687 ** Print into memory obtained from sqlite3_malloc().  Omit the internal
19688 ** %-conversion extensions.
19689 */
19690 SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
19691   char *z;
19692   char zBase[SQLITE_PRINT_BUF_SIZE];
19693   StrAccum acc;
19694 #ifndef SQLITE_OMIT_AUTOINIT
19695   if( sqlite3_initialize() ) return 0;
19696 #endif
19697   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
19698   acc.useMalloc = 2;
19699   sqlite3VXPrintf(&acc, 0, zFormat, ap);
19700   z = sqlite3StrAccumFinish(&acc);
19701   return z;
19702 }
19703
19704 /*
19705 ** Print into memory obtained from sqlite3_malloc()().  Omit the internal
19706 ** %-conversion extensions.
19707 */
19708 SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
19709   va_list ap;
19710   char *z;
19711 #ifndef SQLITE_OMIT_AUTOINIT
19712   if( sqlite3_initialize() ) return 0;
19713 #endif
19714   va_start(ap, zFormat);
19715   z = sqlite3_vmprintf(zFormat, ap);
19716   va_end(ap);
19717   return z;
19718 }
19719
19720 /*
19721 ** sqlite3_snprintf() works like snprintf() except that it ignores the
19722 ** current locale settings.  This is important for SQLite because we
19723 ** are not able to use a "," as the decimal point in place of "." as
19724 ** specified by some locales.
19725 **
19726 ** Oops:  The first two arguments of sqlite3_snprintf() are backwards
19727 ** from the snprintf() standard.  Unfortunately, it is too late to change
19728 ** this without breaking compatibility, so we just have to live with the
19729 ** mistake.
19730 **
19731 ** sqlite3_vsnprintf() is the varargs version.
19732 */
19733 SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
19734   StrAccum acc;
19735   if( n<=0 ) return zBuf;
19736   sqlite3StrAccumInit(&acc, zBuf, n, 0);
19737   acc.useMalloc = 0;
19738   sqlite3VXPrintf(&acc, 0, zFormat, ap);
19739   return sqlite3StrAccumFinish(&acc);
19740 }
19741 SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
19742   char *z;
19743   va_list ap;
19744   va_start(ap,zFormat);
19745   z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
19746   va_end(ap);
19747   return z;
19748 }
19749
19750 /*
19751 ** This is the routine that actually formats the sqlite3_log() message.
19752 ** We house it in a separate routine from sqlite3_log() to avoid using
19753 ** stack space on small-stack systems when logging is disabled.
19754 **
19755 ** sqlite3_log() must render into a static buffer.  It cannot dynamically
19756 ** allocate memory because it might be called while the memory allocator
19757 ** mutex is held.
19758 */
19759 static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
19760   StrAccum acc;                          /* String accumulator */
19761   char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
19762
19763   sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
19764   acc.useMalloc = 0;
19765   sqlite3VXPrintf(&acc, 0, zFormat, ap);
19766   sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
19767                            sqlite3StrAccumFinish(&acc));
19768 }
19769
19770 /*
19771 ** Format and write a message to the log if logging is enabled.
19772 */
19773 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
19774   va_list ap;                             /* Vararg list */
19775   if( sqlite3GlobalConfig.xLog ){
19776     va_start(ap, zFormat);
19777     renderLogMsg(iErrCode, zFormat, ap);
19778     va_end(ap);
19779   }
19780 }
19781
19782 #if defined(SQLITE_DEBUG)
19783 /*
19784 ** A version of printf() that understands %lld.  Used for debugging.
19785 ** The printf() built into some versions of windows does not understand %lld
19786 ** and segfaults if you give it a long long int.
19787 */
19788 SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
19789   va_list ap;
19790   StrAccum acc;
19791   char zBuf[500];
19792   sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
19793   acc.useMalloc = 0;
19794   va_start(ap,zFormat);
19795   sqlite3VXPrintf(&acc, 0, zFormat, ap);
19796   va_end(ap);
19797   sqlite3StrAccumFinish(&acc);
19798   fprintf(stdout,"%s", zBuf);
19799   fflush(stdout);
19800 }
19801 #endif
19802
19803 #ifndef SQLITE_OMIT_TRACE
19804 /*
19805 ** variable-argument wrapper around sqlite3VXPrintf().
19806 */
19807 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
19808   va_list ap;
19809   va_start(ap,zFormat);
19810   sqlite3VXPrintf(p, 1, zFormat, ap);
19811   va_end(ap);
19812 }
19813 #endif
19814
19815 /************** End of printf.c **********************************************/
19816 /************** Begin file random.c ******************************************/
19817 /*
19818 ** 2001 September 15
19819 **
19820 ** The author disclaims copyright to this source code.  In place of
19821 ** a legal notice, here is a blessing:
19822 **
19823 **    May you do good and not evil.
19824 **    May you find forgiveness for yourself and forgive others.
19825 **    May you share freely, never taking more than you give.
19826 **
19827 *************************************************************************
19828 ** This file contains code to implement a pseudo-random number
19829 ** generator (PRNG) for SQLite.
19830 **
19831 ** Random numbers are used by some of the database backends in order
19832 ** to generate random integer keys for tables or random filenames.
19833 */
19834
19835
19836 /* All threads share a single random number generator.
19837 ** This structure is the current state of the generator.
19838 */
19839 static SQLITE_WSD struct sqlite3PrngType {
19840   unsigned char isInit;          /* True if initialized */
19841   unsigned char i, j;            /* State variables */
19842   unsigned char s[256];          /* State variables */
19843 } sqlite3Prng;
19844
19845 /*
19846 ** Get a single 8-bit random value from the RC4 PRNG.  The Mutex
19847 ** must be held while executing this routine.
19848 **
19849 ** Why not just use a library random generator like lrand48() for this?
19850 ** Because the OP_NewRowid opcode in the VDBE depends on having a very
19851 ** good source of random numbers.  The lrand48() library function may
19852 ** well be good enough.  But maybe not.  Or maybe lrand48() has some
19853 ** subtle problems on some systems that could cause problems.  It is hard
19854 ** to know.  To minimize the risk of problems due to bad lrand48()
19855 ** implementations, SQLite uses this random number generator based
19856 ** on RC4, which we know works very well.
19857 **
19858 ** (Later):  Actually, OP_NewRowid does not depend on a good source of
19859 ** randomness any more.  But we will leave this code in all the same.
19860 */
19861 static u8 randomByte(void){
19862   unsigned char t;
19863
19864
19865   /* The "wsdPrng" macro will resolve to the pseudo-random number generator
19866   ** state vector.  If writable static data is unsupported on the target,
19867   ** we have to locate the state vector at run-time.  In the more common
19868   ** case where writable static data is supported, wsdPrng can refer directly
19869   ** to the "sqlite3Prng" state vector declared above.
19870   */
19871 #ifdef SQLITE_OMIT_WSD
19872   struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
19873 # define wsdPrng p[0]
19874 #else
19875 # define wsdPrng sqlite3Prng
19876 #endif
19877
19878
19879   /* Initialize the state of the random number generator once,
19880   ** the first time this routine is called.  The seed value does
19881   ** not need to contain a lot of randomness since we are not
19882   ** trying to do secure encryption or anything like that...
19883   **
19884   ** Nothing in this file or anywhere else in SQLite does any kind of
19885   ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
19886   ** number generator) not as an encryption device.
19887   */
19888   if( !wsdPrng.isInit ){
19889     int i;
19890     char k[256];
19891     wsdPrng.j = 0;
19892     wsdPrng.i = 0;
19893     sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
19894     for(i=0; i<256; i++){
19895       wsdPrng.s[i] = (u8)i;
19896     }
19897     for(i=0; i<256; i++){
19898       wsdPrng.j += wsdPrng.s[i] + k[i];
19899       t = wsdPrng.s[wsdPrng.j];
19900       wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
19901       wsdPrng.s[i] = t;
19902     }
19903     wsdPrng.isInit = 1;
19904   }
19905
19906   /* Generate and return single random byte
19907   */
19908   wsdPrng.i++;
19909   t = wsdPrng.s[wsdPrng.i];
19910   wsdPrng.j += t;
19911   wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
19912   wsdPrng.s[wsdPrng.j] = t;
19913   t += wsdPrng.s[wsdPrng.i];
19914   return wsdPrng.s[t];
19915 }
19916
19917 /*
19918 ** Return N random bytes.
19919 */
19920 SQLITE_API void sqlite3_randomness(int N, void *pBuf){
19921   unsigned char *zBuf = pBuf;
19922 #if SQLITE_THREADSAFE
19923   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
19924 #endif
19925   sqlite3_mutex_enter(mutex);
19926   while( N-- ){
19927     *(zBuf++) = randomByte();
19928   }
19929   sqlite3_mutex_leave(mutex);
19930 }
19931
19932 #ifndef SQLITE_OMIT_BUILTIN_TEST
19933 /*
19934 ** For testing purposes, we sometimes want to preserve the state of
19935 ** PRNG and restore the PRNG to its saved state at a later time, or
19936 ** to reset the PRNG to its initial state.  These routines accomplish
19937 ** those tasks.
19938 **
19939 ** The sqlite3_test_control() interface calls these routines to
19940 ** control the PRNG.
19941 */
19942 static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
19943 SQLITE_PRIVATE void sqlite3PrngSaveState(void){
19944   memcpy(
19945     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
19946     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
19947     sizeof(sqlite3Prng)
19948   );
19949 }
19950 SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
19951   memcpy(
19952     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
19953     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
19954     sizeof(sqlite3Prng)
19955   );
19956 }
19957 SQLITE_PRIVATE void sqlite3PrngResetState(void){
19958   GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
19959 }
19960 #endif /* SQLITE_OMIT_BUILTIN_TEST */
19961
19962 /************** End of random.c **********************************************/
19963 /************** Begin file utf.c *********************************************/
19964 /*
19965 ** 2004 April 13
19966 **
19967 ** The author disclaims copyright to this source code.  In place of
19968 ** a legal notice, here is a blessing:
19969 **
19970 **    May you do good and not evil.
19971 **    May you find forgiveness for yourself and forgive others.
19972 **    May you share freely, never taking more than you give.
19973 **
19974 *************************************************************************
19975 ** This file contains routines used to translate between UTF-8, 
19976 ** UTF-16, UTF-16BE, and UTF-16LE.
19977 **
19978 ** Notes on UTF-8:
19979 **
19980 **   Byte-0    Byte-1    Byte-2    Byte-3    Value
19981 **  0xxxxxxx                                 00000000 00000000 0xxxxxxx
19982 **  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
19983 **  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
19984 **  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
19985 **
19986 **
19987 ** Notes on UTF-16:  (with wwww+1==uuuuu)
19988 **
19989 **      Word-0               Word-1          Value
19990 **  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
19991 **  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
19992 **
19993 **
19994 ** BOM or Byte Order Mark:
19995 **     0xff 0xfe   little-endian utf-16 follows
19996 **     0xfe 0xff   big-endian utf-16 follows
19997 **
19998 */
19999
20000 #ifndef SQLITE_AMALGAMATION
20001 /*
20002 ** The following constant value is used by the SQLITE_BIGENDIAN and
20003 ** SQLITE_LITTLEENDIAN macros.
20004 */
20005 SQLITE_PRIVATE const int sqlite3one = 1;
20006 #endif /* SQLITE_AMALGAMATION */
20007
20008 /*
20009 ** This lookup table is used to help decode the first byte of
20010 ** a multi-byte UTF8 character.
20011 */
20012 static const unsigned char sqlite3Utf8Trans1[] = {
20013   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
20014   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
20015   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
20016   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
20017   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
20018   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
20019   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
20020   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
20021 };
20022
20023
20024 #define WRITE_UTF8(zOut, c) {                          \
20025   if( c<0x00080 ){                                     \
20026     *zOut++ = (u8)(c&0xFF);                            \
20027   }                                                    \
20028   else if( c<0x00800 ){                                \
20029     *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
20030     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
20031   }                                                    \
20032   else if( c<0x10000 ){                                \
20033     *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
20034     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
20035     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
20036   }else{                                               \
20037     *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
20038     *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
20039     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
20040     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
20041   }                                                    \
20042 }
20043
20044 #define WRITE_UTF16LE(zOut, c) {                                    \
20045   if( c<=0xFFFF ){                                                  \
20046     *zOut++ = (u8)(c&0x00FF);                                       \
20047     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
20048   }else{                                                            \
20049     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
20050     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
20051     *zOut++ = (u8)(c&0x00FF);                                       \
20052     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
20053   }                                                                 \
20054 }
20055
20056 #define WRITE_UTF16BE(zOut, c) {                                    \
20057   if( c<=0xFFFF ){                                                  \
20058     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
20059     *zOut++ = (u8)(c&0x00FF);                                       \
20060   }else{                                                            \
20061     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
20062     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
20063     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
20064     *zOut++ = (u8)(c&0x00FF);                                       \
20065   }                                                                 \
20066 }
20067
20068 #define READ_UTF16LE(zIn, TERM, c){                                   \
20069   c = (*zIn++);                                                       \
20070   c += ((*zIn++)<<8);                                                 \
20071   if( c>=0xD800 && c<0xE000 && TERM ){                                \
20072     int c2 = (*zIn++);                                                \
20073     c2 += ((*zIn++)<<8);                                              \
20074     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
20075   }                                                                   \
20076 }
20077
20078 #define READ_UTF16BE(zIn, TERM, c){                                   \
20079   c = ((*zIn++)<<8);                                                  \
20080   c += (*zIn++);                                                      \
20081   if( c>=0xD800 && c<0xE000 && TERM ){                                \
20082     int c2 = ((*zIn++)<<8);                                           \
20083     c2 += (*zIn++);                                                   \
20084     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
20085   }                                                                   \
20086 }
20087
20088 /*
20089 ** Translate a single UTF-8 character.  Return the unicode value.
20090 **
20091 ** During translation, assume that the byte that zTerm points
20092 ** is a 0x00.
20093 **
20094 ** Write a pointer to the next unread byte back into *pzNext.
20095 **
20096 ** Notes On Invalid UTF-8:
20097 **
20098 **  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
20099 **     be encoded as a multi-byte character.  Any multi-byte character that
20100 **     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
20101 **
20102 **  *  This routine never allows a UTF16 surrogate value to be encoded.
20103 **     If a multi-byte character attempts to encode a value between
20104 **     0xd800 and 0xe000 then it is rendered as 0xfffd.
20105 **
20106 **  *  Bytes in the range of 0x80 through 0xbf which occur as the first
20107 **     byte of a character are interpreted as single-byte characters
20108 **     and rendered as themselves even though they are technically
20109 **     invalid characters.
20110 **
20111 **  *  This routine accepts an infinite number of different UTF8 encodings
20112 **     for unicode values 0x80 and greater.  It do not change over-length
20113 **     encodings to 0xfffd as some systems recommend.
20114 */
20115 #define READ_UTF8(zIn, zTerm, c)                           \
20116   c = *(zIn++);                                            \
20117   if( c>=0xc0 ){                                           \
20118     c = sqlite3Utf8Trans1[c-0xc0];                         \
20119     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
20120       c = (c<<6) + (0x3f & *(zIn++));                      \
20121     }                                                      \
20122     if( c<0x80                                             \
20123         || (c&0xFFFFF800)==0xD800                          \
20124         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
20125   }
20126 SQLITE_PRIVATE u32 sqlite3Utf8Read(
20127   const unsigned char *zIn,       /* First byte of UTF-8 character */
20128   const unsigned char **pzNext    /* Write first byte past UTF-8 char here */
20129 ){
20130   unsigned int c;
20131
20132   /* Same as READ_UTF8() above but without the zTerm parameter.
20133   ** For this routine, we assume the UTF8 string is always zero-terminated.
20134   */
20135   c = *(zIn++);
20136   if( c>=0xc0 ){
20137     c = sqlite3Utf8Trans1[c-0xc0];
20138     while( (*zIn & 0xc0)==0x80 ){
20139       c = (c<<6) + (0x3f & *(zIn++));
20140     }
20141     if( c<0x80
20142         || (c&0xFFFFF800)==0xD800
20143         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
20144   }
20145   *pzNext = zIn;
20146   return c;
20147 }
20148
20149
20150
20151
20152 /*
20153 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
20154 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
20155 */ 
20156 /* #define TRANSLATE_TRACE 1 */
20157
20158 #ifndef SQLITE_OMIT_UTF16
20159 /*
20160 ** This routine transforms the internal text encoding used by pMem to
20161 ** desiredEnc. It is an error if the string is already of the desired
20162 ** encoding, or if *pMem does not contain a string value.
20163 */
20164 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
20165   int len;                    /* Maximum length of output string in bytes */
20166   unsigned char *zOut;                  /* Output buffer */
20167   unsigned char *zIn;                   /* Input iterator */
20168   unsigned char *zTerm;                 /* End of input */
20169   unsigned char *z;                     /* Output iterator */
20170   unsigned int c;
20171
20172   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
20173   assert( pMem->flags&MEM_Str );
20174   assert( pMem->enc!=desiredEnc );
20175   assert( pMem->enc!=0 );
20176   assert( pMem->n>=0 );
20177
20178 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
20179   {
20180     char zBuf[100];
20181     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
20182     fprintf(stderr, "INPUT:  %s\n", zBuf);
20183   }
20184 #endif
20185
20186   /* If the translation is between UTF-16 little and big endian, then 
20187   ** all that is required is to swap the byte order. This case is handled
20188   ** differently from the others.
20189   */
20190   if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
20191     u8 temp;
20192     int rc;
20193     rc = sqlite3VdbeMemMakeWriteable(pMem);
20194     if( rc!=SQLITE_OK ){
20195       assert( rc==SQLITE_NOMEM );
20196       return SQLITE_NOMEM;
20197     }
20198     zIn = (u8*)pMem->z;
20199     zTerm = &zIn[pMem->n&~1];
20200     while( zIn<zTerm ){
20201       temp = *zIn;
20202       *zIn = *(zIn+1);
20203       zIn++;
20204       *zIn++ = temp;
20205     }
20206     pMem->enc = desiredEnc;
20207     goto translate_out;
20208   }
20209
20210   /* Set len to the maximum number of bytes required in the output buffer. */
20211   if( desiredEnc==SQLITE_UTF8 ){
20212     /* When converting from UTF-16, the maximum growth results from
20213     ** translating a 2-byte character to a 4-byte UTF-8 character.
20214     ** A single byte is required for the output string
20215     ** nul-terminator.
20216     */
20217     pMem->n &= ~1;
20218     len = pMem->n * 2 + 1;
20219   }else{
20220     /* When converting from UTF-8 to UTF-16 the maximum growth is caused
20221     ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
20222     ** character. Two bytes are required in the output buffer for the
20223     ** nul-terminator.
20224     */
20225     len = pMem->n * 2 + 2;
20226   }
20227
20228   /* Set zIn to point at the start of the input buffer and zTerm to point 1
20229   ** byte past the end.
20230   **
20231   ** Variable zOut is set to point at the output buffer, space obtained
20232   ** from sqlite3_malloc().
20233   */
20234   zIn = (u8*)pMem->z;
20235   zTerm = &zIn[pMem->n];
20236   zOut = sqlite3DbMallocRaw(pMem->db, len);
20237   if( !zOut ){
20238     return SQLITE_NOMEM;
20239   }
20240   z = zOut;
20241
20242   if( pMem->enc==SQLITE_UTF8 ){
20243     if( desiredEnc==SQLITE_UTF16LE ){
20244       /* UTF-8 -> UTF-16 Little-endian */
20245       while( zIn<zTerm ){
20246         /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
20247         READ_UTF8(zIn, zTerm, c);
20248         WRITE_UTF16LE(z, c);
20249       }
20250     }else{
20251       assert( desiredEnc==SQLITE_UTF16BE );
20252       /* UTF-8 -> UTF-16 Big-endian */
20253       while( zIn<zTerm ){
20254         /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
20255         READ_UTF8(zIn, zTerm, c);
20256         WRITE_UTF16BE(z, c);
20257       }
20258     }
20259     pMem->n = (int)(z - zOut);
20260     *z++ = 0;
20261   }else{
20262     assert( desiredEnc==SQLITE_UTF8 );
20263     if( pMem->enc==SQLITE_UTF16LE ){
20264       /* UTF-16 Little-endian -> UTF-8 */
20265       while( zIn<zTerm ){
20266         READ_UTF16LE(zIn, zIn<zTerm, c); 
20267         WRITE_UTF8(z, c);
20268       }
20269     }else{
20270       /* UTF-16 Big-endian -> UTF-8 */
20271       while( zIn<zTerm ){
20272         READ_UTF16BE(zIn, zIn<zTerm, c); 
20273         WRITE_UTF8(z, c);
20274       }
20275     }
20276     pMem->n = (int)(z - zOut);
20277   }
20278   *z = 0;
20279   assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
20280
20281   sqlite3VdbeMemRelease(pMem);
20282   pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
20283   pMem->enc = desiredEnc;
20284   pMem->flags |= (MEM_Term|MEM_Dyn);
20285   pMem->z = (char*)zOut;
20286   pMem->zMalloc = pMem->z;
20287
20288 translate_out:
20289 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
20290   {
20291     char zBuf[100];
20292     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
20293     fprintf(stderr, "OUTPUT: %s\n", zBuf);
20294   }
20295 #endif
20296   return SQLITE_OK;
20297 }
20298
20299 /*
20300 ** This routine checks for a byte-order mark at the beginning of the 
20301 ** UTF-16 string stored in *pMem. If one is present, it is removed and
20302 ** the encoding of the Mem adjusted. This routine does not do any
20303 ** byte-swapping, it just sets Mem.enc appropriately.
20304 **
20305 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
20306 ** changed by this function.
20307 */
20308 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
20309   int rc = SQLITE_OK;
20310   u8 bom = 0;
20311
20312   assert( pMem->n>=0 );
20313   if( pMem->n>1 ){
20314     u8 b1 = *(u8 *)pMem->z;
20315     u8 b2 = *(((u8 *)pMem->z) + 1);
20316     if( b1==0xFE && b2==0xFF ){
20317       bom = SQLITE_UTF16BE;
20318     }
20319     if( b1==0xFF && b2==0xFE ){
20320       bom = SQLITE_UTF16LE;
20321     }
20322   }
20323   
20324   if( bom ){
20325     rc = sqlite3VdbeMemMakeWriteable(pMem);
20326     if( rc==SQLITE_OK ){
20327       pMem->n -= 2;
20328       memmove(pMem->z, &pMem->z[2], pMem->n);
20329       pMem->z[pMem->n] = '\0';
20330       pMem->z[pMem->n+1] = '\0';
20331       pMem->flags |= MEM_Term;
20332       pMem->enc = bom;
20333     }
20334   }
20335   return rc;
20336 }
20337 #endif /* SQLITE_OMIT_UTF16 */
20338
20339 /*
20340 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
20341 ** return the number of unicode characters in pZ up to (but not including)
20342 ** the first 0x00 byte. If nByte is not less than zero, return the
20343 ** number of unicode characters in the first nByte of pZ (or up to 
20344 ** the first 0x00, whichever comes first).
20345 */
20346 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
20347   int r = 0;
20348   const u8 *z = (const u8*)zIn;
20349   const u8 *zTerm;
20350   if( nByte>=0 ){
20351     zTerm = &z[nByte];
20352   }else{
20353     zTerm = (const u8*)(-1);
20354   }
20355   assert( z<=zTerm );
20356   while( *z!=0 && z<zTerm ){
20357     SQLITE_SKIP_UTF8(z);
20358     r++;
20359   }
20360   return r;
20361 }
20362
20363 /* This test function is not currently used by the automated test-suite. 
20364 ** Hence it is only available in debug builds.
20365 */
20366 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
20367 /*
20368 ** Translate UTF-8 to UTF-8.
20369 **
20370 ** This has the effect of making sure that the string is well-formed
20371 ** UTF-8.  Miscoded characters are removed.
20372 **
20373 ** The translation is done in-place and aborted if the output
20374 ** overruns the input.
20375 */
20376 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
20377   unsigned char *zOut = zIn;
20378   unsigned char *zStart = zIn;
20379   u32 c;
20380
20381   while( zIn[0] && zOut<=zIn ){
20382     c = sqlite3Utf8Read(zIn, (const u8**)&zIn);
20383     if( c!=0xfffd ){
20384       WRITE_UTF8(zOut, c);
20385     }
20386   }
20387   *zOut = 0;
20388   return (int)(zOut - zStart);
20389 }
20390 #endif
20391
20392 #ifndef SQLITE_OMIT_UTF16
20393 /*
20394 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
20395 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
20396 ** be freed by the calling function.
20397 **
20398 ** NULL is returned if there is an allocation error.
20399 */
20400 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
20401   Mem m;
20402   memset(&m, 0, sizeof(m));
20403   m.db = db;
20404   sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
20405   sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
20406   if( db->mallocFailed ){
20407     sqlite3VdbeMemRelease(&m);
20408     m.z = 0;
20409   }
20410   assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
20411   assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
20412   assert( (m.flags & MEM_Dyn)!=0 || db->mallocFailed );
20413   assert( m.z || db->mallocFailed );
20414   return m.z;
20415 }
20416
20417 /*
20418 ** Convert a UTF-8 string to the UTF-16 encoding specified by parameter
20419 ** enc. A pointer to the new string is returned, and the value of *pnOut
20420 ** is set to the length of the returned string in bytes. The call should
20421 ** arrange to call sqlite3DbFree() on the returned pointer when it is
20422 ** no longer required.
20423 ** 
20424 ** If a malloc failure occurs, NULL is returned and the db.mallocFailed
20425 ** flag set.
20426 */
20427 #ifdef SQLITE_ENABLE_STAT2
20428 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *db, u8 enc, char *z, int n, int *pnOut){
20429   Mem m;
20430   memset(&m, 0, sizeof(m));
20431   m.db = db;
20432   sqlite3VdbeMemSetStr(&m, z, n, SQLITE_UTF8, SQLITE_STATIC);
20433   if( sqlite3VdbeMemTranslate(&m, enc) ){
20434     assert( db->mallocFailed );
20435     return 0;
20436   }
20437   assert( m.z==m.zMalloc );
20438   *pnOut = m.n;
20439   return m.z;
20440 }
20441 #endif
20442
20443 /*
20444 ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
20445 ** Return the number of bytes in the first nChar unicode characters
20446 ** in pZ.  nChar must be non-negative.
20447 */
20448 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
20449   int c;
20450   unsigned char const *z = zIn;
20451   int n = 0;
20452   
20453   if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
20454     while( n<nChar ){
20455       READ_UTF16BE(z, 1, c);
20456       n++;
20457     }
20458   }else{
20459     while( n<nChar ){
20460       READ_UTF16LE(z, 1, c);
20461       n++;
20462     }
20463   }
20464   return (int)(z-(unsigned char const *)zIn);
20465 }
20466
20467 #if defined(SQLITE_TEST)
20468 /*
20469 ** This routine is called from the TCL test function "translate_selftest".
20470 ** It checks that the primitives for serializing and deserializing
20471 ** characters in each encoding are inverses of each other.
20472 */
20473 SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
20474   unsigned int i, t;
20475   unsigned char zBuf[20];
20476   unsigned char *z;
20477   int n;
20478   unsigned int c;
20479
20480   for(i=0; i<0x00110000; i++){
20481     z = zBuf;
20482     WRITE_UTF8(z, i);
20483     n = (int)(z-zBuf);
20484     assert( n>0 && n<=4 );
20485     z[0] = 0;
20486     z = zBuf;
20487     c = sqlite3Utf8Read(z, (const u8**)&z);
20488     t = i;
20489     if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
20490     if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
20491     assert( c==t );
20492     assert( (z-zBuf)==n );
20493   }
20494   for(i=0; i<0x00110000; i++){
20495     if( i>=0xD800 && i<0xE000 ) continue;
20496     z = zBuf;
20497     WRITE_UTF16LE(z, i);
20498     n = (int)(z-zBuf);
20499     assert( n>0 && n<=4 );
20500     z[0] = 0;
20501     z = zBuf;
20502     READ_UTF16LE(z, 1, c);
20503     assert( c==i );
20504     assert( (z-zBuf)==n );
20505   }
20506   for(i=0; i<0x00110000; i++){
20507     if( i>=0xD800 && i<0xE000 ) continue;
20508     z = zBuf;
20509     WRITE_UTF16BE(z, i);
20510     n = (int)(z-zBuf);
20511     assert( n>0 && n<=4 );
20512     z[0] = 0;
20513     z = zBuf;
20514     READ_UTF16BE(z, 1, c);
20515     assert( c==i );
20516     assert( (z-zBuf)==n );
20517   }
20518 }
20519 #endif /* SQLITE_TEST */
20520 #endif /* SQLITE_OMIT_UTF16 */
20521
20522 /************** End of utf.c *************************************************/
20523 /************** Begin file util.c ********************************************/
20524 /*
20525 ** 2001 September 15
20526 **
20527 ** The author disclaims copyright to this source code.  In place of
20528 ** a legal notice, here is a blessing:
20529 **
20530 **    May you do good and not evil.
20531 **    May you find forgiveness for yourself and forgive others.
20532 **    May you share freely, never taking more than you give.
20533 **
20534 *************************************************************************
20535 ** Utility functions used throughout sqlite.
20536 **
20537 ** This file contains functions for allocating memory, comparing
20538 ** strings, and stuff like that.
20539 **
20540 */
20541 #ifdef SQLITE_HAVE_ISNAN
20542 # include <math.h>
20543 #endif
20544
20545 /*
20546 ** Routine needed to support the testcase() macro.
20547 */
20548 #ifdef SQLITE_COVERAGE_TEST
20549 SQLITE_PRIVATE void sqlite3Coverage(int x){
20550   static unsigned dummy = 0;
20551   dummy += (unsigned)x;
20552 }
20553 #endif
20554
20555 #ifndef SQLITE_OMIT_FLOATING_POINT
20556 /*
20557 ** Return true if the floating point value is Not a Number (NaN).
20558 **
20559 ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
20560 ** Otherwise, we have our own implementation that works on most systems.
20561 */
20562 SQLITE_PRIVATE int sqlite3IsNaN(double x){
20563   int rc;   /* The value return */
20564 #if !defined(SQLITE_HAVE_ISNAN)
20565   /*
20566   ** Systems that support the isnan() library function should probably
20567   ** make use of it by compiling with -DSQLITE_HAVE_ISNAN.  But we have
20568   ** found that many systems do not have a working isnan() function so
20569   ** this implementation is provided as an alternative.
20570   **
20571   ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
20572   ** On the other hand, the use of -ffast-math comes with the following
20573   ** warning:
20574   **
20575   **      This option [-ffast-math] should never be turned on by any
20576   **      -O option since it can result in incorrect output for programs
20577   **      which depend on an exact implementation of IEEE or ISO 
20578   **      rules/specifications for math functions.
20579   **
20580   ** Under MSVC, this NaN test may fail if compiled with a floating-
20581   ** point precision mode other than /fp:precise.  From the MSDN 
20582   ** documentation:
20583   **
20584   **      The compiler [with /fp:precise] will properly handle comparisons 
20585   **      involving NaN. For example, x != x evaluates to true if x is NaN 
20586   **      ...
20587   */
20588 #ifdef __FAST_MATH__
20589 # error SQLite will not work correctly with the -ffast-math option of GCC.
20590 #endif
20591   volatile double y = x;
20592   volatile double z = y;
20593   rc = (y!=z);
20594 #else  /* if defined(SQLITE_HAVE_ISNAN) */
20595   rc = isnan(x);
20596 #endif /* SQLITE_HAVE_ISNAN */
20597   testcase( rc );
20598   return rc;
20599 }
20600 #endif /* SQLITE_OMIT_FLOATING_POINT */
20601
20602 /*
20603 ** Compute a string length that is limited to what can be stored in
20604 ** lower 30 bits of a 32-bit signed integer.
20605 **
20606 ** The value returned will never be negative.  Nor will it ever be greater
20607 ** than the actual length of the string.  For very long strings (greater
20608 ** than 1GiB) the value returned might be less than the true string length.
20609 */
20610 SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
20611   const char *z2 = z;
20612   if( z==0 ) return 0;
20613   while( *z2 ){ z2++; }
20614   return 0x3fffffff & (int)(z2 - z);
20615 }
20616
20617 /*
20618 ** Set the most recent error code and error string for the sqlite
20619 ** handle "db". The error code is set to "err_code".
20620 **
20621 ** If it is not NULL, string zFormat specifies the format of the
20622 ** error string in the style of the printf functions: The following
20623 ** format characters are allowed:
20624 **
20625 **      %s      Insert a string
20626 **      %z      A string that should be freed after use
20627 **      %d      Insert an integer
20628 **      %T      Insert a token
20629 **      %S      Insert the first element of a SrcList
20630 **
20631 ** zFormat and any string tokens that follow it are assumed to be
20632 ** encoded in UTF-8.
20633 **
20634 ** To clear the most recent error for sqlite handle "db", sqlite3Error
20635 ** should be called with err_code set to SQLITE_OK and zFormat set
20636 ** to NULL.
20637 */
20638 SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
20639   if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
20640     db->errCode = err_code;
20641     if( zFormat ){
20642       char *z;
20643       va_list ap;
20644       va_start(ap, zFormat);
20645       z = sqlite3VMPrintf(db, zFormat, ap);
20646       va_end(ap);
20647       sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
20648     }else{
20649       sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
20650     }
20651   }
20652 }
20653
20654 /*
20655 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
20656 ** The following formatting characters are allowed:
20657 **
20658 **      %s      Insert a string
20659 **      %z      A string that should be freed after use
20660 **      %d      Insert an integer
20661 **      %T      Insert a token
20662 **      %S      Insert the first element of a SrcList
20663 **
20664 ** This function should be used to report any error that occurs whilst
20665 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
20666 ** last thing the sqlite3_prepare() function does is copy the error
20667 ** stored by this function into the database handle using sqlite3Error().
20668 ** Function sqlite3Error() should be used during statement execution
20669 ** (sqlite3_step() etc.).
20670 */
20671 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
20672   char *zMsg;
20673   va_list ap;
20674   sqlite3 *db = pParse->db;
20675   va_start(ap, zFormat);
20676   zMsg = sqlite3VMPrintf(db, zFormat, ap);
20677   va_end(ap);
20678   if( db->suppressErr ){
20679     sqlite3DbFree(db, zMsg);
20680   }else{
20681     pParse->nErr++;
20682     sqlite3DbFree(db, pParse->zErrMsg);
20683     pParse->zErrMsg = zMsg;
20684     pParse->rc = SQLITE_ERROR;
20685   }
20686 }
20687
20688 /*
20689 ** Convert an SQL-style quoted string into a normal string by removing
20690 ** the quote characters.  The conversion is done in-place.  If the
20691 ** input does not begin with a quote character, then this routine
20692 ** is a no-op.
20693 **
20694 ** The input string must be zero-terminated.  A new zero-terminator
20695 ** is added to the dequoted string.
20696 **
20697 ** The return value is -1 if no dequoting occurs or the length of the
20698 ** dequoted string, exclusive of the zero terminator, if dequoting does
20699 ** occur.
20700 **
20701 ** 2002-Feb-14: This routine is extended to remove MS-Access style
20702 ** brackets from around identifers.  For example:  "[a-b-c]" becomes
20703 ** "a-b-c".
20704 */
20705 SQLITE_PRIVATE int sqlite3Dequote(char *z){
20706   char quote;
20707   int i, j;
20708   if( z==0 ) return -1;
20709   quote = z[0];
20710   switch( quote ){
20711     case '\'':  break;
20712     case '"':   break;
20713     case '`':   break;                /* For MySQL compatibility */
20714     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
20715     default:    return -1;
20716   }
20717   for(i=1, j=0; ALWAYS(z[i]); i++){
20718     if( z[i]==quote ){
20719       if( z[i+1]==quote ){
20720         z[j++] = quote;
20721         i++;
20722       }else{
20723         break;
20724       }
20725     }else{
20726       z[j++] = z[i];
20727     }
20728   }
20729   z[j] = 0;
20730   return j;
20731 }
20732
20733 /* Convenient short-hand */
20734 #define UpperToLower sqlite3UpperToLower
20735
20736 /*
20737 ** Some systems have stricmp().  Others have strcasecmp().  Because
20738 ** there is no consistency, we will define our own.
20739 **
20740 ** IMPLEMENTATION-OF: R-20522-24639 The sqlite3_strnicmp() API allows
20741 ** applications and extensions to compare the contents of two buffers
20742 ** containing UTF-8 strings in a case-independent fashion, using the same
20743 ** definition of case independence that SQLite uses internally when
20744 ** comparing identifiers.
20745 */
20746 SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
20747   register unsigned char *a, *b;
20748   a = (unsigned char *)zLeft;
20749   b = (unsigned char *)zRight;
20750   while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
20751   return UpperToLower[*a] - UpperToLower[*b];
20752 }
20753 SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
20754   register unsigned char *a, *b;
20755   a = (unsigned char *)zLeft;
20756   b = (unsigned char *)zRight;
20757   while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
20758   return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
20759 }
20760
20761 /*
20762 ** The string z[] is an text representation of a real number.
20763 ** Convert this string to a double and write it into *pResult.
20764 **
20765 ** The string z[] is length bytes in length (bytes, not characters) and
20766 ** uses the encoding enc.  The string is not necessarily zero-terminated.
20767 **
20768 ** Return TRUE if the result is a valid real number (or integer) and FALSE
20769 ** if the string is empty or contains extraneous text.  Valid numbers
20770 ** are in one of these formats:
20771 **
20772 **    [+-]digits[E[+-]digits]
20773 **    [+-]digits.[digits][E[+-]digits]
20774 **    [+-].digits[E[+-]digits]
20775 **
20776 ** Leading and trailing whitespace is ignored for the purpose of determining
20777 ** validity.
20778 **
20779 ** If some prefix of the input string is a valid number, this routine
20780 ** returns FALSE but it still converts the prefix and writes the result
20781 ** into *pResult.
20782 */
20783 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
20784 #ifndef SQLITE_OMIT_FLOATING_POINT
20785   int incr = (enc==SQLITE_UTF8?1:2);
20786   const char *zEnd = z + length;
20787   /* sign * significand * (10 ^ (esign * exponent)) */
20788   int sign = 1;    /* sign of significand */
20789   i64 s = 0;       /* significand */
20790   int d = 0;       /* adjust exponent for shifting decimal point */
20791   int esign = 1;   /* sign of exponent */
20792   int e = 0;       /* exponent */
20793   int eValid = 1;  /* True exponent is either not used or is well-formed */
20794   double result;
20795   int nDigits = 0;
20796
20797   *pResult = 0.0;   /* Default return value, in case of an error */
20798
20799   if( enc==SQLITE_UTF16BE ) z++;
20800
20801   /* skip leading spaces */
20802   while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
20803   if( z>=zEnd ) return 0;
20804
20805   /* get sign of significand */
20806   if( *z=='-' ){
20807     sign = -1;
20808     z+=incr;
20809   }else if( *z=='+' ){
20810     z+=incr;
20811   }
20812
20813   /* skip leading zeroes */
20814   while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
20815
20816   /* copy max significant digits to significand */
20817   while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
20818     s = s*10 + (*z - '0');
20819     z+=incr, nDigits++;
20820   }
20821
20822   /* skip non-significant significand digits
20823   ** (increase exponent by d to shift decimal left) */
20824   while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
20825   if( z>=zEnd ) goto do_atof_calc;
20826
20827   /* if decimal point is present */
20828   if( *z=='.' ){
20829     z+=incr;
20830     /* copy digits from after decimal to significand
20831     ** (decrease exponent by d to shift decimal right) */
20832     while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
20833       s = s*10 + (*z - '0');
20834       z+=incr, nDigits++, d--;
20835     }
20836     /* skip non-significant digits */
20837     while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
20838   }
20839   if( z>=zEnd ) goto do_atof_calc;
20840
20841   /* if exponent is present */
20842   if( *z=='e' || *z=='E' ){
20843     z+=incr;
20844     eValid = 0;
20845     if( z>=zEnd ) goto do_atof_calc;
20846     /* get sign of exponent */
20847     if( *z=='-' ){
20848       esign = -1;
20849       z+=incr;
20850     }else if( *z=='+' ){
20851       z+=incr;
20852     }
20853     /* copy digits to exponent */
20854     while( z<zEnd && sqlite3Isdigit(*z) ){
20855       e = e*10 + (*z - '0');
20856       z+=incr;
20857       eValid = 1;
20858     }
20859   }
20860
20861   /* skip trailing spaces */
20862   if( nDigits && eValid ){
20863     while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
20864   }
20865
20866 do_atof_calc:
20867   /* adjust exponent by d, and update sign */
20868   e = (e*esign) + d;
20869   if( e<0 ) {
20870     esign = -1;
20871     e *= -1;
20872   } else {
20873     esign = 1;
20874   }
20875
20876   /* if 0 significand */
20877   if( !s ) {
20878     /* In the IEEE 754 standard, zero is signed.
20879     ** Add the sign if we've seen at least one digit */
20880     result = (sign<0 && nDigits) ? -(double)0 : (double)0;
20881   } else {
20882     /* attempt to reduce exponent */
20883     if( esign>0 ){
20884       while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
20885     }else{
20886       while( !(s%10) && e>0 ) e--,s/=10;
20887     }
20888
20889     /* adjust the sign of significand */
20890     s = sign<0 ? -s : s;
20891
20892     /* if exponent, scale significand as appropriate
20893     ** and store in result. */
20894     if( e ){
20895       double scale = 1.0;
20896       /* attempt to handle extremely small/large numbers better */
20897       if( e>307 && e<342 ){
20898         while( e%308 ) { scale *= 1.0e+1; e -= 1; }
20899         if( esign<0 ){
20900           result = s / scale;
20901           result /= 1.0e+308;
20902         }else{
20903           result = s * scale;
20904           result *= 1.0e+308;
20905         }
20906       }else{
20907         /* 1.0e+22 is the largest power of 10 than can be 
20908         ** represented exactly. */
20909         while( e%22 ) { scale *= 1.0e+1; e -= 1; }
20910         while( e>0 ) { scale *= 1.0e+22; e -= 22; }
20911         if( esign<0 ){
20912           result = s / scale;
20913         }else{
20914           result = s * scale;
20915         }
20916       }
20917     } else {
20918       result = (double)s;
20919     }
20920   }
20921
20922   /* store the result */
20923   *pResult = result;
20924
20925   /* return true if number and no extra non-whitespace chracters after */
20926   return z>=zEnd && nDigits>0 && eValid;
20927 #else
20928   return !sqlite3Atoi64(z, pResult, length, enc);
20929 #endif /* SQLITE_OMIT_FLOATING_POINT */
20930 }
20931
20932 /*
20933 ** Compare the 19-character string zNum against the text representation
20934 ** value 2^63:  9223372036854775808.  Return negative, zero, or positive
20935 ** if zNum is less than, equal to, or greater than the string.
20936 ** Note that zNum must contain exactly 19 characters.
20937 **
20938 ** Unlike memcmp() this routine is guaranteed to return the difference
20939 ** in the values of the last digit if the only difference is in the
20940 ** last digit.  So, for example,
20941 **
20942 **      compare2pow63("9223372036854775800", 1)
20943 **
20944 ** will return -8.
20945 */
20946 static int compare2pow63(const char *zNum, int incr){
20947   int c = 0;
20948   int i;
20949                     /* 012345678901234567 */
20950   const char *pow63 = "922337203685477580";
20951   for(i=0; c==0 && i<18; i++){
20952     c = (zNum[i*incr]-pow63[i])*10;
20953   }
20954   if( c==0 ){
20955     c = zNum[18*incr] - '8';
20956     testcase( c==(-1) );
20957     testcase( c==0 );
20958     testcase( c==(+1) );
20959   }
20960   return c;
20961 }
20962
20963
20964 /*
20965 ** Convert zNum to a 64-bit signed integer.
20966 **
20967 ** If the zNum value is representable as a 64-bit twos-complement 
20968 ** integer, then write that value into *pNum and return 0.
20969 **
20970 ** If zNum is exactly 9223372036854665808, return 2.  This special
20971 ** case is broken out because while 9223372036854665808 cannot be a 
20972 ** signed 64-bit integer, its negative -9223372036854665808 can be.
20973 **
20974 ** If zNum is too big for a 64-bit integer and is not
20975 ** 9223372036854665808 then return 1.
20976 **
20977 ** length is the number of bytes in the string (bytes, not characters).
20978 ** The string is not necessarily zero-terminated.  The encoding is
20979 ** given by enc.
20980 */
20981 SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
20982   int incr = (enc==SQLITE_UTF8?1:2);
20983   u64 u = 0;
20984   int neg = 0; /* assume positive */
20985   int i;
20986   int c = 0;
20987   const char *zStart;
20988   const char *zEnd = zNum + length;
20989   if( enc==SQLITE_UTF16BE ) zNum++;
20990   while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
20991   if( zNum<zEnd ){
20992     if( *zNum=='-' ){
20993       neg = 1;
20994       zNum+=incr;
20995     }else if( *zNum=='+' ){
20996       zNum+=incr;
20997     }
20998   }
20999   zStart = zNum;
21000   while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
21001   for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
21002     u = u*10 + c - '0';
21003   }
21004   if( u>LARGEST_INT64 ){
21005     *pNum = SMALLEST_INT64;
21006   }else if( neg ){
21007     *pNum = -(i64)u;
21008   }else{
21009     *pNum = (i64)u;
21010   }
21011   testcase( i==18 );
21012   testcase( i==19 );
21013   testcase( i==20 );
21014   if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr ){
21015     /* zNum is empty or contains non-numeric text or is longer
21016     ** than 19 digits (thus guaranteeing that it is too large) */
21017     return 1;
21018   }else if( i<19*incr ){
21019     /* Less than 19 digits, so we know that it fits in 64 bits */
21020     assert( u<=LARGEST_INT64 );
21021     return 0;
21022   }else{
21023     /* zNum is a 19-digit numbers.  Compare it against 9223372036854775808. */
21024     c = compare2pow63(zNum, incr);
21025     if( c<0 ){
21026       /* zNum is less than 9223372036854775808 so it fits */
21027       assert( u<=LARGEST_INT64 );
21028       return 0;
21029     }else if( c>0 ){
21030       /* zNum is greater than 9223372036854775808 so it overflows */
21031       return 1;
21032     }else{
21033       /* zNum is exactly 9223372036854775808.  Fits if negative.  The
21034       ** special case 2 overflow if positive */
21035       assert( u-1==LARGEST_INT64 );
21036       assert( (*pNum)==SMALLEST_INT64 );
21037       return neg ? 0 : 2;
21038     }
21039   }
21040 }
21041
21042 /*
21043 ** If zNum represents an integer that will fit in 32-bits, then set
21044 ** *pValue to that integer and return true.  Otherwise return false.
21045 **
21046 ** Any non-numeric characters that following zNum are ignored.
21047 ** This is different from sqlite3Atoi64() which requires the
21048 ** input number to be zero-terminated.
21049 */
21050 SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
21051   sqlite_int64 v = 0;
21052   int i, c;
21053   int neg = 0;
21054   if( zNum[0]=='-' ){
21055     neg = 1;
21056     zNum++;
21057   }else if( zNum[0]=='+' ){
21058     zNum++;
21059   }
21060   while( zNum[0]=='0' ) zNum++;
21061   for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
21062     v = v*10 + c;
21063   }
21064
21065   /* The longest decimal representation of a 32 bit integer is 10 digits:
21066   **
21067   **             1234567890
21068   **     2^31 -> 2147483648
21069   */
21070   testcase( i==10 );
21071   if( i>10 ){
21072     return 0;
21073   }
21074   testcase( v-neg==2147483647 );
21075   if( v-neg>2147483647 ){
21076     return 0;
21077   }
21078   if( neg ){
21079     v = -v;
21080   }
21081   *pValue = (int)v;
21082   return 1;
21083 }
21084
21085 /*
21086 ** Return a 32-bit integer value extracted from a string.  If the
21087 ** string is not an integer, just return 0.
21088 */
21089 SQLITE_PRIVATE int sqlite3Atoi(const char *z){
21090   int x = 0;
21091   if( z ) sqlite3GetInt32(z, &x);
21092   return x;
21093 }
21094
21095 /*
21096 ** The variable-length integer encoding is as follows:
21097 **
21098 ** KEY:
21099 **         A = 0xxxxxxx    7 bits of data and one flag bit
21100 **         B = 1xxxxxxx    7 bits of data and one flag bit
21101 **         C = xxxxxxxx    8 bits of data
21102 **
21103 **  7 bits - A
21104 ** 14 bits - BA
21105 ** 21 bits - BBA
21106 ** 28 bits - BBBA
21107 ** 35 bits - BBBBA
21108 ** 42 bits - BBBBBA
21109 ** 49 bits - BBBBBBA
21110 ** 56 bits - BBBBBBBA
21111 ** 64 bits - BBBBBBBBC
21112 */
21113
21114 /*
21115 ** Write a 64-bit variable-length integer to memory starting at p[0].
21116 ** The length of data write will be between 1 and 9 bytes.  The number
21117 ** of bytes written is returned.
21118 **
21119 ** A variable-length integer consists of the lower 7 bits of each byte
21120 ** for all bytes that have the 8th bit set and one byte with the 8th
21121 ** bit clear.  Except, if we get to the 9th byte, it stores the full
21122 ** 8 bits and is the last byte.
21123 */
21124 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
21125   int i, j, n;
21126   u8 buf[10];
21127   if( v & (((u64)0xff000000)<<32) ){
21128     p[8] = (u8)v;
21129     v >>= 8;
21130     for(i=7; i>=0; i--){
21131       p[i] = (u8)((v & 0x7f) | 0x80);
21132       v >>= 7;
21133     }
21134     return 9;
21135   }    
21136   n = 0;
21137   do{
21138     buf[n++] = (u8)((v & 0x7f) | 0x80);
21139     v >>= 7;
21140   }while( v!=0 );
21141   buf[0] &= 0x7f;
21142   assert( n<=9 );
21143   for(i=0, j=n-1; j>=0; j--, i++){
21144     p[i] = buf[j];
21145   }
21146   return n;
21147 }
21148
21149 /*
21150 ** This routine is a faster version of sqlite3PutVarint() that only
21151 ** works for 32-bit positive integers and which is optimized for
21152 ** the common case of small integers.  A MACRO version, putVarint32,
21153 ** is provided which inlines the single-byte case.  All code should use
21154 ** the MACRO version as this function assumes the single-byte case has
21155 ** already been handled.
21156 */
21157 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
21158 #ifndef putVarint32
21159   if( (v & ~0x7f)==0 ){
21160     p[0] = v;
21161     return 1;
21162   }
21163 #endif
21164   if( (v & ~0x3fff)==0 ){
21165     p[0] = (u8)((v>>7) | 0x80);
21166     p[1] = (u8)(v & 0x7f);
21167     return 2;
21168   }
21169   return sqlite3PutVarint(p, v);
21170 }
21171
21172 /*
21173 ** Bitmasks used by sqlite3GetVarint().  These precomputed constants
21174 ** are defined here rather than simply putting the constant expressions
21175 ** inline in order to work around bugs in the RVT compiler.
21176 **
21177 ** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
21178 **
21179 ** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
21180 */
21181 #define SLOT_2_0     0x001fc07f
21182 #define SLOT_4_2_0   0xf01fc07f
21183
21184
21185 /*
21186 ** Read a 64-bit variable-length integer from memory starting at p[0].
21187 ** Return the number of bytes read.  The value is stored in *v.
21188 */
21189 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
21190   u32 a,b,s;
21191
21192   a = *p;
21193   /* a: p0 (unmasked) */
21194   if (!(a&0x80))
21195   {
21196     *v = a;
21197     return 1;
21198   }
21199
21200   p++;
21201   b = *p;
21202   /* b: p1 (unmasked) */
21203   if (!(b&0x80))
21204   {
21205     a &= 0x7f;
21206     a = a<<7;
21207     a |= b;
21208     *v = a;
21209     return 2;
21210   }
21211
21212   /* Verify that constants are precomputed correctly */
21213   assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
21214   assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
21215
21216   p++;
21217   a = a<<14;
21218   a |= *p;
21219   /* a: p0<<14 | p2 (unmasked) */
21220   if (!(a&0x80))
21221   {
21222     a &= SLOT_2_0;
21223     b &= 0x7f;
21224     b = b<<7;
21225     a |= b;
21226     *v = a;
21227     return 3;
21228   }
21229
21230   /* CSE1 from below */
21231   a &= SLOT_2_0;
21232   p++;
21233   b = b<<14;
21234   b |= *p;
21235   /* b: p1<<14 | p3 (unmasked) */
21236   if (!(b&0x80))
21237   {
21238     b &= SLOT_2_0;
21239     /* moved CSE1 up */
21240     /* a &= (0x7f<<14)|(0x7f); */
21241     a = a<<7;
21242     a |= b;
21243     *v = a;
21244     return 4;
21245   }
21246
21247   /* a: p0<<14 | p2 (masked) */
21248   /* b: p1<<14 | p3 (unmasked) */
21249   /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
21250   /* moved CSE1 up */
21251   /* a &= (0x7f<<14)|(0x7f); */
21252   b &= SLOT_2_0;
21253   s = a;
21254   /* s: p0<<14 | p2 (masked) */
21255
21256   p++;
21257   a = a<<14;
21258   a |= *p;
21259   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
21260   if (!(a&0x80))
21261   {
21262     /* we can skip these cause they were (effectively) done above in calc'ing s */
21263     /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
21264     /* b &= (0x7f<<14)|(0x7f); */
21265     b = b<<7;
21266     a |= b;
21267     s = s>>18;
21268     *v = ((u64)s)<<32 | a;
21269     return 5;
21270   }
21271
21272   /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
21273   s = s<<7;
21274   s |= b;
21275   /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
21276
21277   p++;
21278   b = b<<14;
21279   b |= *p;
21280   /* b: p1<<28 | p3<<14 | p5 (unmasked) */
21281   if (!(b&0x80))
21282   {
21283     /* we can skip this cause it was (effectively) done above in calc'ing s */
21284     /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
21285     a &= SLOT_2_0;
21286     a = a<<7;
21287     a |= b;
21288     s = s>>18;
21289     *v = ((u64)s)<<32 | a;
21290     return 6;
21291   }
21292
21293   p++;
21294   a = a<<14;
21295   a |= *p;
21296   /* a: p2<<28 | p4<<14 | p6 (unmasked) */
21297   if (!(a&0x80))
21298   {
21299     a &= SLOT_4_2_0;
21300     b &= SLOT_2_0;
21301     b = b<<7;
21302     a |= b;
21303     s = s>>11;
21304     *v = ((u64)s)<<32 | a;
21305     return 7;
21306   }
21307
21308   /* CSE2 from below */
21309   a &= SLOT_2_0;
21310   p++;
21311   b = b<<14;
21312   b |= *p;
21313   /* b: p3<<28 | p5<<14 | p7 (unmasked) */
21314   if (!(b&0x80))
21315   {
21316     b &= SLOT_4_2_0;
21317     /* moved CSE2 up */
21318     /* a &= (0x7f<<14)|(0x7f); */
21319     a = a<<7;
21320     a |= b;
21321     s = s>>4;
21322     *v = ((u64)s)<<32 | a;
21323     return 8;
21324   }
21325
21326   p++;
21327   a = a<<15;
21328   a |= *p;
21329   /* a: p4<<29 | p6<<15 | p8 (unmasked) */
21330
21331   /* moved CSE2 up */
21332   /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
21333   b &= SLOT_2_0;
21334   b = b<<8;
21335   a |= b;
21336
21337   s = s<<4;
21338   b = p[-4];
21339   b &= 0x7f;
21340   b = b>>3;
21341   s |= b;
21342
21343   *v = ((u64)s)<<32 | a;
21344
21345   return 9;
21346 }
21347
21348 /*
21349 ** Read a 32-bit variable-length integer from memory starting at p[0].
21350 ** Return the number of bytes read.  The value is stored in *v.
21351 **
21352 ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
21353 ** integer, then set *v to 0xffffffff.
21354 **
21355 ** A MACRO version, getVarint32, is provided which inlines the 
21356 ** single-byte case.  All code should use the MACRO version as 
21357 ** this function assumes the single-byte case has already been handled.
21358 */
21359 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
21360   u32 a,b;
21361
21362   /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
21363   ** by the getVarin32() macro */
21364   a = *p;
21365   /* a: p0 (unmasked) */
21366 #ifndef getVarint32
21367   if (!(a&0x80))
21368   {
21369     /* Values between 0 and 127 */
21370     *v = a;
21371     return 1;
21372   }
21373 #endif
21374
21375   /* The 2-byte case */
21376   p++;
21377   b = *p;
21378   /* b: p1 (unmasked) */
21379   if (!(b&0x80))
21380   {
21381     /* Values between 128 and 16383 */
21382     a &= 0x7f;
21383     a = a<<7;
21384     *v = a | b;
21385     return 2;
21386   }
21387
21388   /* The 3-byte case */
21389   p++;
21390   a = a<<14;
21391   a |= *p;
21392   /* a: p0<<14 | p2 (unmasked) */
21393   if (!(a&0x80))
21394   {
21395     /* Values between 16384 and 2097151 */
21396     a &= (0x7f<<14)|(0x7f);
21397     b &= 0x7f;
21398     b = b<<7;
21399     *v = a | b;
21400     return 3;
21401   }
21402
21403   /* A 32-bit varint is used to store size information in btrees.
21404   ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
21405   ** A 3-byte varint is sufficient, for example, to record the size
21406   ** of a 1048569-byte BLOB or string.
21407   **
21408   ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
21409   ** rare larger cases can be handled by the slower 64-bit varint
21410   ** routine.
21411   */
21412 #if 1
21413   {
21414     u64 v64;
21415     u8 n;
21416
21417     p -= 2;
21418     n = sqlite3GetVarint(p, &v64);
21419     assert( n>3 && n<=9 );
21420     if( (v64 & SQLITE_MAX_U32)!=v64 ){
21421       *v = 0xffffffff;
21422     }else{
21423       *v = (u32)v64;
21424     }
21425     return n;
21426   }
21427
21428 #else
21429   /* For following code (kept for historical record only) shows an
21430   ** unrolling for the 3- and 4-byte varint cases.  This code is
21431   ** slightly faster, but it is also larger and much harder to test.
21432   */
21433   p++;
21434   b = b<<14;
21435   b |= *p;
21436   /* b: p1<<14 | p3 (unmasked) */
21437   if (!(b&0x80))
21438   {
21439     /* Values between 2097152 and 268435455 */
21440     b &= (0x7f<<14)|(0x7f);
21441     a &= (0x7f<<14)|(0x7f);
21442     a = a<<7;
21443     *v = a | b;
21444     return 4;
21445   }
21446
21447   p++;
21448   a = a<<14;
21449   a |= *p;
21450   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
21451   if (!(a&0x80))
21452   {
21453     /* Values  between 268435456 and 34359738367 */
21454     a &= SLOT_4_2_0;
21455     b &= SLOT_4_2_0;
21456     b = b<<7;
21457     *v = a | b;
21458     return 5;
21459   }
21460
21461   /* We can only reach this point when reading a corrupt database
21462   ** file.  In that case we are not in any hurry.  Use the (relatively
21463   ** slow) general-purpose sqlite3GetVarint() routine to extract the
21464   ** value. */
21465   {
21466     u64 v64;
21467     u8 n;
21468
21469     p -= 4;
21470     n = sqlite3GetVarint(p, &v64);
21471     assert( n>5 && n<=9 );
21472     *v = (u32)v64;
21473     return n;
21474   }
21475 #endif
21476 }
21477
21478 /*
21479 ** Return the number of bytes that will be needed to store the given
21480 ** 64-bit integer.
21481 */
21482 SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
21483   int i = 0;
21484   do{
21485     i++;
21486     v >>= 7;
21487   }while( v!=0 && ALWAYS(i<9) );
21488   return i;
21489 }
21490
21491
21492 /*
21493 ** Read or write a four-byte big-endian integer value.
21494 */
21495 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
21496   return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
21497 }
21498 SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
21499   p[0] = (u8)(v>>24);
21500   p[1] = (u8)(v>>16);
21501   p[2] = (u8)(v>>8);
21502   p[3] = (u8)v;
21503 }
21504
21505
21506
21507 /*
21508 ** Translate a single byte of Hex into an integer.
21509 ** This routine only works if h really is a valid hexadecimal
21510 ** character:  0..9a..fA..F
21511 */
21512 SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
21513   assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
21514 #ifdef SQLITE_ASCII
21515   h += 9*(1&(h>>6));
21516 #endif
21517 #ifdef SQLITE_EBCDIC
21518   h += 9*(1&~(h>>4));
21519 #endif
21520   return (u8)(h & 0xf);
21521 }
21522
21523 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
21524 /*
21525 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
21526 ** value.  Return a pointer to its binary value.  Space to hold the
21527 ** binary value has been obtained from malloc and must be freed by
21528 ** the calling routine.
21529 */
21530 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
21531   char *zBlob;
21532   int i;
21533
21534   zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
21535   n--;
21536   if( zBlob ){
21537     for(i=0; i<n; i+=2){
21538       zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
21539     }
21540     zBlob[i/2] = 0;
21541   }
21542   return zBlob;
21543 }
21544 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
21545
21546 /*
21547 ** Log an error that is an API call on a connection pointer that should
21548 ** not have been used.  The "type" of connection pointer is given as the
21549 ** argument.  The zType is a word like "NULL" or "closed" or "invalid".
21550 */
21551 static void logBadConnection(const char *zType){
21552   sqlite3_log(SQLITE_MISUSE, 
21553      "API call with %s database connection pointer",
21554      zType
21555   );
21556 }
21557
21558 /*
21559 ** Check to make sure we have a valid db pointer.  This test is not
21560 ** foolproof but it does provide some measure of protection against
21561 ** misuse of the interface such as passing in db pointers that are
21562 ** NULL or which have been previously closed.  If this routine returns
21563 ** 1 it means that the db pointer is valid and 0 if it should not be
21564 ** dereferenced for any reason.  The calling function should invoke
21565 ** SQLITE_MISUSE immediately.
21566 **
21567 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
21568 ** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
21569 ** open properly and is not fit for general use but which can be
21570 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
21571 */
21572 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
21573   u32 magic;
21574   if( db==0 ){
21575     logBadConnection("NULL");
21576     return 0;
21577   }
21578   magic = db->magic;
21579   if( magic!=SQLITE_MAGIC_OPEN ){
21580     if( sqlite3SafetyCheckSickOrOk(db) ){
21581       testcase( sqlite3GlobalConfig.xLog!=0 );
21582       logBadConnection("unopened");
21583     }
21584     return 0;
21585   }else{
21586     return 1;
21587   }
21588 }
21589 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
21590   u32 magic;
21591   magic = db->magic;
21592   if( magic!=SQLITE_MAGIC_SICK &&
21593       magic!=SQLITE_MAGIC_OPEN &&
21594       magic!=SQLITE_MAGIC_BUSY ){
21595     testcase( sqlite3GlobalConfig.xLog!=0 );
21596     logBadConnection("invalid");
21597     return 0;
21598   }else{
21599     return 1;
21600   }
21601 }
21602
21603 /*
21604 ** Attempt to add, substract, or multiply the 64-bit signed value iB against
21605 ** the other 64-bit signed integer at *pA and store the result in *pA.
21606 ** Return 0 on success.  Or if the operation would have resulted in an
21607 ** overflow, leave *pA unchanged and return 1.
21608 */
21609 SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
21610   i64 iA = *pA;
21611   testcase( iA==0 ); testcase( iA==1 );
21612   testcase( iB==-1 ); testcase( iB==0 );
21613   if( iB>=0 ){
21614     testcase( iA>0 && LARGEST_INT64 - iA == iB );
21615     testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
21616     if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
21617     *pA += iB;
21618   }else{
21619     testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
21620     testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
21621     if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
21622     *pA += iB;
21623   }
21624   return 0; 
21625 }
21626 SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
21627   testcase( iB==SMALLEST_INT64+1 );
21628   if( iB==SMALLEST_INT64 ){
21629     testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
21630     if( (*pA)>=0 ) return 1;
21631     *pA -= iB;
21632     return 0;
21633   }else{
21634     return sqlite3AddInt64(pA, -iB);
21635   }
21636 }
21637 #define TWOPOWER32 (((i64)1)<<32)
21638 #define TWOPOWER31 (((i64)1)<<31)
21639 SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
21640   i64 iA = *pA;
21641   i64 iA1, iA0, iB1, iB0, r;
21642
21643   iA1 = iA/TWOPOWER32;
21644   iA0 = iA % TWOPOWER32;
21645   iB1 = iB/TWOPOWER32;
21646   iB0 = iB % TWOPOWER32;
21647   if( iA1*iB1 != 0 ) return 1;
21648   assert( iA1*iB0==0 || iA0*iB1==0 );
21649   r = iA1*iB0 + iA0*iB1;
21650   testcase( r==(-TWOPOWER31)-1 );
21651   testcase( r==(-TWOPOWER31) );
21652   testcase( r==TWOPOWER31 );
21653   testcase( r==TWOPOWER31-1 );
21654   if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
21655   r *= TWOPOWER32;
21656   if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
21657   *pA = r;
21658   return 0;
21659 }
21660
21661 /*
21662 ** Compute the absolute value of a 32-bit signed integer, of possible.  Or 
21663 ** if the integer has a value of -2147483648, return +2147483647
21664 */
21665 SQLITE_PRIVATE int sqlite3AbsInt32(int x){
21666   if( x>=0 ) return x;
21667   if( x==(int)0x80000000 ) return 0x7fffffff;
21668   return -x;
21669 }
21670
21671 #ifdef SQLITE_ENABLE_8_3_NAMES
21672 /*
21673 ** If SQLITE_ENABLE_8_3_NAME is set at compile-time and if the database
21674 ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
21675 ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
21676 ** three characters, then shorten the suffix on z[] to be the last three
21677 ** characters of the original suffix.
21678 **
21679 ** Examples:
21680 **
21681 **     test.db-journal    =>   test.nal
21682 **     test.db-wal        =>   test.wal
21683 **     test.db-shm        =>   test.shm
21684 */
21685 SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
21686   const char *zOk;
21687   zOk = sqlite3_uri_parameter(zBaseFilename, "8_3_names");
21688   if( zOk && sqlite3GetBoolean(zOk) ){
21689     int i, sz;
21690     sz = sqlite3Strlen30(z);
21691     for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
21692     if( z[i]=='.' && ALWAYS(sz>i+4) ) memcpy(&z[i+1], &z[sz-3], 4);
21693   }
21694 }
21695 #endif
21696
21697 /************** End of util.c ************************************************/
21698 /************** Begin file hash.c ********************************************/
21699 /*
21700 ** 2001 September 22
21701 **
21702 ** The author disclaims copyright to this source code.  In place of
21703 ** a legal notice, here is a blessing:
21704 **
21705 **    May you do good and not evil.
21706 **    May you find forgiveness for yourself and forgive others.
21707 **    May you share freely, never taking more than you give.
21708 **
21709 *************************************************************************
21710 ** This is the implementation of generic hash-tables
21711 ** used in SQLite.
21712 */
21713
21714 /* Turn bulk memory into a hash table object by initializing the
21715 ** fields of the Hash structure.
21716 **
21717 ** "pNew" is a pointer to the hash table that is to be initialized.
21718 */
21719 SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
21720   assert( pNew!=0 );
21721   pNew->first = 0;
21722   pNew->count = 0;
21723   pNew->htsize = 0;
21724   pNew->ht = 0;
21725 }
21726
21727 /* Remove all entries from a hash table.  Reclaim all memory.
21728 ** Call this routine to delete a hash table or to reset a hash table
21729 ** to the empty state.
21730 */
21731 SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
21732   HashElem *elem;         /* For looping over all elements of the table */
21733
21734   assert( pH!=0 );
21735   elem = pH->first;
21736   pH->first = 0;
21737   sqlite3_free(pH->ht);
21738   pH->ht = 0;
21739   pH->htsize = 0;
21740   while( elem ){
21741     HashElem *next_elem = elem->next;
21742     sqlite3_free(elem);
21743     elem = next_elem;
21744   }
21745   pH->count = 0;
21746 }
21747
21748 /*
21749 ** The hashing function.
21750 */
21751 static unsigned int strHash(const char *z, int nKey){
21752   int h = 0;
21753   assert( nKey>=0 );
21754   while( nKey > 0  ){
21755     h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
21756     nKey--;
21757   }
21758   return h;
21759 }
21760
21761
21762 /* Link pNew element into the hash table pH.  If pEntry!=0 then also
21763 ** insert pNew into the pEntry hash bucket.
21764 */
21765 static void insertElement(
21766   Hash *pH,              /* The complete hash table */
21767   struct _ht *pEntry,    /* The entry into which pNew is inserted */
21768   HashElem *pNew         /* The element to be inserted */
21769 ){
21770   HashElem *pHead;       /* First element already in pEntry */
21771   if( pEntry ){
21772     pHead = pEntry->count ? pEntry->chain : 0;
21773     pEntry->count++;
21774     pEntry->chain = pNew;
21775   }else{
21776     pHead = 0;
21777   }
21778   if( pHead ){
21779     pNew->next = pHead;
21780     pNew->prev = pHead->prev;
21781     if( pHead->prev ){ pHead->prev->next = pNew; }
21782     else             { pH->first = pNew; }
21783     pHead->prev = pNew;
21784   }else{
21785     pNew->next = pH->first;
21786     if( pH->first ){ pH->first->prev = pNew; }
21787     pNew->prev = 0;
21788     pH->first = pNew;
21789   }
21790 }
21791
21792
21793 /* Resize the hash table so that it cantains "new_size" buckets.
21794 **
21795 ** The hash table might fail to resize if sqlite3_malloc() fails or
21796 ** if the new size is the same as the prior size.
21797 ** Return TRUE if the resize occurs and false if not.
21798 */
21799 static int rehash(Hash *pH, unsigned int new_size){
21800   struct _ht *new_ht;            /* The new hash table */
21801   HashElem *elem, *next_elem;    /* For looping over existing elements */
21802
21803 #if SQLITE_MALLOC_SOFT_LIMIT>0
21804   if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
21805     new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
21806   }
21807   if( new_size==pH->htsize ) return 0;
21808 #endif
21809
21810   /* The inability to allocates space for a larger hash table is
21811   ** a performance hit but it is not a fatal error.  So mark the
21812   ** allocation as a benign.
21813   */
21814   sqlite3BeginBenignMalloc();
21815   new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
21816   sqlite3EndBenignMalloc();
21817
21818   if( new_ht==0 ) return 0;
21819   sqlite3_free(pH->ht);
21820   pH->ht = new_ht;
21821   pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
21822   memset(new_ht, 0, new_size*sizeof(struct _ht));
21823   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
21824     unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
21825     next_elem = elem->next;
21826     insertElement(pH, &new_ht[h], elem);
21827   }
21828   return 1;
21829 }
21830
21831 /* This function (for internal use only) locates an element in an
21832 ** hash table that matches the given key.  The hash for this key has
21833 ** already been computed and is passed as the 4th parameter.
21834 */
21835 static HashElem *findElementGivenHash(
21836   const Hash *pH,     /* The pH to be searched */
21837   const char *pKey,   /* The key we are searching for */
21838   int nKey,           /* Bytes in key (not counting zero terminator) */
21839   unsigned int h      /* The hash for this key. */
21840 ){
21841   HashElem *elem;                /* Used to loop thru the element list */
21842   int count;                     /* Number of elements left to test */
21843
21844   if( pH->ht ){
21845     struct _ht *pEntry = &pH->ht[h];
21846     elem = pEntry->chain;
21847     count = pEntry->count;
21848   }else{
21849     elem = pH->first;
21850     count = pH->count;
21851   }
21852   while( count-- && ALWAYS(elem) ){
21853     if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){ 
21854       return elem;
21855     }
21856     elem = elem->next;
21857   }
21858   return 0;
21859 }
21860
21861 /* Remove a single entry from the hash table given a pointer to that
21862 ** element and a hash on the element's key.
21863 */
21864 static void removeElementGivenHash(
21865   Hash *pH,         /* The pH containing "elem" */
21866   HashElem* elem,   /* The element to be removed from the pH */
21867   unsigned int h    /* Hash value for the element */
21868 ){
21869   struct _ht *pEntry;
21870   if( elem->prev ){
21871     elem->prev->next = elem->next; 
21872   }else{
21873     pH->first = elem->next;
21874   }
21875   if( elem->next ){
21876     elem->next->prev = elem->prev;
21877   }
21878   if( pH->ht ){
21879     pEntry = &pH->ht[h];
21880     if( pEntry->chain==elem ){
21881       pEntry->chain = elem->next;
21882     }
21883     pEntry->count--;
21884     assert( pEntry->count>=0 );
21885   }
21886   sqlite3_free( elem );
21887   pH->count--;
21888   if( pH->count<=0 ){
21889     assert( pH->first==0 );
21890     assert( pH->count==0 );
21891     sqlite3HashClear(pH);
21892   }
21893 }
21894
21895 /* Attempt to locate an element of the hash table pH with a key
21896 ** that matches pKey,nKey.  Return the data for this element if it is
21897 ** found, or NULL if there is no match.
21898 */
21899 SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
21900   HashElem *elem;    /* The element that matches key */
21901   unsigned int h;    /* A hash on key */
21902
21903   assert( pH!=0 );
21904   assert( pKey!=0 );
21905   assert( nKey>=0 );
21906   if( pH->ht ){
21907     h = strHash(pKey, nKey) % pH->htsize;
21908   }else{
21909     h = 0;
21910   }
21911   elem = findElementGivenHash(pH, pKey, nKey, h);
21912   return elem ? elem->data : 0;
21913 }
21914
21915 /* Insert an element into the hash table pH.  The key is pKey,nKey
21916 ** and the data is "data".
21917 **
21918 ** If no element exists with a matching key, then a new
21919 ** element is created and NULL is returned.
21920 **
21921 ** If another element already exists with the same key, then the
21922 ** new data replaces the old data and the old data is returned.
21923 ** The key is not copied in this instance.  If a malloc fails, then
21924 ** the new data is returned and the hash table is unchanged.
21925 **
21926 ** If the "data" parameter to this function is NULL, then the
21927 ** element corresponding to "key" is removed from the hash table.
21928 */
21929 SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
21930   unsigned int h;       /* the hash of the key modulo hash table size */
21931   HashElem *elem;       /* Used to loop thru the element list */
21932   HashElem *new_elem;   /* New element added to the pH */
21933
21934   assert( pH!=0 );
21935   assert( pKey!=0 );
21936   assert( nKey>=0 );
21937   if( pH->htsize ){
21938     h = strHash(pKey, nKey) % pH->htsize;
21939   }else{
21940     h = 0;
21941   }
21942   elem = findElementGivenHash(pH,pKey,nKey,h);
21943   if( elem ){
21944     void *old_data = elem->data;
21945     if( data==0 ){
21946       removeElementGivenHash(pH,elem,h);
21947     }else{
21948       elem->data = data;
21949       elem->pKey = pKey;
21950       assert(nKey==elem->nKey);
21951     }
21952     return old_data;
21953   }
21954   if( data==0 ) return 0;
21955   new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
21956   if( new_elem==0 ) return data;
21957   new_elem->pKey = pKey;
21958   new_elem->nKey = nKey;
21959   new_elem->data = data;
21960   pH->count++;
21961   if( pH->count>=10 && pH->count > 2*pH->htsize ){
21962     if( rehash(pH, pH->count*2) ){
21963       assert( pH->htsize>0 );
21964       h = strHash(pKey, nKey) % pH->htsize;
21965     }
21966   }
21967   if( pH->ht ){
21968     insertElement(pH, &pH->ht[h], new_elem);
21969   }else{
21970     insertElement(pH, 0, new_elem);
21971   }
21972   return 0;
21973 }
21974
21975 /************** End of hash.c ************************************************/
21976 /************** Begin file opcodes.c *****************************************/
21977 /* Automatically generated.  Do not edit */
21978 /* See the mkopcodec.awk script for details. */
21979 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
21980 SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
21981  static const char *const azName[] = { "?",
21982      /*   1 */ "Goto",
21983      /*   2 */ "Gosub",
21984      /*   3 */ "Return",
21985      /*   4 */ "Yield",
21986      /*   5 */ "HaltIfNull",
21987      /*   6 */ "Halt",
21988      /*   7 */ "Integer",
21989      /*   8 */ "Int64",
21990      /*   9 */ "String",
21991      /*  10 */ "Null",
21992      /*  11 */ "Blob",
21993      /*  12 */ "Variable",
21994      /*  13 */ "Move",
21995      /*  14 */ "Copy",
21996      /*  15 */ "SCopy",
21997      /*  16 */ "ResultRow",
21998      /*  17 */ "CollSeq",
21999      /*  18 */ "Function",
22000      /*  19 */ "Not",
22001      /*  20 */ "AddImm",
22002      /*  21 */ "MustBeInt",
22003      /*  22 */ "RealAffinity",
22004      /*  23 */ "Permutation",
22005      /*  24 */ "Compare",
22006      /*  25 */ "Jump",
22007      /*  26 */ "If",
22008      /*  27 */ "IfNot",
22009      /*  28 */ "Column",
22010      /*  29 */ "Affinity",
22011      /*  30 */ "MakeRecord",
22012      /*  31 */ "Count",
22013      /*  32 */ "Savepoint",
22014      /*  33 */ "AutoCommit",
22015      /*  34 */ "Transaction",
22016      /*  35 */ "ReadCookie",
22017      /*  36 */ "SetCookie",
22018      /*  37 */ "VerifyCookie",
22019      /*  38 */ "OpenRead",
22020      /*  39 */ "OpenWrite",
22021      /*  40 */ "OpenAutoindex",
22022      /*  41 */ "OpenEphemeral",
22023      /*  42 */ "OpenPseudo",
22024      /*  43 */ "Close",
22025      /*  44 */ "SeekLt",
22026      /*  45 */ "SeekLe",
22027      /*  46 */ "SeekGe",
22028      /*  47 */ "SeekGt",
22029      /*  48 */ "Seek",
22030      /*  49 */ "NotFound",
22031      /*  50 */ "Found",
22032      /*  51 */ "IsUnique",
22033      /*  52 */ "NotExists",
22034      /*  53 */ "Sequence",
22035      /*  54 */ "NewRowid",
22036      /*  55 */ "Insert",
22037      /*  56 */ "InsertInt",
22038      /*  57 */ "Delete",
22039      /*  58 */ "ResetCount",
22040      /*  59 */ "RowKey",
22041      /*  60 */ "RowData",
22042      /*  61 */ "Rowid",
22043      /*  62 */ "NullRow",
22044      /*  63 */ "Last",
22045      /*  64 */ "Sort",
22046      /*  65 */ "Rewind",
22047      /*  66 */ "Prev",
22048      /*  67 */ "Next",
22049      /*  68 */ "Or",
22050      /*  69 */ "And",
22051      /*  70 */ "IdxInsert",
22052      /*  71 */ "IdxDelete",
22053      /*  72 */ "IdxRowid",
22054      /*  73 */ "IsNull",
22055      /*  74 */ "NotNull",
22056      /*  75 */ "Ne",
22057      /*  76 */ "Eq",
22058      /*  77 */ "Gt",
22059      /*  78 */ "Le",
22060      /*  79 */ "Lt",
22061      /*  80 */ "Ge",
22062      /*  81 */ "IdxLT",
22063      /*  82 */ "BitAnd",
22064      /*  83 */ "BitOr",
22065      /*  84 */ "ShiftLeft",
22066      /*  85 */ "ShiftRight",
22067      /*  86 */ "Add",
22068      /*  87 */ "Subtract",
22069      /*  88 */ "Multiply",
22070      /*  89 */ "Divide",
22071      /*  90 */ "Remainder",
22072      /*  91 */ "Concat",
22073      /*  92 */ "IdxGE",
22074      /*  93 */ "BitNot",
22075      /*  94 */ "String8",
22076      /*  95 */ "Destroy",
22077      /*  96 */ "Clear",
22078      /*  97 */ "CreateIndex",
22079      /*  98 */ "CreateTable",
22080      /*  99 */ "ParseSchema",
22081      /* 100 */ "LoadAnalysis",
22082      /* 101 */ "DropTable",
22083      /* 102 */ "DropIndex",
22084      /* 103 */ "DropTrigger",
22085      /* 104 */ "IntegrityCk",
22086      /* 105 */ "RowSetAdd",
22087      /* 106 */ "RowSetRead",
22088      /* 107 */ "RowSetTest",
22089      /* 108 */ "Program",
22090      /* 109 */ "Param",
22091      /* 110 */ "FkCounter",
22092      /* 111 */ "FkIfZero",
22093      /* 112 */ "MemMax",
22094      /* 113 */ "IfPos",
22095      /* 114 */ "IfNeg",
22096      /* 115 */ "IfZero",
22097      /* 116 */ "AggStep",
22098      /* 117 */ "AggFinal",
22099      /* 118 */ "Checkpoint",
22100      /* 119 */ "JournalMode",
22101      /* 120 */ "Vacuum",
22102      /* 121 */ "IncrVacuum",
22103      /* 122 */ "Expire",
22104      /* 123 */ "TableLock",
22105      /* 124 */ "VBegin",
22106      /* 125 */ "VCreate",
22107      /* 126 */ "VDestroy",
22108      /* 127 */ "VOpen",
22109      /* 128 */ "VFilter",
22110      /* 129 */ "VColumn",
22111      /* 130 */ "Real",
22112      /* 131 */ "VNext",
22113      /* 132 */ "VRename",
22114      /* 133 */ "VUpdate",
22115      /* 134 */ "Pagecount",
22116      /* 135 */ "MaxPgcnt",
22117      /* 136 */ "Trace",
22118      /* 137 */ "Noop",
22119      /* 138 */ "Explain",
22120      /* 139 */ "NotUsed_139",
22121      /* 140 */ "NotUsed_140",
22122      /* 141 */ "ToText",
22123      /* 142 */ "ToBlob",
22124      /* 143 */ "ToNumeric",
22125      /* 144 */ "ToInt",
22126      /* 145 */ "ToReal",
22127   };
22128   return azName[i];
22129 }
22130 #endif
22131
22132 /************** End of opcodes.c *********************************************/
22133 /************** Begin file os_os2.c ******************************************/
22134 /*
22135 ** 2006 Feb 14
22136 **
22137 ** The author disclaims copyright to this source code.  In place of
22138 ** a legal notice, here is a blessing:
22139 **
22140 **    May you do good and not evil.
22141 **    May you find forgiveness for yourself and forgive others.
22142 **    May you share freely, never taking more than you give.
22143 **
22144 ******************************************************************************
22145 **
22146 ** This file contains code that is specific to OS/2.
22147 */
22148
22149
22150 #if SQLITE_OS_OS2
22151
22152 /*
22153 ** A Note About Memory Allocation:
22154 **
22155 ** This driver uses malloc()/free() directly rather than going through
22156 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
22157 ** are designed for use on embedded systems where memory is scarce and
22158 ** malloc failures happen frequently.  OS/2 does not typically run on
22159 ** embedded systems, and when it does the developers normally have bigger
22160 ** problems to worry about than running out of memory.  So there is not
22161 ** a compelling need to use the wrappers.
22162 **
22163 ** But there is a good reason to not use the wrappers.  If we use the
22164 ** wrappers then we will get simulated malloc() failures within this
22165 ** driver.  And that causes all kinds of problems for our tests.  We
22166 ** could enhance SQLite to deal with simulated malloc failures within
22167 ** the OS driver, but the code to deal with those failure would not
22168 ** be exercised on Linux (which does not need to malloc() in the driver)
22169 ** and so we would have difficulty writing coverage tests for that
22170 ** code.  Better to leave the code out, we think.
22171 **
22172 ** The point of this discussion is as follows:  When creating a new
22173 ** OS layer for an embedded system, if you use this file as an example,
22174 ** avoid the use of malloc()/free().  Those routines work ok on OS/2
22175 ** desktops but not so well in embedded systems.
22176 */
22177
22178 /*
22179 ** Macros used to determine whether or not to use threads.
22180 */
22181 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE
22182 # define SQLITE_OS2_THREADS 1
22183 #endif
22184
22185 /*
22186 ** Include code that is common to all os_*.c files
22187 */
22188 /************** Include os_common.h in the middle of os_os2.c ****************/
22189 /************** Begin file os_common.h ***************************************/
22190 /*
22191 ** 2004 May 22
22192 **
22193 ** The author disclaims copyright to this source code.  In place of
22194 ** a legal notice, here is a blessing:
22195 **
22196 **    May you do good and not evil.
22197 **    May you find forgiveness for yourself and forgive others.
22198 **    May you share freely, never taking more than you give.
22199 **
22200 ******************************************************************************
22201 **
22202 ** This file contains macros and a little bit of code that is common to
22203 ** all of the platform-specific files (os_*.c) and is #included into those
22204 ** files.
22205 **
22206 ** This file should be #included by the os_*.c files only.  It is not a
22207 ** general purpose header file.
22208 */
22209 #ifndef _OS_COMMON_H_
22210 #define _OS_COMMON_H_
22211
22212 /*
22213 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
22214 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
22215 ** switch.  The following code should catch this problem at compile-time.
22216 */
22217 #ifdef MEMORY_DEBUG
22218 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
22219 #endif
22220
22221 #ifdef SQLITE_DEBUG
22222 SQLITE_PRIVATE int sqlite3OSTrace = 0;
22223 #define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
22224 #else
22225 #define OSTRACE(X)
22226 #endif
22227
22228 /*
22229 ** Macros for performance tracing.  Normally turned off.  Only works
22230 ** on i486 hardware.
22231 */
22232 #ifdef SQLITE_PERFORMANCE_TRACE
22233
22234 /* 
22235 ** hwtime.h contains inline assembler code for implementing 
22236 ** high-performance timing routines.
22237 */
22238 /************** Include hwtime.h in the middle of os_common.h ****************/
22239 /************** Begin file hwtime.h ******************************************/
22240 /*
22241 ** 2008 May 27
22242 **
22243 ** The author disclaims copyright to this source code.  In place of
22244 ** a legal notice, here is a blessing:
22245 **
22246 **    May you do good and not evil.
22247 **    May you find forgiveness for yourself and forgive others.
22248 **    May you share freely, never taking more than you give.
22249 **
22250 ******************************************************************************
22251 **
22252 ** This file contains inline asm code for retrieving "high-performance"
22253 ** counters for x86 class CPUs.
22254 */
22255 #ifndef _HWTIME_H_
22256 #define _HWTIME_H_
22257
22258 /*
22259 ** The following routine only works on pentium-class (or newer) processors.
22260 ** It uses the RDTSC opcode to read the cycle count value out of the
22261 ** processor and returns that value.  This can be used for high-res
22262 ** profiling.
22263 */
22264 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
22265       (defined(i386) || defined(__i386__) || defined(_M_IX86))
22266
22267   #if defined(__GNUC__)
22268
22269   __inline__ sqlite_uint64 sqlite3Hwtime(void){
22270      unsigned int lo, hi;
22271      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
22272      return (sqlite_uint64)hi << 32 | lo;
22273   }
22274
22275   #elif defined(_MSC_VER)
22276
22277   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
22278      __asm {
22279         rdtsc
22280         ret       ; return value at EDX:EAX
22281      }
22282   }
22283
22284   #endif
22285
22286 #elif (defined(__GNUC__) && defined(__x86_64__))
22287
22288   __inline__ sqlite_uint64 sqlite3Hwtime(void){
22289       unsigned long val;
22290       __asm__ __volatile__ ("rdtsc" : "=A" (val));
22291       return val;
22292   }
22293  
22294 #elif (defined(__GNUC__) && defined(__ppc__))
22295
22296   __inline__ sqlite_uint64 sqlite3Hwtime(void){
22297       unsigned long long retval;
22298       unsigned long junk;
22299       __asm__ __volatile__ ("\n\
22300           1:      mftbu   %1\n\
22301                   mftb    %L0\n\
22302                   mftbu   %0\n\
22303                   cmpw    %0,%1\n\
22304                   bne     1b"
22305                   : "=r" (retval), "=r" (junk));
22306       return retval;
22307   }
22308
22309 #else
22310
22311   #error Need implementation of sqlite3Hwtime() for your platform.
22312
22313   /*
22314   ** To compile without implementing sqlite3Hwtime() for your platform,
22315   ** you can remove the above #error and use the following
22316   ** stub function.  You will lose timing support for many
22317   ** of the debugging and testing utilities, but it should at
22318   ** least compile and run.
22319   */
22320 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
22321
22322 #endif
22323
22324 #endif /* !defined(_HWTIME_H_) */
22325
22326 /************** End of hwtime.h **********************************************/
22327 /************** Continuing where we left off in os_common.h ******************/
22328
22329 static sqlite_uint64 g_start;
22330 static sqlite_uint64 g_elapsed;
22331 #define TIMER_START       g_start=sqlite3Hwtime()
22332 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
22333 #define TIMER_ELAPSED     g_elapsed
22334 #else
22335 #define TIMER_START
22336 #define TIMER_END
22337 #define TIMER_ELAPSED     ((sqlite_uint64)0)
22338 #endif
22339
22340 /*
22341 ** If we compile with the SQLITE_TEST macro set, then the following block
22342 ** of code will give us the ability to simulate a disk I/O error.  This
22343 ** is used for testing the I/O recovery logic.
22344 */
22345 #ifdef SQLITE_TEST
22346 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
22347 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
22348 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
22349 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
22350 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
22351 SQLITE_API int sqlite3_diskfull_pending = 0;
22352 SQLITE_API int sqlite3_diskfull = 0;
22353 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
22354 #define SimulateIOError(CODE)  \
22355   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
22356        || sqlite3_io_error_pending-- == 1 )  \
22357               { local_ioerr(); CODE; }
22358 static void local_ioerr(){
22359   IOTRACE(("IOERR\n"));
22360   sqlite3_io_error_hit++;
22361   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
22362 }
22363 #define SimulateDiskfullError(CODE) \
22364    if( sqlite3_diskfull_pending ){ \
22365      if( sqlite3_diskfull_pending == 1 ){ \
22366        local_ioerr(); \
22367        sqlite3_diskfull = 1; \
22368        sqlite3_io_error_hit = 1; \
22369        CODE; \
22370      }else{ \
22371        sqlite3_diskfull_pending--; \
22372      } \
22373    }
22374 #else
22375 #define SimulateIOErrorBenign(X)
22376 #define SimulateIOError(A)
22377 #define SimulateDiskfullError(A)
22378 #endif
22379
22380 /*
22381 ** When testing, keep a count of the number of open files.
22382 */
22383 #ifdef SQLITE_TEST
22384 SQLITE_API int sqlite3_open_file_count = 0;
22385 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
22386 #else
22387 #define OpenCounter(X)
22388 #endif
22389
22390 #endif /* !defined(_OS_COMMON_H_) */
22391
22392 /************** End of os_common.h *******************************************/
22393 /************** Continuing where we left off in os_os2.c *********************/
22394
22395 /* Forward references */
22396 typedef struct os2File os2File;         /* The file structure */
22397 typedef struct os2ShmNode os2ShmNode;   /* A shared descritive memory node */
22398 typedef struct os2ShmLink os2ShmLink;   /* A connection to shared-memory */
22399
22400 /*
22401 ** The os2File structure is subclass of sqlite3_file specific for the OS/2
22402 ** protability layer.
22403 */
22404 struct os2File {
22405   const sqlite3_io_methods *pMethod;  /* Always the first entry */
22406   HFILE h;                  /* Handle for accessing the file */
22407   int flags;                /* Flags provided to os2Open() */
22408   int locktype;             /* Type of lock currently held on this file */
22409   int szChunk;              /* Chunk size configured by FCNTL_CHUNK_SIZE */
22410   char *zFullPathCp;        /* Full path name of this file */
22411   os2ShmLink *pShmLink;     /* Instance of shared memory on this file */
22412 };
22413
22414 #define LOCK_TIMEOUT 10L /* the default locking timeout */
22415
22416 /*
22417 ** Missing from some versions of the OS/2 toolkit -
22418 ** used to allocate from high memory if possible
22419 */
22420 #ifndef OBJ_ANY
22421 # define OBJ_ANY 0x00000400
22422 #endif
22423
22424 /*****************************************************************************
22425 ** The next group of routines implement the I/O methods specified
22426 ** by the sqlite3_io_methods object.
22427 ******************************************************************************/
22428
22429 /*
22430 ** Close a file.
22431 */
22432 static int os2Close( sqlite3_file *id ){
22433   APIRET rc;
22434   os2File *pFile = (os2File*)id;
22435
22436   assert( id!=0 );
22437   OSTRACE(( "CLOSE %d (%s)\n", pFile->h, pFile->zFullPathCp ));
22438
22439   rc = DosClose( pFile->h );
22440
22441   if( pFile->flags & SQLITE_OPEN_DELETEONCLOSE )
22442     DosForceDelete( (PSZ)pFile->zFullPathCp );
22443
22444   free( pFile->zFullPathCp );
22445   pFile->zFullPathCp = NULL;
22446   pFile->locktype = NO_LOCK;
22447   pFile->h = (HFILE)-1;
22448   pFile->flags = 0;
22449
22450   OpenCounter( -1 );
22451   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
22452 }
22453
22454 /*
22455 ** Read data from a file into a buffer.  Return SQLITE_OK if all
22456 ** bytes were read successfully and SQLITE_IOERR if anything goes
22457 ** wrong.
22458 */
22459 static int os2Read(
22460   sqlite3_file *id,               /* File to read from */
22461   void *pBuf,                     /* Write content into this buffer */
22462   int amt,                        /* Number of bytes to read */
22463   sqlite3_int64 offset            /* Begin reading at this offset */
22464 ){
22465   ULONG fileLocation = 0L;
22466   ULONG got;
22467   os2File *pFile = (os2File*)id;
22468   assert( id!=0 );
22469   SimulateIOError( return SQLITE_IOERR_READ );
22470   OSTRACE(( "READ %d lock=%d\n", pFile->h, pFile->locktype ));
22471   if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
22472     return SQLITE_IOERR;
22473   }
22474   if( DosRead( pFile->h, pBuf, amt, &got ) != NO_ERROR ){
22475     return SQLITE_IOERR_READ;
22476   }
22477   if( got == (ULONG)amt )
22478     return SQLITE_OK;
22479   else {
22480     /* Unread portions of the input buffer must be zero-filled */
22481     memset(&((char*)pBuf)[got], 0, amt-got);
22482     return SQLITE_IOERR_SHORT_READ;
22483   }
22484 }
22485
22486 /*
22487 ** Write data from a buffer into a file.  Return SQLITE_OK on success
22488 ** or some other error code on failure.
22489 */
22490 static int os2Write(
22491   sqlite3_file *id,               /* File to write into */
22492   const void *pBuf,               /* The bytes to be written */
22493   int amt,                        /* Number of bytes to write */
22494   sqlite3_int64 offset            /* Offset into the file to begin writing at */
22495 ){
22496   ULONG fileLocation = 0L;
22497   APIRET rc = NO_ERROR;
22498   ULONG wrote;
22499   os2File *pFile = (os2File*)id;
22500   assert( id!=0 );
22501   SimulateIOError( return SQLITE_IOERR_WRITE );
22502   SimulateDiskfullError( return SQLITE_FULL );
22503   OSTRACE(( "WRITE %d lock=%d\n", pFile->h, pFile->locktype ));
22504   if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
22505     return SQLITE_IOERR;
22506   }
22507   assert( amt>0 );
22508   while( amt > 0 &&
22509          ( rc = DosWrite( pFile->h, (PVOID)pBuf, amt, &wrote ) ) == NO_ERROR &&
22510          wrote > 0
22511   ){
22512     amt -= wrote;
22513     pBuf = &((char*)pBuf)[wrote];
22514   }
22515
22516   return ( rc != NO_ERROR || amt > (int)wrote ) ? SQLITE_FULL : SQLITE_OK;
22517 }
22518
22519 /*
22520 ** Truncate an open file to a specified size
22521 */
22522 static int os2Truncate( sqlite3_file *id, i64 nByte ){
22523   APIRET rc;
22524   os2File *pFile = (os2File*)id;
22525   assert( id!=0 );
22526   OSTRACE(( "TRUNCATE %d %lld\n", pFile->h, nByte ));
22527   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
22528
22529   /* If the user has configured a chunk-size for this file, truncate the
22530   ** file so that it consists of an integer number of chunks (i.e. the
22531   ** actual file size after the operation may be larger than the requested
22532   ** size).
22533   */
22534   if( pFile->szChunk ){
22535     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
22536   }
22537   
22538   rc = DosSetFileSize( pFile->h, nByte );
22539   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_TRUNCATE;
22540 }
22541
22542 #ifdef SQLITE_TEST
22543 /*
22544 ** Count the number of fullsyncs and normal syncs.  This is used to test
22545 ** that syncs and fullsyncs are occuring at the right times.
22546 */
22547 SQLITE_API int sqlite3_sync_count = 0;
22548 SQLITE_API int sqlite3_fullsync_count = 0;
22549 #endif
22550
22551 /*
22552 ** Make sure all writes to a particular file are committed to disk.
22553 */
22554 static int os2Sync( sqlite3_file *id, int flags ){
22555   os2File *pFile = (os2File*)id;
22556   OSTRACE(( "SYNC %d lock=%d\n", pFile->h, pFile->locktype ));
22557 #ifdef SQLITE_TEST
22558   if( flags & SQLITE_SYNC_FULL){
22559     sqlite3_fullsync_count++;
22560   }
22561   sqlite3_sync_count++;
22562 #endif
22563   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
22564   ** no-op
22565   */
22566 #ifdef SQLITE_NO_SYNC
22567   UNUSED_PARAMETER(pFile);
22568   return SQLITE_OK;
22569 #else
22570   return DosResetBuffer( pFile->h ) == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
22571 #endif
22572 }
22573
22574 /*
22575 ** Determine the current size of a file in bytes
22576 */
22577 static int os2FileSize( sqlite3_file *id, sqlite3_int64 *pSize ){
22578   APIRET rc = NO_ERROR;
22579   FILESTATUS3 fsts3FileInfo;
22580   memset(&fsts3FileInfo, 0, sizeof(fsts3FileInfo));
22581   assert( id!=0 );
22582   SimulateIOError( return SQLITE_IOERR_FSTAT );
22583   rc = DosQueryFileInfo( ((os2File*)id)->h, FIL_STANDARD, &fsts3FileInfo, sizeof(FILESTATUS3) );
22584   if( rc == NO_ERROR ){
22585     *pSize = fsts3FileInfo.cbFile;
22586     return SQLITE_OK;
22587   }else{
22588     return SQLITE_IOERR_FSTAT;
22589   }
22590 }
22591
22592 /*
22593 ** Acquire a reader lock.
22594 */
22595 static int getReadLock( os2File *pFile ){
22596   FILELOCK  LockArea,
22597             UnlockArea;
22598   APIRET res;
22599   memset(&LockArea, 0, sizeof(LockArea));
22600   memset(&UnlockArea, 0, sizeof(UnlockArea));
22601   LockArea.lOffset = SHARED_FIRST;
22602   LockArea.lRange = SHARED_SIZE;
22603   UnlockArea.lOffset = 0L;
22604   UnlockArea.lRange = 0L;
22605   res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
22606   OSTRACE(( "GETREADLOCK %d res=%d\n", pFile->h, res ));
22607   return res;
22608 }
22609
22610 /*
22611 ** Undo a readlock
22612 */
22613 static int unlockReadLock( os2File *id ){
22614   FILELOCK  LockArea,
22615             UnlockArea;
22616   APIRET res;
22617   memset(&LockArea, 0, sizeof(LockArea));
22618   memset(&UnlockArea, 0, sizeof(UnlockArea));
22619   LockArea.lOffset = 0L;
22620   LockArea.lRange = 0L;
22621   UnlockArea.lOffset = SHARED_FIRST;
22622   UnlockArea.lRange = SHARED_SIZE;
22623   res = DosSetFileLocks( id->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
22624   OSTRACE(( "UNLOCK-READLOCK file handle=%d res=%d?\n", id->h, res ));
22625   return res;
22626 }
22627
22628 /*
22629 ** Lock the file with the lock specified by parameter locktype - one
22630 ** of the following:
22631 **
22632 **     (1) SHARED_LOCK
22633 **     (2) RESERVED_LOCK
22634 **     (3) PENDING_LOCK
22635 **     (4) EXCLUSIVE_LOCK
22636 **
22637 ** Sometimes when requesting one lock state, additional lock states
22638 ** are inserted in between.  The locking might fail on one of the later
22639 ** transitions leaving the lock state different from what it started but
22640 ** still short of its goal.  The following chart shows the allowed
22641 ** transitions and the inserted intermediate states:
22642 **
22643 **    UNLOCKED -> SHARED
22644 **    SHARED -> RESERVED
22645 **    SHARED -> (PENDING) -> EXCLUSIVE
22646 **    RESERVED -> (PENDING) -> EXCLUSIVE
22647 **    PENDING -> EXCLUSIVE
22648 **
22649 ** This routine will only increase a lock.  The os2Unlock() routine
22650 ** erases all locks at once and returns us immediately to locking level 0.
22651 ** It is not possible to lower the locking level one step at a time.  You
22652 ** must go straight to locking level 0.
22653 */
22654 static int os2Lock( sqlite3_file *id, int locktype ){
22655   int rc = SQLITE_OK;       /* Return code from subroutines */
22656   APIRET res = NO_ERROR;    /* Result of an OS/2 lock call */
22657   int newLocktype;       /* Set pFile->locktype to this value before exiting */
22658   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
22659   FILELOCK  LockArea,
22660             UnlockArea;
22661   os2File *pFile = (os2File*)id;
22662   memset(&LockArea, 0, sizeof(LockArea));
22663   memset(&UnlockArea, 0, sizeof(UnlockArea));
22664   assert( pFile!=0 );
22665   OSTRACE(( "LOCK %d %d was %d\n", pFile->h, locktype, pFile->locktype ));
22666
22667   /* If there is already a lock of this type or more restrictive on the
22668   ** os2File, do nothing. Don't use the end_lock: exit path, as
22669   ** sqlite3_mutex_enter() hasn't been called yet.
22670   */
22671   if( pFile->locktype>=locktype ){
22672     OSTRACE(( "LOCK %d %d ok (already held)\n", pFile->h, locktype ));
22673     return SQLITE_OK;
22674   }
22675
22676   /* Make sure the locking sequence is correct
22677   */
22678   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
22679   assert( locktype!=PENDING_LOCK );
22680   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
22681
22682   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
22683   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
22684   ** the PENDING_LOCK byte is temporary.
22685   */
22686   newLocktype = pFile->locktype;
22687   if( pFile->locktype==NO_LOCK
22688       || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
22689   ){
22690     LockArea.lOffset = PENDING_BYTE;
22691     LockArea.lRange = 1L;
22692     UnlockArea.lOffset = 0L;
22693     UnlockArea.lRange = 0L;
22694
22695     /* wait longer than LOCK_TIMEOUT here not to have to try multiple times */
22696     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 100L, 0L );
22697     if( res == NO_ERROR ){
22698       gotPendingLock = 1;
22699       OSTRACE(( "LOCK %d pending lock boolean set.  res=%d\n", pFile->h, res ));
22700     }
22701   }
22702
22703   /* Acquire a shared lock
22704   */
22705   if( locktype==SHARED_LOCK && res == NO_ERROR ){
22706     assert( pFile->locktype==NO_LOCK );
22707     res = getReadLock(pFile);
22708     if( res == NO_ERROR ){
22709       newLocktype = SHARED_LOCK;
22710     }
22711     OSTRACE(( "LOCK %d acquire shared lock. res=%d\n", pFile->h, res ));
22712   }
22713
22714   /* Acquire a RESERVED lock
22715   */
22716   if( locktype==RESERVED_LOCK && res == NO_ERROR ){
22717     assert( pFile->locktype==SHARED_LOCK );
22718     LockArea.lOffset = RESERVED_BYTE;
22719     LockArea.lRange = 1L;
22720     UnlockArea.lOffset = 0L;
22721     UnlockArea.lRange = 0L;
22722     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22723     if( res == NO_ERROR ){
22724       newLocktype = RESERVED_LOCK;
22725     }
22726     OSTRACE(( "LOCK %d acquire reserved lock. res=%d\n", pFile->h, res ));
22727   }
22728
22729   /* Acquire a PENDING lock
22730   */
22731   if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
22732     newLocktype = PENDING_LOCK;
22733     gotPendingLock = 0;
22734     OSTRACE(( "LOCK %d acquire pending lock. pending lock boolean unset.\n",
22735                pFile->h ));
22736   }
22737
22738   /* Acquire an EXCLUSIVE lock
22739   */
22740   if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
22741     assert( pFile->locktype>=SHARED_LOCK );
22742     res = unlockReadLock(pFile);
22743     OSTRACE(( "unreadlock = %d\n", res ));
22744     LockArea.lOffset = SHARED_FIRST;
22745     LockArea.lRange = SHARED_SIZE;
22746     UnlockArea.lOffset = 0L;
22747     UnlockArea.lRange = 0L;
22748     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22749     if( res == NO_ERROR ){
22750       newLocktype = EXCLUSIVE_LOCK;
22751     }else{
22752       OSTRACE(( "OS/2 error-code = %d\n", res ));
22753       getReadLock(pFile);
22754     }
22755     OSTRACE(( "LOCK %d acquire exclusive lock.  res=%d\n", pFile->h, res ));
22756   }
22757
22758   /* If we are holding a PENDING lock that ought to be released, then
22759   ** release it now.
22760   */
22761   if( gotPendingLock && locktype==SHARED_LOCK ){
22762     int r;
22763     LockArea.lOffset = 0L;
22764     LockArea.lRange = 0L;
22765     UnlockArea.lOffset = PENDING_BYTE;
22766     UnlockArea.lRange = 1L;
22767     r = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22768     OSTRACE(( "LOCK %d unlocking pending/is shared. r=%d\n", pFile->h, r ));
22769   }
22770
22771   /* Update the state of the lock has held in the file descriptor then
22772   ** return the appropriate result code.
22773   */
22774   if( res == NO_ERROR ){
22775     rc = SQLITE_OK;
22776   }else{
22777     OSTRACE(( "LOCK FAILED %d trying for %d but got %d\n", pFile->h,
22778               locktype, newLocktype ));
22779     rc = SQLITE_BUSY;
22780   }
22781   pFile->locktype = newLocktype;
22782   OSTRACE(( "LOCK %d now %d\n", pFile->h, pFile->locktype ));
22783   return rc;
22784 }
22785
22786 /*
22787 ** This routine checks if there is a RESERVED lock held on the specified
22788 ** file by this or any other process. If such a lock is held, return
22789 ** non-zero, otherwise zero.
22790 */
22791 static int os2CheckReservedLock( sqlite3_file *id, int *pOut ){
22792   int r = 0;
22793   os2File *pFile = (os2File*)id;
22794   assert( pFile!=0 );
22795   if( pFile->locktype>=RESERVED_LOCK ){
22796     r = 1;
22797     OSTRACE(( "TEST WR-LOCK %d %d (local)\n", pFile->h, r ));
22798   }else{
22799     FILELOCK  LockArea,
22800               UnlockArea;
22801     APIRET rc = NO_ERROR;
22802     memset(&LockArea, 0, sizeof(LockArea));
22803     memset(&UnlockArea, 0, sizeof(UnlockArea));
22804     LockArea.lOffset = RESERVED_BYTE;
22805     LockArea.lRange = 1L;
22806     UnlockArea.lOffset = 0L;
22807     UnlockArea.lRange = 0L;
22808     rc = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22809     OSTRACE(( "TEST WR-LOCK %d lock reserved byte rc=%d\n", pFile->h, rc ));
22810     if( rc == NO_ERROR ){
22811       APIRET rcu = NO_ERROR; /* return code for unlocking */
22812       LockArea.lOffset = 0L;
22813       LockArea.lRange = 0L;
22814       UnlockArea.lOffset = RESERVED_BYTE;
22815       UnlockArea.lRange = 1L;
22816       rcu = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22817       OSTRACE(( "TEST WR-LOCK %d unlock reserved byte r=%d\n", pFile->h, rcu ));
22818     }
22819     r = !(rc == NO_ERROR);
22820     OSTRACE(( "TEST WR-LOCK %d %d (remote)\n", pFile->h, r ));
22821   }
22822   *pOut = r;
22823   return SQLITE_OK;
22824 }
22825
22826 /*
22827 ** Lower the locking level on file descriptor id to locktype.  locktype
22828 ** must be either NO_LOCK or SHARED_LOCK.
22829 **
22830 ** If the locking level of the file descriptor is already at or below
22831 ** the requested locking level, this routine is a no-op.
22832 **
22833 ** It is not possible for this routine to fail if the second argument
22834 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
22835 ** might return SQLITE_IOERR;
22836 */
22837 static int os2Unlock( sqlite3_file *id, int locktype ){
22838   int type;
22839   os2File *pFile = (os2File*)id;
22840   APIRET rc = SQLITE_OK;
22841   APIRET res = NO_ERROR;
22842   FILELOCK  LockArea,
22843             UnlockArea;
22844   memset(&LockArea, 0, sizeof(LockArea));
22845   memset(&UnlockArea, 0, sizeof(UnlockArea));
22846   assert( pFile!=0 );
22847   assert( locktype<=SHARED_LOCK );
22848   OSTRACE(( "UNLOCK %d to %d was %d\n", pFile->h, locktype, pFile->locktype ));
22849   type = pFile->locktype;
22850   if( type>=EXCLUSIVE_LOCK ){
22851     LockArea.lOffset = 0L;
22852     LockArea.lRange = 0L;
22853     UnlockArea.lOffset = SHARED_FIRST;
22854     UnlockArea.lRange = SHARED_SIZE;
22855     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22856     OSTRACE(( "UNLOCK %d exclusive lock res=%d\n", pFile->h, res ));
22857     if( locktype==SHARED_LOCK && getReadLock(pFile) != NO_ERROR ){
22858       /* This should never happen.  We should always be able to
22859       ** reacquire the read lock */
22860       OSTRACE(( "UNLOCK %d to %d getReadLock() failed\n", pFile->h, locktype ));
22861       rc = SQLITE_IOERR_UNLOCK;
22862     }
22863   }
22864   if( type>=RESERVED_LOCK ){
22865     LockArea.lOffset = 0L;
22866     LockArea.lRange = 0L;
22867     UnlockArea.lOffset = RESERVED_BYTE;
22868     UnlockArea.lRange = 1L;
22869     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22870     OSTRACE(( "UNLOCK %d reserved res=%d\n", pFile->h, res ));
22871   }
22872   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
22873     res = unlockReadLock(pFile);
22874     OSTRACE(( "UNLOCK %d is %d want %d res=%d\n",
22875               pFile->h, type, locktype, res ));
22876   }
22877   if( type>=PENDING_LOCK ){
22878     LockArea.lOffset = 0L;
22879     LockArea.lRange = 0L;
22880     UnlockArea.lOffset = PENDING_BYTE;
22881     UnlockArea.lRange = 1L;
22882     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22883     OSTRACE(( "UNLOCK %d pending res=%d\n", pFile->h, res ));
22884   }
22885   pFile->locktype = locktype;
22886   OSTRACE(( "UNLOCK %d now %d\n", pFile->h, pFile->locktype ));
22887   return rc;
22888 }
22889
22890 /*
22891 ** Control and query of the open file handle.
22892 */
22893 static int os2FileControl(sqlite3_file *id, int op, void *pArg){
22894   switch( op ){
22895     case SQLITE_FCNTL_LOCKSTATE: {
22896       *(int*)pArg = ((os2File*)id)->locktype;
22897       OSTRACE(( "FCNTL_LOCKSTATE %d lock=%d\n",
22898                 ((os2File*)id)->h, ((os2File*)id)->locktype ));
22899       return SQLITE_OK;
22900     }
22901     case SQLITE_FCNTL_CHUNK_SIZE: {
22902       ((os2File*)id)->szChunk = *(int*)pArg;
22903       return SQLITE_OK;
22904     }
22905     case SQLITE_FCNTL_SIZE_HINT: {
22906       sqlite3_int64 sz = *(sqlite3_int64*)pArg;
22907       SimulateIOErrorBenign(1);
22908       os2Truncate(id, sz);
22909       SimulateIOErrorBenign(0);
22910       return SQLITE_OK;
22911     }
22912     case SQLITE_FCNTL_SYNC_OMITTED: {
22913       return SQLITE_OK;
22914     }
22915   }
22916   return SQLITE_NOTFOUND;
22917 }
22918
22919 /*
22920 ** Return the sector size in bytes of the underlying block device for
22921 ** the specified file. This is almost always 512 bytes, but may be
22922 ** larger for some devices.
22923 **
22924 ** SQLite code assumes this function cannot fail. It also assumes that
22925 ** if two files are created in the same file-system directory (i.e.
22926 ** a database and its journal file) that the sector size will be the
22927 ** same for both.
22928 */
22929 static int os2SectorSize(sqlite3_file *id){
22930   UNUSED_PARAMETER(id);
22931   return SQLITE_DEFAULT_SECTOR_SIZE;
22932 }
22933
22934 /*
22935 ** Return a vector of device characteristics.
22936 */
22937 static int os2DeviceCharacteristics(sqlite3_file *id){
22938   UNUSED_PARAMETER(id);
22939   return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN;
22940 }
22941
22942
22943 /*
22944 ** Character set conversion objects used by conversion routines.
22945 */
22946 static UconvObject ucUtf8 = NULL; /* convert between UTF-8 and UCS-2 */
22947 static UconvObject uclCp = NULL;  /* convert between local codepage and UCS-2 */
22948
22949 /*
22950 ** Helper function to initialize the conversion objects from and to UTF-8.
22951 */
22952 static void initUconvObjects( void ){
22953   if( UniCreateUconvObject( UTF_8, &ucUtf8 ) != ULS_SUCCESS )
22954     ucUtf8 = NULL;
22955   if ( UniCreateUconvObject( (UniChar *)L"@path=yes", &uclCp ) != ULS_SUCCESS )
22956     uclCp = NULL;
22957 }
22958
22959 /*
22960 ** Helper function to free the conversion objects from and to UTF-8.
22961 */
22962 static void freeUconvObjects( void ){
22963   if ( ucUtf8 )
22964     UniFreeUconvObject( ucUtf8 );
22965   if ( uclCp )
22966     UniFreeUconvObject( uclCp );
22967   ucUtf8 = NULL;
22968   uclCp = NULL;
22969 }
22970
22971 /*
22972 ** Helper function to convert UTF-8 filenames to local OS/2 codepage.
22973 ** The two-step process: first convert the incoming UTF-8 string
22974 ** into UCS-2 and then from UCS-2 to the current codepage.
22975 ** The returned char pointer has to be freed.
22976 */
22977 static char *convertUtf8PathToCp( const char *in ){
22978   UniChar tempPath[CCHMAXPATH];
22979   char *out = (char *)calloc( CCHMAXPATH, 1 );
22980
22981   if( !out )
22982     return NULL;
22983
22984   if( !ucUtf8 || !uclCp )
22985     initUconvObjects();
22986
22987   /* determine string for the conversion of UTF-8 which is CP1208 */
22988   if( UniStrToUcs( ucUtf8, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
22989     return out; /* if conversion fails, return the empty string */
22990
22991   /* conversion for current codepage which can be used for paths */
22992   UniStrFromUcs( uclCp, out, tempPath, CCHMAXPATH );
22993
22994   return out;
22995 }
22996
22997 /*
22998 ** Helper function to convert filenames from local codepage to UTF-8.
22999 ** The two-step process: first convert the incoming codepage-specific
23000 ** string into UCS-2 and then from UCS-2 to the codepage of UTF-8.
23001 ** The returned char pointer has to be freed.
23002 **
23003 ** This function is non-static to be able to use this in shell.c and
23004 ** similar applications that take command line arguments.
23005 */
23006 char *convertCpPathToUtf8( const char *in ){
23007   UniChar tempPath[CCHMAXPATH];
23008   char *out = (char *)calloc( CCHMAXPATH, 1 );
23009
23010   if( !out )
23011     return NULL;
23012
23013   if( !ucUtf8 || !uclCp )
23014     initUconvObjects();
23015
23016   /* conversion for current codepage which can be used for paths */
23017   if( UniStrToUcs( uclCp, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
23018     return out; /* if conversion fails, return the empty string */
23019
23020   /* determine string for the conversion of UTF-8 which is CP1208 */
23021   UniStrFromUcs( ucUtf8, out, tempPath, CCHMAXPATH );
23022
23023   return out;
23024 }
23025
23026
23027 #ifndef SQLITE_OMIT_WAL
23028
23029 /*
23030 ** Use main database file for interprocess locking. If un-defined
23031 ** a separate file is created for this purpose. The file will be
23032 ** used only to set file locks. There will be no data written to it.
23033 */
23034 #define SQLITE_OS2_NO_WAL_LOCK_FILE     
23035
23036 #if 0
23037 static void _ERR_TRACE( const char *fmt, ... ) {
23038   va_list  ap;
23039   va_start(ap, fmt);
23040   vfprintf(stderr, fmt, ap);
23041   fflush(stderr);
23042 }
23043 #define ERR_TRACE(rc, msg)        \
23044         if( (rc) != SQLITE_OK ) _ERR_TRACE msg;
23045 #else
23046 #define ERR_TRACE(rc, msg)
23047 #endif
23048
23049 /*
23050 ** Helper functions to obtain and relinquish the global mutex. The
23051 ** global mutex is used to protect os2ShmNodeList.
23052 **
23053 ** Function os2ShmMutexHeld() is used to assert() that the global mutex 
23054 ** is held when required. This function is only used as part of assert() 
23055 ** statements. e.g.
23056 **
23057 **   os2ShmEnterMutex()
23058 **     assert( os2ShmMutexHeld() );
23059 **   os2ShmLeaveMutex()
23060 */
23061 static void os2ShmEnterMutex(void){
23062   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23063 }
23064 static void os2ShmLeaveMutex(void){
23065   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23066 }
23067 #ifdef SQLITE_DEBUG
23068 static int os2ShmMutexHeld(void) {
23069   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23070 }
23071 int GetCurrentProcessId(void) {
23072   PPIB pib;
23073   DosGetInfoBlocks(NULL, &pib);
23074   return (int)pib->pib_ulpid;
23075 }
23076 #endif
23077
23078 /*
23079 ** Object used to represent a the shared memory area for a single log file.
23080 ** When multiple threads all reference the same log-summary, each thread has
23081 ** its own os2File object, but they all point to a single instance of this 
23082 ** object.  In other words, each log-summary is opened only once per process.
23083 **
23084 ** os2ShmMutexHeld() must be true when creating or destroying
23085 ** this object or while reading or writing the following fields:
23086 **
23087 **      nRef
23088 **      pNext 
23089 **
23090 ** The following fields are read-only after the object is created:
23091 ** 
23092 **      szRegion
23093 **      hLockFile
23094 **      shmBaseName
23095 **
23096 ** Either os2ShmNode.mutex must be held or os2ShmNode.nRef==0 and
23097 ** os2ShmMutexHeld() is true when reading or writing any other field
23098 ** in this structure.
23099 **
23100 */
23101 struct os2ShmNode {
23102   sqlite3_mutex *mutex;      /* Mutex to access this object */
23103   os2ShmNode *pNext;         /* Next in list of all os2ShmNode objects */
23104
23105   int szRegion;              /* Size of shared-memory regions */
23106
23107   int nRegion;               /* Size of array apRegion */
23108   void **apRegion;           /* Array of pointers to shared-memory regions */
23109
23110   int nRef;                  /* Number of os2ShmLink objects pointing to this */
23111   os2ShmLink *pFirst;        /* First os2ShmLink object pointing to this */
23112
23113   HFILE hLockFile;           /* File used for inter-process memory locking */
23114   char shmBaseName[1];       /* Name of the memory object !!! must last !!! */
23115 };
23116
23117
23118 /*
23119 ** Structure used internally by this VFS to record the state of an
23120 ** open shared memory connection.
23121 **
23122 ** The following fields are initialized when this object is created and
23123 ** are read-only thereafter:
23124 **
23125 **    os2Shm.pShmNode
23126 **    os2Shm.id
23127 **
23128 ** All other fields are read/write.  The os2Shm.pShmNode->mutex must be held
23129 ** while accessing any read/write fields.
23130 */
23131 struct os2ShmLink {
23132   os2ShmNode *pShmNode;      /* The underlying os2ShmNode object */
23133   os2ShmLink *pNext;         /* Next os2Shm with the same os2ShmNode */
23134   u32 sharedMask;            /* Mask of shared locks held */
23135   u32 exclMask;              /* Mask of exclusive locks held */
23136 #ifdef SQLITE_DEBUG
23137   u8 id;                     /* Id of this connection with its os2ShmNode */
23138 #endif
23139 };
23140
23141
23142 /*
23143 ** A global list of all os2ShmNode objects.
23144 **
23145 ** The os2ShmMutexHeld() must be true while reading or writing this list.
23146 */
23147 static os2ShmNode *os2ShmNodeList = NULL;
23148
23149 /*
23150 ** Constants used for locking
23151 */
23152 #ifdef  SQLITE_OS2_NO_WAL_LOCK_FILE
23153 #define OS2_SHM_BASE   (PENDING_BYTE + 0x10000)         /* first lock byte */
23154 #else
23155 #define OS2_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
23156 #endif
23157
23158 #define OS2_SHM_DMS    (OS2_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
23159
23160 /*
23161 ** Apply advisory locks for all n bytes beginning at ofst.
23162 */
23163 #define _SHM_UNLCK  1   /* no lock */
23164 #define _SHM_RDLCK  2   /* shared lock, no wait */
23165 #define _SHM_WRLCK  3   /* exlusive lock, no wait */
23166 #define _SHM_WRLCK_WAIT 4 /* exclusive lock, wait */
23167 static int os2ShmSystemLock(
23168   os2ShmNode *pNode,    /* Apply locks to this open shared-memory segment */
23169   int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, _SHM_WRLCK or _SHM_WRLCK_WAIT */
23170   int ofst,             /* Offset to first byte to be locked/unlocked */
23171   int nByte             /* Number of bytes to lock or unlock */
23172 ){
23173   APIRET rc;
23174   FILELOCK area;
23175   ULONG mode, timeout;
23176
23177   /* Access to the os2ShmNode object is serialized by the caller */
23178   assert( sqlite3_mutex_held(pNode->mutex) || pNode->nRef==0 );
23179
23180   mode = 1;     /* shared lock */
23181   timeout = 0;  /* no wait */
23182   area.lOffset = ofst;
23183   area.lRange = nByte;
23184
23185   switch( lockType ) {
23186     case _SHM_WRLCK_WAIT:
23187       timeout = (ULONG)-1;      /* wait forever */
23188     case _SHM_WRLCK:
23189       mode = 0;                 /* exclusive lock */
23190     case _SHM_RDLCK:
23191       rc = DosSetFileLocks(pNode->hLockFile, 
23192                            NULL, &area, timeout, mode);
23193       break;
23194     /* case _SHM_UNLCK: */
23195     default:
23196       rc = DosSetFileLocks(pNode->hLockFile, 
23197                            &area, NULL, 0, 0);
23198       break;
23199   }
23200                           
23201   OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n", 
23202            pNode->hLockFile,
23203            rc==SQLITE_OK ? "ok" : "failed",
23204            lockType==_SHM_UNLCK ? "Unlock" : "Lock",
23205            rc));
23206
23207   ERR_TRACE(rc, ("os2ShmSystemLock: %d %s\n", rc, pNode->shmBaseName))
23208
23209   return ( rc == 0 ) ?  SQLITE_OK : SQLITE_BUSY;
23210 }
23211
23212 /*
23213 ** Find an os2ShmNode in global list or allocate a new one, if not found.
23214 **
23215 ** This is not a VFS shared-memory method; it is a utility function called
23216 ** by VFS shared-memory methods.
23217 */
23218 static int os2OpenSharedMemory( os2File *fd, int szRegion ) {
23219   os2ShmLink *pLink;
23220   os2ShmNode *pNode;
23221   int cbShmName, rc = SQLITE_OK;
23222   char shmName[CCHMAXPATH + 30];
23223 #ifndef SQLITE_OS2_NO_WAL_LOCK_FILE
23224   ULONG action;
23225 #endif
23226   
23227   /* We need some additional space at the end to append the region number */
23228   cbShmName = sprintf(shmName, "\\SHAREMEM\\%s", fd->zFullPathCp );
23229   if( cbShmName >= CCHMAXPATH-8 )
23230     return SQLITE_IOERR_SHMOPEN; 
23231
23232   /* Replace colon in file name to form a valid shared memory name */
23233   shmName[10+1] = '!';
23234
23235   /* Allocate link object (we free it later in case of failure) */
23236   pLink = sqlite3_malloc( sizeof(*pLink) );
23237   if( !pLink )
23238     return SQLITE_NOMEM;
23239
23240   /* Access node list */
23241   os2ShmEnterMutex();
23242
23243   /* Find node by it's shared memory base name */
23244   for( pNode = os2ShmNodeList; 
23245        pNode && stricmp(shmName, pNode->shmBaseName) != 0; 
23246        pNode = pNode->pNext )   ;
23247
23248   /* Not found: allocate a new node */
23249   if( !pNode ) {
23250     pNode = sqlite3_malloc( sizeof(*pNode) + cbShmName );
23251     if( pNode ) {
23252       memset(pNode, 0, sizeof(*pNode) );
23253       pNode->szRegion = szRegion;
23254       pNode->hLockFile = (HFILE)-1;      
23255       strcpy(pNode->shmBaseName, shmName);
23256
23257 #ifdef SQLITE_OS2_NO_WAL_LOCK_FILE
23258       if( DosDupHandle(fd->h, &pNode->hLockFile) != 0 ) {
23259 #else
23260       sprintf(shmName, "%s-lck", fd->zFullPathCp);
23261       if( DosOpen((PSZ)shmName, &pNode->hLockFile, &action, 0, FILE_NORMAL, 
23262                   OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW,
23263                   OPEN_ACCESS_READWRITE | OPEN_SHARE_DENYNONE | 
23264                   OPEN_FLAGS_NOINHERIT | OPEN_FLAGS_FAIL_ON_ERROR,
23265                   NULL) != 0 ) {
23266 #endif
23267         sqlite3_free(pNode);  
23268         rc = SQLITE_IOERR;
23269       } else {
23270         pNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
23271         if( !pNode->mutex ) {
23272           sqlite3_free(pNode);  
23273           rc = SQLITE_NOMEM;
23274         }
23275       }   
23276     } else {
23277       rc = SQLITE_NOMEM;
23278     }
23279     
23280     if( rc == SQLITE_OK ) {
23281       pNode->pNext = os2ShmNodeList;
23282       os2ShmNodeList = pNode;
23283     } else {
23284       pNode = NULL;
23285     }
23286   } else if( pNode->szRegion != szRegion ) {
23287     rc = SQLITE_IOERR_SHMSIZE;
23288     pNode = NULL;
23289   }
23290
23291   if( pNode ) {
23292     sqlite3_mutex_enter(pNode->mutex);
23293
23294     memset(pLink, 0, sizeof(*pLink));
23295
23296     pLink->pShmNode = pNode;
23297     pLink->pNext = pNode->pFirst;
23298     pNode->pFirst = pLink;
23299     pNode->nRef++;
23300
23301     fd->pShmLink = pLink;
23302
23303     sqlite3_mutex_leave(pNode->mutex);
23304     
23305   } else {
23306     /* Error occured. Free our link object. */
23307     sqlite3_free(pLink);  
23308   }
23309
23310   os2ShmLeaveMutex();
23311
23312   ERR_TRACE(rc, ("os2OpenSharedMemory: %d  %s\n", rc, fd->zFullPathCp))  
23313   
23314   return rc;
23315 }
23316
23317 /*
23318 ** Purge the os2ShmNodeList list of all entries with nRef==0.
23319 **
23320 ** This is not a VFS shared-memory method; it is a utility function called
23321 ** by VFS shared-memory methods.
23322 */
23323 static void os2PurgeShmNodes( int deleteFlag ) {
23324   os2ShmNode *pNode;
23325   os2ShmNode **ppNode;
23326
23327   os2ShmEnterMutex();
23328   
23329   ppNode = &os2ShmNodeList;
23330
23331   while( *ppNode ) {
23332     pNode = *ppNode;
23333
23334     if( pNode->nRef == 0 ) {
23335       *ppNode = pNode->pNext;   
23336      
23337       if( pNode->apRegion ) {
23338         /* Prevent other processes from resizing the shared memory */
23339         os2ShmSystemLock(pNode, _SHM_WRLCK_WAIT, OS2_SHM_DMS, 1);
23340
23341         while( pNode->nRegion-- ) {
23342 #ifdef SQLITE_DEBUG
23343           int rc = 
23344 #endif          
23345           DosFreeMem(pNode->apRegion[pNode->nRegion]);
23346
23347           OSTRACE(("SHM-PURGE pid-%d unmap region=%d %s\n",
23348                   (int)GetCurrentProcessId(), pNode->nRegion,
23349                   rc == 0 ? "ok" : "failed"));
23350         }
23351
23352         /* Allow other processes to resize the shared memory */
23353         os2ShmSystemLock(pNode, _SHM_UNLCK, OS2_SHM_DMS, 1);
23354
23355         sqlite3_free(pNode->apRegion);
23356       }  
23357
23358       DosClose(pNode->hLockFile);
23359       
23360 #ifndef SQLITE_OS2_NO_WAL_LOCK_FILE
23361       if( deleteFlag ) {
23362          char fileName[CCHMAXPATH];
23363          /* Skip "\\SHAREMEM\\" */
23364          sprintf(fileName, "%s-lck", pNode->shmBaseName + 10);
23365          /* restore colon */
23366          fileName[1] = ':';
23367          
23368          DosForceDelete(fileName); 
23369       }
23370 #endif
23371
23372       sqlite3_mutex_free(pNode->mutex);
23373
23374       sqlite3_free(pNode);
23375       
23376     } else {
23377       ppNode = &pNode->pNext;
23378     }
23379   } 
23380
23381   os2ShmLeaveMutex();
23382 }
23383
23384 /*
23385 ** This function is called to obtain a pointer to region iRegion of the
23386 ** shared-memory associated with the database file id. Shared-memory regions
23387 ** are numbered starting from zero. Each shared-memory region is szRegion
23388 ** bytes in size.
23389 **
23390 ** If an error occurs, an error code is returned and *pp is set to NULL.
23391 **
23392 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
23393 ** region has not been allocated (by any client, including one running in a
23394 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
23395 ** bExtend is non-zero and the requested shared-memory region has not yet
23396 ** been allocated, it is allocated by this function.
23397 **
23398 ** If the shared-memory region has already been allocated or is allocated by
23399 ** this call as described above, then it is mapped into this processes
23400 ** address space (if it is not already), *pp is set to point to the mapped
23401 ** memory and SQLITE_OK returned.
23402 */
23403 static int os2ShmMap(
23404   sqlite3_file *id,               /* Handle open on database file */
23405   int iRegion,                    /* Region to retrieve */
23406   int szRegion,                   /* Size of regions */
23407   int bExtend,                    /* True to extend block if necessary */
23408   void volatile **pp              /* OUT: Mapped memory */
23409 ){
23410   PVOID pvTemp;
23411   void **apRegion;
23412   os2ShmNode *pNode;
23413   int n, rc = SQLITE_OK;
23414   char shmName[CCHMAXPATH];
23415   os2File *pFile = (os2File*)id;
23416   
23417   *pp = NULL;
23418
23419   if( !pFile->pShmLink )
23420     rc = os2OpenSharedMemory( pFile, szRegion );
23421   
23422   if( rc == SQLITE_OK ) {
23423     pNode = pFile->pShmLink->pShmNode ;
23424     
23425     sqlite3_mutex_enter(pNode->mutex);
23426     
23427     assert( szRegion==pNode->szRegion );
23428
23429     /* Unmapped region ? */
23430     if( iRegion >= pNode->nRegion ) {
23431       /* Prevent other processes from resizing the shared memory */
23432       os2ShmSystemLock(pNode, _SHM_WRLCK_WAIT, OS2_SHM_DMS, 1);
23433
23434       apRegion = sqlite3_realloc(
23435         pNode->apRegion, (iRegion + 1) * sizeof(apRegion[0]));
23436
23437       if( apRegion ) {
23438         pNode->apRegion = apRegion;
23439
23440         while( pNode->nRegion <= iRegion ) {
23441           sprintf(shmName, "%s-%u", 
23442                   pNode->shmBaseName, pNode->nRegion);
23443
23444           if( DosGetNamedSharedMem(&pvTemp, (PSZ)shmName, 
23445                 PAG_READ | PAG_WRITE) != NO_ERROR ) {
23446             if( !bExtend )
23447               break;
23448
23449             if( DosAllocSharedMem(&pvTemp, (PSZ)shmName, szRegion,
23450                   PAG_READ | PAG_WRITE | PAG_COMMIT | OBJ_ANY) != NO_ERROR && 
23451                 DosAllocSharedMem(&pvTemp, (PSZ)shmName, szRegion,
23452                   PAG_READ | PAG_WRITE | PAG_COMMIT) != NO_ERROR ) { 
23453               rc = SQLITE_NOMEM;
23454               break;
23455             }
23456           }
23457
23458           apRegion[pNode->nRegion++] = pvTemp;
23459         }
23460
23461         /* zero out remaining entries */ 
23462         for( n = pNode->nRegion; n <= iRegion; n++ )
23463           pNode->apRegion[n] = NULL;
23464
23465         /* Return this region (maybe zero) */
23466         *pp = pNode->apRegion[iRegion];
23467       } else {
23468         rc = SQLITE_NOMEM;
23469       }
23470
23471       /* Allow other processes to resize the shared memory */
23472       os2ShmSystemLock(pNode, _SHM_UNLCK, OS2_SHM_DMS, 1);
23473       
23474     } else {
23475       /* Region has been mapped previously */
23476       *pp = pNode->apRegion[iRegion];
23477     }
23478
23479     sqlite3_mutex_leave(pNode->mutex);
23480   } 
23481
23482   ERR_TRACE(rc, ("os2ShmMap: %s iRgn = %d, szRgn = %d, bExt = %d : %d\n", 
23483                  pFile->zFullPathCp, iRegion, szRegion, bExtend, rc))
23484           
23485   return rc;
23486 }
23487
23488 /*
23489 ** Close a connection to shared-memory.  Delete the underlying
23490 ** storage if deleteFlag is true.
23491 **
23492 ** If there is no shared memory associated with the connection then this
23493 ** routine is a harmless no-op.
23494 */
23495 static int os2ShmUnmap(
23496   sqlite3_file *id,               /* The underlying database file */
23497   int deleteFlag                  /* Delete shared-memory if true */
23498 ){
23499   os2File *pFile = (os2File*)id;
23500   os2ShmLink *pLink = pFile->pShmLink;
23501   
23502   if( pLink ) {
23503     int nRef = -1;
23504     os2ShmLink **ppLink;
23505     os2ShmNode *pNode = pLink->pShmNode;
23506
23507     sqlite3_mutex_enter(pNode->mutex);
23508     
23509     for( ppLink = &pNode->pFirst;
23510          *ppLink && *ppLink != pLink;
23511          ppLink = &(*ppLink)->pNext )   ;
23512          
23513     assert(*ppLink);
23514
23515     if( *ppLink ) {
23516       *ppLink = pLink->pNext;
23517       nRef = --pNode->nRef;
23518     } else {
23519       ERR_TRACE(1, ("os2ShmUnmap: link not found ! %s\n", 
23520                     pNode->shmBaseName))
23521     }
23522     
23523     pFile->pShmLink = NULL;
23524     sqlite3_free(pLink);
23525
23526     sqlite3_mutex_leave(pNode->mutex);
23527     
23528     if( nRef == 0 )
23529       os2PurgeShmNodes( deleteFlag );
23530   }
23531
23532   return SQLITE_OK;
23533 }
23534
23535 /*
23536 ** Change the lock state for a shared-memory segment.
23537 **
23538 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
23539 ** different here than in posix.  In xShmLock(), one can go from unlocked
23540 ** to shared and back or from unlocked to exclusive and back.  But one may
23541 ** not go from shared to exclusive or from exclusive to shared.
23542 */
23543 static int os2ShmLock(
23544   sqlite3_file *id,          /* Database file holding the shared memory */
23545   int ofst,                  /* First lock to acquire or release */
23546   int n,                     /* Number of locks to acquire or release */
23547   int flags                  /* What to do with the lock */
23548 ){
23549   u32 mask;                             /* Mask of locks to take or release */
23550   int rc = SQLITE_OK;                   /* Result code */
23551   os2File *pFile = (os2File*)id;
23552   os2ShmLink *p = pFile->pShmLink;      /* The shared memory being locked */
23553   os2ShmLink *pX;                       /* For looping over all siblings */
23554   os2ShmNode *pShmNode = p->pShmNode;   /* Our node */
23555   
23556   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
23557   assert( n>=1 );
23558   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
23559        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
23560        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
23561        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
23562   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
23563
23564   mask = (u32)((1U<<(ofst+n)) - (1U<<ofst));
23565   assert( n>1 || mask==(1<<ofst) );
23566
23567
23568   sqlite3_mutex_enter(pShmNode->mutex);
23569
23570   if( flags & SQLITE_SHM_UNLOCK ){
23571     u32 allMask = 0; /* Mask of locks held by siblings */
23572
23573     /* See if any siblings hold this same lock */
23574     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
23575       if( pX==p ) continue;
23576       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
23577       allMask |= pX->sharedMask;
23578     }
23579
23580     /* Unlock the system-level locks */
23581     if( (mask & allMask)==0 ){
23582       rc = os2ShmSystemLock(pShmNode, _SHM_UNLCK, ofst+OS2_SHM_BASE, n);
23583     }else{
23584       rc = SQLITE_OK;
23585     }
23586
23587     /* Undo the local locks */
23588     if( rc==SQLITE_OK ){
23589       p->exclMask &= ~mask;
23590       p->sharedMask &= ~mask;
23591     } 
23592   }else if( flags & SQLITE_SHM_SHARED ){
23593     u32 allShared = 0;  /* Union of locks held by connections other than "p" */
23594
23595     /* Find out which shared locks are already held by sibling connections.
23596     ** If any sibling already holds an exclusive lock, go ahead and return
23597     ** SQLITE_BUSY.
23598     */
23599     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
23600       if( (pX->exclMask & mask)!=0 ){
23601         rc = SQLITE_BUSY;
23602         break;
23603       }
23604       allShared |= pX->sharedMask;
23605     }
23606
23607     /* Get shared locks at the system level, if necessary */
23608     if( rc==SQLITE_OK ){
23609       if( (allShared & mask)==0 ){
23610         rc = os2ShmSystemLock(pShmNode, _SHM_RDLCK, ofst+OS2_SHM_BASE, n);
23611       }else{
23612         rc = SQLITE_OK;
23613       }
23614     }
23615
23616     /* Get the local shared locks */
23617     if( rc==SQLITE_OK ){
23618       p->sharedMask |= mask;
23619     }
23620   }else{
23621     /* Make sure no sibling connections hold locks that will block this
23622     ** lock.  If any do, return SQLITE_BUSY right away.
23623     */
23624     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
23625       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
23626         rc = SQLITE_BUSY;
23627         break;
23628       }
23629     }
23630   
23631     /* Get the exclusive locks at the system level.  Then if successful
23632     ** also mark the local connection as being locked.
23633     */
23634     if( rc==SQLITE_OK ){
23635       rc = os2ShmSystemLock(pShmNode, _SHM_WRLCK, ofst+OS2_SHM_BASE, n);
23636       if( rc==SQLITE_OK ){
23637         assert( (p->sharedMask & mask)==0 );
23638         p->exclMask |= mask;
23639       }
23640     }
23641   }
23642
23643   sqlite3_mutex_leave(pShmNode->mutex);
23644   
23645   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
23646            p->id, (int)GetCurrentProcessId(), p->sharedMask, p->exclMask,
23647            rc ? "failed" : "ok"));
23648
23649   ERR_TRACE(rc, ("os2ShmLock: ofst = %d, n = %d, flags = 0x%x -> %d \n", 
23650                  ofst, n, flags, rc))
23651                   
23652   return rc; 
23653 }
23654
23655 /*
23656 ** Implement a memory barrier or memory fence on shared memory.
23657 **
23658 ** All loads and stores begun before the barrier must complete before
23659 ** any load or store begun after the barrier.
23660 */
23661 static void os2ShmBarrier(
23662   sqlite3_file *id                /* Database file holding the shared memory */
23663 ){
23664   UNUSED_PARAMETER(id);
23665   os2ShmEnterMutex();
23666   os2ShmLeaveMutex();
23667 }
23668
23669 #else
23670 # define os2ShmMap     0
23671 # define os2ShmLock    0
23672 # define os2ShmBarrier 0
23673 # define os2ShmUnmap   0
23674 #endif /* #ifndef SQLITE_OMIT_WAL */
23675
23676
23677 /*
23678 ** This vector defines all the methods that can operate on an
23679 ** sqlite3_file for os2.
23680 */
23681 static const sqlite3_io_methods os2IoMethod = {
23682   2,                              /* iVersion */
23683   os2Close,                       /* xClose */
23684   os2Read,                        /* xRead */
23685   os2Write,                       /* xWrite */
23686   os2Truncate,                    /* xTruncate */
23687   os2Sync,                        /* xSync */
23688   os2FileSize,                    /* xFileSize */
23689   os2Lock,                        /* xLock */
23690   os2Unlock,                      /* xUnlock */
23691   os2CheckReservedLock,           /* xCheckReservedLock */
23692   os2FileControl,                 /* xFileControl */
23693   os2SectorSize,                  /* xSectorSize */
23694   os2DeviceCharacteristics,       /* xDeviceCharacteristics */
23695   os2ShmMap,                      /* xShmMap */
23696   os2ShmLock,                     /* xShmLock */
23697   os2ShmBarrier,                  /* xShmBarrier */
23698   os2ShmUnmap                     /* xShmUnmap */
23699 };
23700
23701
23702 /***************************************************************************
23703 ** Here ends the I/O methods that form the sqlite3_io_methods object.
23704 **
23705 ** The next block of code implements the VFS methods.
23706 ****************************************************************************/
23707
23708 /*
23709 ** Create a temporary file name in zBuf.  zBuf must be big enough to
23710 ** hold at pVfs->mxPathname characters.
23711 */
23712 static int getTempname(int nBuf, char *zBuf ){
23713   static const char zChars[] =
23714     "abcdefghijklmnopqrstuvwxyz"
23715     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
23716     "0123456789";
23717   int i, j;
23718   PSZ zTempPathCp;      
23719   char zTempPath[CCHMAXPATH];
23720   ULONG ulDriveNum, ulDriveMap;
23721   
23722   /* It's odd to simulate an io-error here, but really this is just
23723   ** using the io-error infrastructure to test that SQLite handles this
23724   ** function failing. 
23725   */
23726   SimulateIOError( return SQLITE_IOERR );
23727
23728   if( sqlite3_temp_directory ) {
23729     sqlite3_snprintf(CCHMAXPATH-30, zTempPath, "%s", sqlite3_temp_directory);
23730   } else if( DosScanEnv( (PSZ)"TEMP",   &zTempPathCp ) == NO_ERROR ||
23731              DosScanEnv( (PSZ)"TMP",    &zTempPathCp ) == NO_ERROR ||
23732              DosScanEnv( (PSZ)"TMPDIR", &zTempPathCp ) == NO_ERROR ) {
23733     char *zTempPathUTF = convertCpPathToUtf8( (char *)zTempPathCp );
23734     sqlite3_snprintf(CCHMAXPATH-30, zTempPath, "%s", zTempPathUTF);
23735     free( zTempPathUTF );
23736   } else if( DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap ) == NO_ERROR ) {
23737     zTempPath[0] = (char)('A' + ulDriveNum - 1);
23738     zTempPath[1] = ':'; 
23739     zTempPath[2] = '\0'; 
23740   } else {
23741     zTempPath[0] = '\0'; 
23742   }
23743   
23744   /* Strip off a trailing slashes or backslashes, otherwise we would get *
23745    * multiple (back)slashes which causes DosOpen() to fail.              *
23746    * Trailing spaces are not allowed, either.                            */
23747   j = sqlite3Strlen30(zTempPath);
23748   while( j > 0 && ( zTempPath[j-1] == '\\' || zTempPath[j-1] == '/' || 
23749                     zTempPath[j-1] == ' ' ) ){
23750     j--;
23751   }
23752   zTempPath[j] = '\0';
23753   
23754   /* We use 20 bytes to randomize the name */
23755   sqlite3_snprintf(nBuf-22, zBuf,
23756                    "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
23757   j = sqlite3Strlen30(zBuf);
23758   sqlite3_randomness( 20, &zBuf[j] );
23759   for( i = 0; i < 20; i++, j++ ){
23760     zBuf[j] = zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
23761   }
23762   zBuf[j] = 0;
23763
23764   OSTRACE(( "TEMP FILENAME: %s\n", zBuf ));
23765   return SQLITE_OK;
23766 }
23767
23768
23769 /*
23770 ** Turn a relative pathname into a full pathname.  Write the full
23771 ** pathname into zFull[].  zFull[] will be at least pVfs->mxPathname
23772 ** bytes in size.
23773 */
23774 static int os2FullPathname(
23775   sqlite3_vfs *pVfs,          /* Pointer to vfs object */
23776   const char *zRelative,      /* Possibly relative input path */
23777   int nFull,                  /* Size of output buffer in bytes */
23778   char *zFull                 /* Output buffer */
23779 ){
23780   char *zRelativeCp = convertUtf8PathToCp( zRelative );
23781   char zFullCp[CCHMAXPATH] = "\0";
23782   char *zFullUTF;
23783   APIRET rc = DosQueryPathInfo( (PSZ)zRelativeCp, FIL_QUERYFULLNAME, 
23784                                 zFullCp, CCHMAXPATH );
23785   free( zRelativeCp );
23786   zFullUTF = convertCpPathToUtf8( zFullCp );
23787   sqlite3_snprintf( nFull, zFull, zFullUTF );
23788   free( zFullUTF );
23789   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
23790 }
23791
23792
23793 /*
23794 ** Open a file.
23795 */
23796 static int os2Open(
23797   sqlite3_vfs *pVfs,            /* Not used */
23798   const char *zName,            /* Name of the file (UTF-8) */
23799   sqlite3_file *id,             /* Write the SQLite file handle here */
23800   int flags,                    /* Open mode flags */
23801   int *pOutFlags                /* Status return flags */
23802 ){
23803   HFILE h;
23804   ULONG ulOpenFlags = 0;
23805   ULONG ulOpenMode = 0;
23806   ULONG ulAction = 0;
23807   ULONG rc;
23808   os2File *pFile = (os2File*)id;
23809   const char *zUtf8Name = zName;
23810   char *zNameCp;
23811   char  zTmpname[CCHMAXPATH];
23812
23813   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
23814   int isCreate     = (flags & SQLITE_OPEN_CREATE);
23815   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
23816 #ifndef NDEBUG
23817   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
23818   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
23819   int eType        = (flags & 0xFFFFFF00);
23820   int isOpenJournal = (isCreate && (
23821         eType==SQLITE_OPEN_MASTER_JOURNAL 
23822      || eType==SQLITE_OPEN_MAIN_JOURNAL 
23823      || eType==SQLITE_OPEN_WAL
23824   ));
23825 #endif
23826
23827   UNUSED_PARAMETER(pVfs);
23828   assert( id!=0 );
23829
23830   /* Check the following statements are true: 
23831   **
23832   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
23833   **   (b) if CREATE is set, then READWRITE must also be set, and
23834   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
23835   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
23836   */
23837   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
23838   assert(isCreate==0 || isReadWrite);
23839   assert(isExclusive==0 || isCreate);
23840   assert(isDelete==0 || isCreate);
23841
23842   /* The main DB, main journal, WAL file and master journal are never 
23843   ** automatically deleted. Nor are they ever temporary files.  */
23844   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
23845   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
23846   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
23847   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
23848
23849   /* Assert that the upper layer has set one of the "file-type" flags. */
23850   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
23851        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
23852        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
23853        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
23854   );
23855
23856   memset( pFile, 0, sizeof(*pFile) );
23857   pFile->h = (HFILE)-1;
23858
23859   /* If the second argument to this function is NULL, generate a 
23860   ** temporary file name to use 
23861   */
23862   if( !zUtf8Name ){
23863     assert(isDelete && !isOpenJournal);
23864     rc = getTempname(CCHMAXPATH, zTmpname);
23865     if( rc!=SQLITE_OK ){
23866       return rc;
23867     }
23868     zUtf8Name = zTmpname;
23869   }
23870
23871   if( isReadWrite ){
23872     ulOpenMode |= OPEN_ACCESS_READWRITE;
23873   }else{
23874     ulOpenMode |= OPEN_ACCESS_READONLY;
23875   }
23876
23877   /* Open in random access mode for possibly better speed.  Allow full
23878   ** sharing because file locks will provide exclusive access when needed.
23879   ** The handle should not be inherited by child processes and we don't 
23880   ** want popups from the critical error handler.
23881   */
23882   ulOpenMode |= OPEN_FLAGS_RANDOM | OPEN_SHARE_DENYNONE | 
23883                 OPEN_FLAGS_NOINHERIT | OPEN_FLAGS_FAIL_ON_ERROR;
23884
23885   /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is 
23886   ** created. SQLite doesn't use it to indicate "exclusive access" 
23887   ** as it is usually understood.
23888   */
23889   if( isExclusive ){
23890     /* Creates a new file, only if it does not already exist. */
23891     /* If the file exists, it fails. */
23892     ulOpenFlags |= OPEN_ACTION_CREATE_IF_NEW | OPEN_ACTION_FAIL_IF_EXISTS;
23893   }else if( isCreate ){
23894     /* Open existing file, or create if it doesn't exist */
23895     ulOpenFlags |= OPEN_ACTION_CREATE_IF_NEW | OPEN_ACTION_OPEN_IF_EXISTS;
23896   }else{
23897     /* Opens a file, only if it exists. */
23898     ulOpenFlags |= OPEN_ACTION_FAIL_IF_NEW | OPEN_ACTION_OPEN_IF_EXISTS;
23899   }
23900
23901   zNameCp = convertUtf8PathToCp( zUtf8Name );
23902   rc = DosOpen( (PSZ)zNameCp,
23903                 &h,
23904                 &ulAction,
23905                 0L,
23906                 FILE_NORMAL,
23907                 ulOpenFlags,
23908                 ulOpenMode,
23909                 (PEAOP2)NULL );
23910   free( zNameCp );
23911
23912   if( rc != NO_ERROR ){
23913     OSTRACE(( "OPEN Invalid handle rc=%d: zName=%s, ulAction=%#lx, ulFlags=%#lx, ulMode=%#lx\n",
23914               rc, zUtf8Name, ulAction, ulOpenFlags, ulOpenMode ));
23915
23916     if( isReadWrite ){
23917       return os2Open( pVfs, zName, id,
23918                       ((flags|SQLITE_OPEN_READONLY)&~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
23919                       pOutFlags );
23920     }else{
23921       return SQLITE_CANTOPEN;
23922     }
23923   }
23924
23925   if( pOutFlags ){
23926     *pOutFlags = isReadWrite ? SQLITE_OPEN_READWRITE : SQLITE_OPEN_READONLY;
23927   }
23928
23929   os2FullPathname( pVfs, zUtf8Name, sizeof( zTmpname ), zTmpname );
23930   pFile->zFullPathCp = convertUtf8PathToCp( zTmpname );
23931   pFile->pMethod = &os2IoMethod;
23932   pFile->flags = flags;
23933   pFile->h = h;
23934
23935   OpenCounter(+1);
23936   OSTRACE(( "OPEN %d pOutFlags=%d\n", pFile->h, pOutFlags ));
23937   return SQLITE_OK;
23938 }
23939
23940 /*
23941 ** Delete the named file.
23942 */
23943 static int os2Delete(
23944   sqlite3_vfs *pVfs,                     /* Not used on os2 */
23945   const char *zFilename,                 /* Name of file to delete */
23946   int syncDir                            /* Not used on os2 */
23947 ){
23948   APIRET rc;
23949   char *zFilenameCp;
23950   SimulateIOError( return SQLITE_IOERR_DELETE );
23951   zFilenameCp = convertUtf8PathToCp( zFilename );
23952   rc = DosDelete( (PSZ)zFilenameCp );
23953   free( zFilenameCp );
23954   OSTRACE(( "DELETE \"%s\"\n", zFilename ));
23955   return (rc == NO_ERROR ||
23956           rc == ERROR_FILE_NOT_FOUND ||
23957           rc == ERROR_PATH_NOT_FOUND ) ? SQLITE_OK : SQLITE_IOERR_DELETE;
23958 }
23959
23960 /*
23961 ** Check the existance and status of a file.
23962 */
23963 static int os2Access(
23964   sqlite3_vfs *pVfs,        /* Not used on os2 */
23965   const char *zFilename,    /* Name of file to check */
23966   int flags,                /* Type of test to make on this file */
23967   int *pOut                 /* Write results here */
23968 ){
23969   APIRET rc;
23970   FILESTATUS3 fsts3ConfigInfo;
23971   char *zFilenameCp;
23972
23973   UNUSED_PARAMETER(pVfs);
23974   SimulateIOError( return SQLITE_IOERR_ACCESS; );
23975   
23976   zFilenameCp = convertUtf8PathToCp( zFilename );
23977   rc = DosQueryPathInfo( (PSZ)zFilenameCp, FIL_STANDARD,
23978                          &fsts3ConfigInfo, sizeof(FILESTATUS3) );
23979   free( zFilenameCp );
23980   OSTRACE(( "ACCESS fsts3ConfigInfo.attrFile=%d flags=%d rc=%d\n",
23981             fsts3ConfigInfo.attrFile, flags, rc ));
23982
23983   switch( flags ){
23984     case SQLITE_ACCESS_EXISTS:
23985       /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
23986       ** as if it does not exist.
23987       */
23988       if( fsts3ConfigInfo.cbFile == 0 ) 
23989         rc = ERROR_FILE_NOT_FOUND;
23990       break;
23991     case SQLITE_ACCESS_READ:
23992       break;
23993     case SQLITE_ACCESS_READWRITE:
23994       if( fsts3ConfigInfo.attrFile & FILE_READONLY )
23995         rc = ERROR_ACCESS_DENIED;
23996       break;
23997     default:
23998       rc = ERROR_FILE_NOT_FOUND;
23999       assert( !"Invalid flags argument" );
24000   }
24001
24002   *pOut = (rc == NO_ERROR);
24003   OSTRACE(( "ACCESS %s flags %d: rc=%d\n", zFilename, flags, *pOut ));
24004
24005   return SQLITE_OK;
24006 }
24007
24008
24009 #ifndef SQLITE_OMIT_LOAD_EXTENSION
24010 /*
24011 ** Interfaces for opening a shared library, finding entry points
24012 ** within the shared library, and closing the shared library.
24013 */
24014 /*
24015 ** Interfaces for opening a shared library, finding entry points
24016 ** within the shared library, and closing the shared library.
24017 */
24018 static void *os2DlOpen(sqlite3_vfs *pVfs, const char *zFilename){
24019   HMODULE hmod;
24020   APIRET rc;
24021   char *zFilenameCp = convertUtf8PathToCp(zFilename);
24022   rc = DosLoadModule(NULL, 0, (PSZ)zFilenameCp, &hmod);
24023   free(zFilenameCp);
24024   return rc != NO_ERROR ? 0 : (void*)hmod;
24025 }
24026 /*
24027 ** A no-op since the error code is returned on the DosLoadModule call.
24028 ** os2Dlopen returns zero if DosLoadModule is not successful.
24029 */
24030 static void os2DlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
24031 /* no-op */
24032 }
24033 static void (*os2DlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
24034   PFN pfn;
24035   APIRET rc;
24036   rc = DosQueryProcAddr((HMODULE)pHandle, 0L, (PSZ)zSymbol, &pfn);
24037   if( rc != NO_ERROR ){
24038     /* if the symbol itself was not found, search again for the same
24039      * symbol with an extra underscore, that might be needed depending
24040      * on the calling convention */
24041     char _zSymbol[256] = "_";
24042     strncat(_zSymbol, zSymbol, 254);
24043     rc = DosQueryProcAddr((HMODULE)pHandle, 0L, (PSZ)_zSymbol, &pfn);
24044   }
24045   return rc != NO_ERROR ? 0 : (void(*)(void))pfn;
24046 }
24047 static void os2DlClose(sqlite3_vfs *pVfs, void *pHandle){
24048   DosFreeModule((HMODULE)pHandle);
24049 }
24050 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
24051   #define os2DlOpen 0
24052   #define os2DlError 0
24053   #define os2DlSym 0
24054   #define os2DlClose 0
24055 #endif
24056
24057
24058 /*
24059 ** Write up to nBuf bytes of randomness into zBuf.
24060 */
24061 static int os2Randomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf ){
24062   int n = 0;
24063 #if defined(SQLITE_TEST)
24064   n = nBuf;
24065   memset(zBuf, 0, nBuf);
24066 #else
24067   int i;                           
24068   PPIB ppib;
24069   PTIB ptib;
24070   DATETIME dt; 
24071   static unsigned c = 0;
24072   /* Ordered by variation probability */
24073   static ULONG svIdx[6] = { QSV_MS_COUNT, QSV_TIME_LOW,
24074                             QSV_MAXPRMEM, QSV_MAXSHMEM,
24075                             QSV_TOTAVAILMEM, QSV_TOTRESMEM };
24076
24077   /* 8 bytes; timezone and weekday don't increase the randomness much */
24078   if( (int)sizeof(dt)-3 <= nBuf - n ){
24079     c += 0x0100;
24080     DosGetDateTime(&dt);
24081     dt.year = (USHORT)((dt.year - 1900) | c);
24082     memcpy(&zBuf[n], &dt, sizeof(dt)-3);
24083     n += sizeof(dt)-3;
24084   }
24085
24086   /* 4 bytes; PIDs and TIDs are 16 bit internally, so combine them */
24087   if( (int)sizeof(ULONG) <= nBuf - n ){
24088     DosGetInfoBlocks(&ptib, &ppib);
24089     *(PULONG)&zBuf[n] = MAKELONG(ppib->pib_ulpid,
24090                                  ptib->tib_ptib2->tib2_ultid);
24091     n += sizeof(ULONG);
24092   }
24093
24094   /* Up to 6 * 4 bytes; variables depend on the system state */
24095   for( i = 0; i < 6 && (int)sizeof(ULONG) <= nBuf - n; i++ ){
24096     DosQuerySysInfo(svIdx[i], svIdx[i], 
24097                     (PULONG)&zBuf[n], sizeof(ULONG));
24098     n += sizeof(ULONG);
24099   } 
24100 #endif
24101
24102   return n;
24103 }
24104
24105 /*
24106 ** Sleep for a little while.  Return the amount of time slept.
24107 ** The argument is the number of microseconds we want to sleep.
24108 ** The return value is the number of microseconds of sleep actually
24109 ** requested from the underlying operating system, a number which
24110 ** might be greater than or equal to the argument, but not less
24111 ** than the argument.
24112 */
24113 static int os2Sleep( sqlite3_vfs *pVfs, int microsec ){
24114   DosSleep( (microsec/1000) );
24115   return microsec;
24116 }
24117
24118 /*
24119 ** The following variable, if set to a non-zero value, becomes the result
24120 ** returned from sqlite3OsCurrentTime().  This is used for testing.
24121 */
24122 #ifdef SQLITE_TEST
24123 SQLITE_API int sqlite3_current_time = 0;
24124 #endif
24125
24126 /*
24127 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
24128 ** the current time and date as a Julian Day number times 86_400_000.  In
24129 ** other words, write into *piNow the number of milliseconds since the Julian
24130 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
24131 ** proleptic Gregorian calendar.
24132 **
24133 ** On success, return 0.  Return 1 if the time and date cannot be found.
24134 */
24135 static int os2CurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
24136 #ifdef SQLITE_TEST
24137   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
24138 #endif
24139   int year, month, datepart, timepart;
24140  
24141   DATETIME dt;
24142   DosGetDateTime( &dt );
24143
24144   year = dt.year;
24145   month = dt.month;
24146
24147   /* Calculations from http://www.astro.keele.ac.uk/~rno/Astronomy/hjd.html
24148   ** http://www.astro.keele.ac.uk/~rno/Astronomy/hjd-0.1.c
24149   ** Calculate the Julian days
24150   */
24151   datepart = (int)dt.day - 32076 +
24152     1461*(year + 4800 + (month - 14)/12)/4 +
24153     367*(month - 2 - (month - 14)/12*12)/12 -
24154     3*((year + 4900 + (month - 14)/12)/100)/4;
24155
24156   /* Time in milliseconds, hours to noon added */
24157   timepart = 12*3600*1000 + dt.hundredths*10 + dt.seconds*1000 +
24158     ((int)dt.minutes + dt.timezone)*60*1000 + dt.hours*3600*1000;
24159
24160   *piNow = (sqlite3_int64)datepart*86400*1000 + timepart;
24161    
24162 #ifdef SQLITE_TEST
24163   if( sqlite3_current_time ){
24164     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
24165   }
24166 #endif
24167
24168   UNUSED_PARAMETER(pVfs);
24169   return 0;
24170 }
24171
24172 /*
24173 ** Find the current time (in Universal Coordinated Time).  Write the
24174 ** current time and date as a Julian Day number into *prNow and
24175 ** return 0.  Return 1 if the time and date cannot be found.
24176 */
24177 static int os2CurrentTime( sqlite3_vfs *pVfs, double *prNow ){
24178   int rc;
24179   sqlite3_int64 i;
24180   rc = os2CurrentTimeInt64(pVfs, &i);
24181   if( !rc ){
24182     *prNow = i/86400000.0;
24183   }
24184   return rc;
24185 }
24186
24187 /*
24188 ** The idea is that this function works like a combination of
24189 ** GetLastError() and FormatMessage() on windows (or errno and
24190 ** strerror_r() on unix). After an error is returned by an OS
24191 ** function, SQLite calls this function with zBuf pointing to
24192 ** a buffer of nBuf bytes. The OS layer should populate the
24193 ** buffer with a nul-terminated UTF-8 encoded error message
24194 ** describing the last IO error to have occurred within the calling
24195 ** thread.
24196 **
24197 ** If the error message is too large for the supplied buffer,
24198 ** it should be truncated. The return value of xGetLastError
24199 ** is zero if the error message fits in the buffer, or non-zero
24200 ** otherwise (if the message was truncated). If non-zero is returned,
24201 ** then it is not necessary to include the nul-terminator character
24202 ** in the output buffer.
24203 **
24204 ** Not supplying an error message will have no adverse effect
24205 ** on SQLite. It is fine to have an implementation that never
24206 ** returns an error message:
24207 **
24208 **   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
24209 **     assert(zBuf[0]=='\0');
24210 **     return 0;
24211 **   }
24212 **
24213 ** However if an error message is supplied, it will be incorporated
24214 ** by sqlite into the error message available to the user using
24215 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
24216 */
24217 static int os2GetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
24218   assert(zBuf[0]=='\0');
24219   return 0;
24220 }
24221
24222 /*
24223 ** Initialize and deinitialize the operating system interface.
24224 */
24225 SQLITE_API int sqlite3_os_init(void){
24226   static sqlite3_vfs os2Vfs = {
24227     3,                 /* iVersion */
24228     sizeof(os2File),   /* szOsFile */
24229     CCHMAXPATH,        /* mxPathname */
24230     0,                 /* pNext */
24231     "os2",             /* zName */
24232     0,                 /* pAppData */
24233
24234     os2Open,           /* xOpen */
24235     os2Delete,         /* xDelete */
24236     os2Access,         /* xAccess */
24237     os2FullPathname,   /* xFullPathname */
24238     os2DlOpen,         /* xDlOpen */
24239     os2DlError,        /* xDlError */
24240     os2DlSym,          /* xDlSym */
24241     os2DlClose,        /* xDlClose */
24242     os2Randomness,     /* xRandomness */
24243     os2Sleep,          /* xSleep */
24244     os2CurrentTime,    /* xCurrentTime */
24245     os2GetLastError,   /* xGetLastError */
24246     os2CurrentTimeInt64, /* xCurrentTimeInt64 */
24247     0,                 /* xSetSystemCall */
24248     0,                 /* xGetSystemCall */
24249     0                  /* xNextSystemCall */
24250   };
24251   sqlite3_vfs_register(&os2Vfs, 1);
24252   initUconvObjects();
24253 /*  sqlite3OSTrace = 1; */
24254   return SQLITE_OK;
24255 }
24256 SQLITE_API int sqlite3_os_end(void){
24257   freeUconvObjects();
24258   return SQLITE_OK;
24259 }
24260
24261 #endif /* SQLITE_OS_OS2 */
24262
24263 /************** End of os_os2.c **********************************************/
24264 /************** Begin file os_unix.c *****************************************/
24265 /*
24266 ** 2004 May 22
24267 **
24268 ** The author disclaims copyright to this source code.  In place of
24269 ** a legal notice, here is a blessing:
24270 **
24271 **    May you do good and not evil.
24272 **    May you find forgiveness for yourself and forgive others.
24273 **    May you share freely, never taking more than you give.
24274 **
24275 ******************************************************************************
24276 **
24277 ** This file contains the VFS implementation for unix-like operating systems
24278 ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
24279 **
24280 ** There are actually several different VFS implementations in this file.
24281 ** The differences are in the way that file locking is done.  The default
24282 ** implementation uses Posix Advisory Locks.  Alternative implementations
24283 ** use flock(), dot-files, various proprietary locking schemas, or simply
24284 ** skip locking all together.
24285 **
24286 ** This source file is organized into divisions where the logic for various
24287 ** subfunctions is contained within the appropriate division.  PLEASE
24288 ** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
24289 ** in the correct division and should be clearly labeled.
24290 **
24291 ** The layout of divisions is as follows:
24292 **
24293 **   *  General-purpose declarations and utility functions.
24294 **   *  Unique file ID logic used by VxWorks.
24295 **   *  Various locking primitive implementations (all except proxy locking):
24296 **      + for Posix Advisory Locks
24297 **      + for no-op locks
24298 **      + for dot-file locks
24299 **      + for flock() locking
24300 **      + for named semaphore locks (VxWorks only)
24301 **      + for AFP filesystem locks (MacOSX only)
24302 **   *  sqlite3_file methods not associated with locking.
24303 **   *  Definitions of sqlite3_io_methods objects for all locking
24304 **      methods plus "finder" functions for each locking method.
24305 **   *  sqlite3_vfs method implementations.
24306 **   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
24307 **   *  Definitions of sqlite3_vfs objects for all locking methods
24308 **      plus implementations of sqlite3_os_init() and sqlite3_os_end().
24309 */
24310 #if SQLITE_OS_UNIX              /* This file is used on unix only */
24311
24312 /*
24313 ** There are various methods for file locking used for concurrency
24314 ** control:
24315 **
24316 **   1. POSIX locking (the default),
24317 **   2. No locking,
24318 **   3. Dot-file locking,
24319 **   4. flock() locking,
24320 **   5. AFP locking (OSX only),
24321 **   6. Named POSIX semaphores (VXWorks only),
24322 **   7. proxy locking. (OSX only)
24323 **
24324 ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
24325 ** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
24326 ** selection of the appropriate locking style based on the filesystem
24327 ** where the database is located.  
24328 */
24329 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
24330 #  if defined(__APPLE__)
24331 #    define SQLITE_ENABLE_LOCKING_STYLE 1
24332 #  else
24333 #    define SQLITE_ENABLE_LOCKING_STYLE 0
24334 #  endif
24335 #endif
24336
24337 /*
24338 ** Define the OS_VXWORKS pre-processor macro to 1 if building on 
24339 ** vxworks, or 0 otherwise.
24340 */
24341 #ifndef OS_VXWORKS
24342 #  if defined(__RTP__) || defined(_WRS_KERNEL)
24343 #    define OS_VXWORKS 1
24344 #  else
24345 #    define OS_VXWORKS 0
24346 #  endif
24347 #endif
24348
24349 /*
24350 ** These #defines should enable >2GB file support on Posix if the
24351 ** underlying operating system supports it.  If the OS lacks
24352 ** large file support, these should be no-ops.
24353 **
24354 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
24355 ** on the compiler command line.  This is necessary if you are compiling
24356 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
24357 ** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
24358 ** without this option, LFS is enable.  But LFS does not exist in the kernel
24359 ** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
24360 ** portability you should omit LFS.
24361 **
24362 ** The previous paragraph was written in 2005.  (This paragraph is written
24363 ** on 2008-11-28.) These days, all Linux kernels support large files, so
24364 ** you should probably leave LFS enabled.  But some embedded platforms might
24365 ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
24366 */
24367 #ifndef SQLITE_DISABLE_LFS
24368 # define _LARGE_FILE       1
24369 # ifndef _FILE_OFFSET_BITS
24370 #   define _FILE_OFFSET_BITS 64
24371 # endif
24372 # define _LARGEFILE_SOURCE 1
24373 #endif
24374
24375 /*
24376 ** standard include files.
24377 */
24378 #include <sys/types.h>
24379 #include <sys/stat.h>
24380 #include <fcntl.h>
24381 #include <unistd.h>
24382 #include <sys/time.h>
24383 #include <errno.h>
24384 #ifndef SQLITE_OMIT_WAL
24385 #include <sys/mman.h>
24386 #endif
24387
24388 #if SQLITE_ENABLE_LOCKING_STYLE
24389 # include <sys/ioctl.h>
24390 # if OS_VXWORKS
24391 #  include <semaphore.h>
24392 #  include <limits.h>
24393 # else
24394 #  include <sys/file.h>
24395 #  include <sys/param.h>
24396 # endif
24397 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
24398
24399 #if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
24400 # include <sys/mount.h>
24401 #endif
24402
24403 #ifdef HAVE_UTIME
24404 # include <utime.h>
24405 #endif
24406
24407 /*
24408 ** Allowed values of unixFile.fsFlags
24409 */
24410 #define SQLITE_FSFLAGS_IS_MSDOS     0x1
24411
24412 /*
24413 ** If we are to be thread-safe, include the pthreads header and define
24414 ** the SQLITE_UNIX_THREADS macro.
24415 */
24416 #if SQLITE_THREADSAFE
24417 # define SQLITE_UNIX_THREADS 1
24418 #endif
24419
24420 /*
24421 ** Default permissions when creating a new file
24422 */
24423 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
24424 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
24425 #endif
24426
24427 /*
24428  ** Default permissions when creating auto proxy dir
24429  */
24430 #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
24431 # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
24432 #endif
24433
24434 /*
24435 ** Maximum supported path-length.
24436 */
24437 #define MAX_PATHNAME 512
24438
24439 /*
24440 ** Only set the lastErrno if the error code is a real error and not 
24441 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
24442 */
24443 #define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
24444
24445 /* Forward references */
24446 typedef struct unixShm unixShm;               /* Connection shared memory */
24447 typedef struct unixShmNode unixShmNode;       /* Shared memory instance */
24448 typedef struct unixInodeInfo unixInodeInfo;   /* An i-node */
24449 typedef struct UnixUnusedFd UnixUnusedFd;     /* An unused file descriptor */
24450
24451 /*
24452 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
24453 ** cannot be closed immediately. In these cases, instances of the following
24454 ** structure are used to store the file descriptor while waiting for an
24455 ** opportunity to either close or reuse it.
24456 */
24457 struct UnixUnusedFd {
24458   int fd;                   /* File descriptor to close */
24459   int flags;                /* Flags this file descriptor was opened with */
24460   UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
24461 };
24462
24463 /*
24464 ** The unixFile structure is subclass of sqlite3_file specific to the unix
24465 ** VFS implementations.
24466 */
24467 typedef struct unixFile unixFile;
24468 struct unixFile {
24469   sqlite3_io_methods const *pMethod;  /* Always the first entry */
24470   unixInodeInfo *pInode;              /* Info about locks on this inode */
24471   int h;                              /* The file descriptor */
24472   int dirfd;                          /* File descriptor for the directory */
24473   unsigned char eFileLock;            /* The type of lock held on this fd */
24474   unsigned char ctrlFlags;            /* Behavioral bits.  UNIXFILE_* flags */
24475   int lastErrno;                      /* The unix errno from last I/O error */
24476   void *lockingContext;               /* Locking style specific state */
24477   UnixUnusedFd *pUnused;              /* Pre-allocated UnixUnusedFd */
24478   const char *zPath;                  /* Name of the file */
24479   unixShm *pShm;                      /* Shared memory segment information */
24480   int szChunk;                        /* Configured by FCNTL_CHUNK_SIZE */
24481 #if SQLITE_ENABLE_LOCKING_STYLE
24482   int openFlags;                      /* The flags specified at open() */
24483 #endif
24484 #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
24485   unsigned fsFlags;                   /* cached details from statfs() */
24486 #endif
24487 #if OS_VXWORKS
24488   int isDelete;                       /* Delete on close if true */
24489   struct vxworksFileId *pId;          /* Unique file ID */
24490 #endif
24491 #ifndef NDEBUG
24492   /* The next group of variables are used to track whether or not the
24493   ** transaction counter in bytes 24-27 of database files are updated
24494   ** whenever any part of the database changes.  An assertion fault will
24495   ** occur if a file is updated without also updating the transaction
24496   ** counter.  This test is made to avoid new problems similar to the
24497   ** one described by ticket #3584. 
24498   */
24499   unsigned char transCntrChng;   /* True if the transaction counter changed */
24500   unsigned char dbUpdate;        /* True if any part of database file changed */
24501   unsigned char inNormalWrite;   /* True if in a normal write operation */
24502 #endif
24503 #ifdef SQLITE_TEST
24504   /* In test mode, increase the size of this structure a bit so that 
24505   ** it is larger than the struct CrashFile defined in test6.c.
24506   */
24507   char aPadding[32];
24508 #endif
24509 };
24510
24511 /*
24512 ** Allowed values for the unixFile.ctrlFlags bitmask:
24513 */
24514 #define UNIXFILE_EXCL   0x01     /* Connections from one process only */
24515 #define UNIXFILE_RDONLY 0x02     /* Connection is read only */
24516
24517 /*
24518 ** Include code that is common to all os_*.c files
24519 */
24520 /************** Include os_common.h in the middle of os_unix.c ***************/
24521 /************** Begin file os_common.h ***************************************/
24522 /*
24523 ** 2004 May 22
24524 **
24525 ** The author disclaims copyright to this source code.  In place of
24526 ** a legal notice, here is a blessing:
24527 **
24528 **    May you do good and not evil.
24529 **    May you find forgiveness for yourself and forgive others.
24530 **    May you share freely, never taking more than you give.
24531 **
24532 ******************************************************************************
24533 **
24534 ** This file contains macros and a little bit of code that is common to
24535 ** all of the platform-specific files (os_*.c) and is #included into those
24536 ** files.
24537 **
24538 ** This file should be #included by the os_*.c files only.  It is not a
24539 ** general purpose header file.
24540 */
24541 #ifndef _OS_COMMON_H_
24542 #define _OS_COMMON_H_
24543
24544 /*
24545 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
24546 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
24547 ** switch.  The following code should catch this problem at compile-time.
24548 */
24549 #ifdef MEMORY_DEBUG
24550 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
24551 #endif
24552
24553 #ifdef SQLITE_DEBUG
24554 SQLITE_PRIVATE int sqlite3OSTrace = 0;
24555 #define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
24556 #else
24557 #define OSTRACE(X)
24558 #endif
24559
24560 /*
24561 ** Macros for performance tracing.  Normally turned off.  Only works
24562 ** on i486 hardware.
24563 */
24564 #ifdef SQLITE_PERFORMANCE_TRACE
24565
24566 /* 
24567 ** hwtime.h contains inline assembler code for implementing 
24568 ** high-performance timing routines.
24569 */
24570 /************** Include hwtime.h in the middle of os_common.h ****************/
24571 /************** Begin file hwtime.h ******************************************/
24572 /*
24573 ** 2008 May 27
24574 **
24575 ** The author disclaims copyright to this source code.  In place of
24576 ** a legal notice, here is a blessing:
24577 **
24578 **    May you do good and not evil.
24579 **    May you find forgiveness for yourself and forgive others.
24580 **    May you share freely, never taking more than you give.
24581 **
24582 ******************************************************************************
24583 **
24584 ** This file contains inline asm code for retrieving "high-performance"
24585 ** counters for x86 class CPUs.
24586 */
24587 #ifndef _HWTIME_H_
24588 #define _HWTIME_H_
24589
24590 /*
24591 ** The following routine only works on pentium-class (or newer) processors.
24592 ** It uses the RDTSC opcode to read the cycle count value out of the
24593 ** processor and returns that value.  This can be used for high-res
24594 ** profiling.
24595 */
24596 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
24597       (defined(i386) || defined(__i386__) || defined(_M_IX86))
24598
24599   #if defined(__GNUC__)
24600
24601   __inline__ sqlite_uint64 sqlite3Hwtime(void){
24602      unsigned int lo, hi;
24603      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
24604      return (sqlite_uint64)hi << 32 | lo;
24605   }
24606
24607   #elif defined(_MSC_VER)
24608
24609   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
24610      __asm {
24611         rdtsc
24612         ret       ; return value at EDX:EAX
24613      }
24614   }
24615
24616   #endif
24617
24618 #elif (defined(__GNUC__) && defined(__x86_64__))
24619
24620   __inline__ sqlite_uint64 sqlite3Hwtime(void){
24621       unsigned long val;
24622       __asm__ __volatile__ ("rdtsc" : "=A" (val));
24623       return val;
24624   }
24625  
24626 #elif (defined(__GNUC__) && defined(__ppc__))
24627
24628   __inline__ sqlite_uint64 sqlite3Hwtime(void){
24629       unsigned long long retval;
24630       unsigned long junk;
24631       __asm__ __volatile__ ("\n\
24632           1:      mftbu   %1\n\
24633                   mftb    %L0\n\
24634                   mftbu   %0\n\
24635                   cmpw    %0,%1\n\
24636                   bne     1b"
24637                   : "=r" (retval), "=r" (junk));
24638       return retval;
24639   }
24640
24641 #else
24642
24643   #error Need implementation of sqlite3Hwtime() for your platform.
24644
24645   /*
24646   ** To compile without implementing sqlite3Hwtime() for your platform,
24647   ** you can remove the above #error and use the following
24648   ** stub function.  You will lose timing support for many
24649   ** of the debugging and testing utilities, but it should at
24650   ** least compile and run.
24651   */
24652 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
24653
24654 #endif
24655
24656 #endif /* !defined(_HWTIME_H_) */
24657
24658 /************** End of hwtime.h **********************************************/
24659 /************** Continuing where we left off in os_common.h ******************/
24660
24661 static sqlite_uint64 g_start;
24662 static sqlite_uint64 g_elapsed;
24663 #define TIMER_START       g_start=sqlite3Hwtime()
24664 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
24665 #define TIMER_ELAPSED     g_elapsed
24666 #else
24667 #define TIMER_START
24668 #define TIMER_END
24669 #define TIMER_ELAPSED     ((sqlite_uint64)0)
24670 #endif
24671
24672 /*
24673 ** If we compile with the SQLITE_TEST macro set, then the following block
24674 ** of code will give us the ability to simulate a disk I/O error.  This
24675 ** is used for testing the I/O recovery logic.
24676 */
24677 #ifdef SQLITE_TEST
24678 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
24679 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
24680 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
24681 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
24682 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
24683 SQLITE_API int sqlite3_diskfull_pending = 0;
24684 SQLITE_API int sqlite3_diskfull = 0;
24685 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
24686 #define SimulateIOError(CODE)  \
24687   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
24688        || sqlite3_io_error_pending-- == 1 )  \
24689               { local_ioerr(); CODE; }
24690 static void local_ioerr(){
24691   IOTRACE(("IOERR\n"));
24692   sqlite3_io_error_hit++;
24693   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
24694 }
24695 #define SimulateDiskfullError(CODE) \
24696    if( sqlite3_diskfull_pending ){ \
24697      if( sqlite3_diskfull_pending == 1 ){ \
24698        local_ioerr(); \
24699        sqlite3_diskfull = 1; \
24700        sqlite3_io_error_hit = 1; \
24701        CODE; \
24702      }else{ \
24703        sqlite3_diskfull_pending--; \
24704      } \
24705    }
24706 #else
24707 #define SimulateIOErrorBenign(X)
24708 #define SimulateIOError(A)
24709 #define SimulateDiskfullError(A)
24710 #endif
24711
24712 /*
24713 ** When testing, keep a count of the number of open files.
24714 */
24715 #ifdef SQLITE_TEST
24716 SQLITE_API int sqlite3_open_file_count = 0;
24717 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
24718 #else
24719 #define OpenCounter(X)
24720 #endif
24721
24722 #endif /* !defined(_OS_COMMON_H_) */
24723
24724 /************** End of os_common.h *******************************************/
24725 /************** Continuing where we left off in os_unix.c ********************/
24726
24727 /*
24728 ** Define various macros that are missing from some systems.
24729 */
24730 #ifndef O_LARGEFILE
24731 # define O_LARGEFILE 0
24732 #endif
24733 #ifdef SQLITE_DISABLE_LFS
24734 # undef O_LARGEFILE
24735 # define O_LARGEFILE 0
24736 #endif
24737 #ifndef O_NOFOLLOW
24738 # define O_NOFOLLOW 0
24739 #endif
24740 #ifndef O_BINARY
24741 # define O_BINARY 0
24742 #endif
24743
24744 /*
24745 ** The threadid macro resolves to the thread-id or to 0.  Used for
24746 ** testing and debugging only.
24747 */
24748 #if SQLITE_THREADSAFE
24749 #define threadid pthread_self()
24750 #else
24751 #define threadid 0
24752 #endif
24753
24754 /*
24755 ** Different Unix systems declare open() in different ways.  Same use
24756 ** open(const char*,int,mode_t).  Others use open(const char*,int,...).
24757 ** The difference is important when using a pointer to the function.
24758 **
24759 ** The safest way to deal with the problem is to always use this wrapper
24760 ** which always has the same well-defined interface.
24761 */
24762 static int posixOpen(const char *zFile, int flags, int mode){
24763   return open(zFile, flags, mode);
24764 }
24765
24766 /*
24767 ** Many system calls are accessed through pointer-to-functions so that
24768 ** they may be overridden at runtime to facilitate fault injection during
24769 ** testing and sandboxing.  The following array holds the names and pointers
24770 ** to all overrideable system calls.
24771 */
24772 static struct unix_syscall {
24773   const char *zName;            /* Name of the sytem call */
24774   sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
24775   sqlite3_syscall_ptr pDefault; /* Default value */
24776 } aSyscall[] = {
24777   { "open",         (sqlite3_syscall_ptr)posixOpen,  0  },
24778 #define osOpen      ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
24779
24780   { "close",        (sqlite3_syscall_ptr)close,      0  },
24781 #define osClose     ((int(*)(int))aSyscall[1].pCurrent)
24782
24783   { "access",       (sqlite3_syscall_ptr)access,     0  },
24784 #define osAccess    ((int(*)(const char*,int))aSyscall[2].pCurrent)
24785
24786   { "getcwd",       (sqlite3_syscall_ptr)getcwd,     0  },
24787 #define osGetcwd    ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
24788
24789   { "stat",         (sqlite3_syscall_ptr)stat,       0  },
24790 #define osStat      ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
24791
24792 /*
24793 ** The DJGPP compiler environment looks mostly like Unix, but it
24794 ** lacks the fcntl() system call.  So redefine fcntl() to be something
24795 ** that always succeeds.  This means that locking does not occur under
24796 ** DJGPP.  But it is DOS - what did you expect?
24797 */
24798 #ifdef __DJGPP__
24799   { "fstat",        0,                 0  },
24800 #define osFstat(a,b,c)    0
24801 #else     
24802   { "fstat",        (sqlite3_syscall_ptr)fstat,      0  },
24803 #define osFstat     ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
24804 #endif
24805
24806   { "ftruncate",    (sqlite3_syscall_ptr)ftruncate,  0  },
24807 #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
24808
24809   { "fcntl",        (sqlite3_syscall_ptr)fcntl,      0  },
24810 #define osFcntl     ((int(*)(int,int,...))aSyscall[7].pCurrent)
24811
24812   { "read",         (sqlite3_syscall_ptr)read,       0  },
24813 #define osRead      ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
24814
24815 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
24816   { "pread",        (sqlite3_syscall_ptr)pread,      0  },
24817 #else
24818   { "pread",        (sqlite3_syscall_ptr)0,          0  },
24819 #endif
24820 #define osPread     ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
24821
24822 #if defined(USE_PREAD64)
24823   { "pread64",      (sqlite3_syscall_ptr)pread64,    0  },
24824 #else
24825   { "pread64",      (sqlite3_syscall_ptr)0,          0  },
24826 #endif
24827 #define osPread64   ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
24828
24829   { "write",        (sqlite3_syscall_ptr)write,      0  },
24830 #define osWrite     ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
24831
24832 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
24833   { "pwrite",       (sqlite3_syscall_ptr)pwrite,     0  },
24834 #else
24835   { "pwrite",       (sqlite3_syscall_ptr)0,          0  },
24836 #endif
24837 #define osPwrite    ((ssize_t(*)(int,const void*,size_t,off_t))\
24838                     aSyscall[12].pCurrent)
24839
24840 #if defined(USE_PREAD64)
24841   { "pwrite64",     (sqlite3_syscall_ptr)pwrite64,   0  },
24842 #else
24843   { "pwrite64",     (sqlite3_syscall_ptr)0,          0  },
24844 #endif
24845 #define osPwrite64  ((ssize_t(*)(int,const void*,size_t,off_t))\
24846                     aSyscall[13].pCurrent)
24847
24848 #if SQLITE_ENABLE_LOCKING_STYLE
24849   { "fchmod",       (sqlite3_syscall_ptr)fchmod,     0  },
24850 #else
24851   { "fchmod",       (sqlite3_syscall_ptr)0,          0  },
24852 #endif
24853 #define osFchmod    ((int(*)(int,mode_t))aSyscall[14].pCurrent)
24854
24855 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
24856   { "fallocate",    (sqlite3_syscall_ptr)posix_fallocate,  0 },
24857 #else
24858   { "fallocate",    (sqlite3_syscall_ptr)0,                0 },
24859 #endif
24860 #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
24861
24862 }; /* End of the overrideable system calls */
24863
24864 /*
24865 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
24866 ** "unix" VFSes.  Return SQLITE_OK opon successfully updating the
24867 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
24868 ** system call named zName.
24869 */
24870 static int unixSetSystemCall(
24871   sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
24872   const char *zName,            /* Name of system call to override */
24873   sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
24874 ){
24875   unsigned int i;
24876   int rc = SQLITE_NOTFOUND;
24877
24878   UNUSED_PARAMETER(pNotUsed);
24879   if( zName==0 ){
24880     /* If no zName is given, restore all system calls to their default
24881     ** settings and return NULL
24882     */
24883     rc = SQLITE_OK;
24884     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
24885       if( aSyscall[i].pDefault ){
24886         aSyscall[i].pCurrent = aSyscall[i].pDefault;
24887       }
24888     }
24889   }else{
24890     /* If zName is specified, operate on only the one system call
24891     ** specified.
24892     */
24893     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
24894       if( strcmp(zName, aSyscall[i].zName)==0 ){
24895         if( aSyscall[i].pDefault==0 ){
24896           aSyscall[i].pDefault = aSyscall[i].pCurrent;
24897         }
24898         rc = SQLITE_OK;
24899         if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
24900         aSyscall[i].pCurrent = pNewFunc;
24901         break;
24902       }
24903     }
24904   }
24905   return rc;
24906 }
24907
24908 /*
24909 ** Return the value of a system call.  Return NULL if zName is not a
24910 ** recognized system call name.  NULL is also returned if the system call
24911 ** is currently undefined.
24912 */
24913 static sqlite3_syscall_ptr unixGetSystemCall(
24914   sqlite3_vfs *pNotUsed,
24915   const char *zName
24916 ){
24917   unsigned int i;
24918
24919   UNUSED_PARAMETER(pNotUsed);
24920   for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
24921     if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
24922   }
24923   return 0;
24924 }
24925
24926 /*
24927 ** Return the name of the first system call after zName.  If zName==NULL
24928 ** then return the name of the first system call.  Return NULL if zName
24929 ** is the last system call or if zName is not the name of a valid
24930 ** system call.
24931 */
24932 static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
24933   int i = -1;
24934
24935   UNUSED_PARAMETER(p);
24936   if( zName ){
24937     for(i=0; i<ArraySize(aSyscall)-1; i++){
24938       if( strcmp(zName, aSyscall[i].zName)==0 ) break;
24939     }
24940   }
24941   for(i++; i<ArraySize(aSyscall); i++){
24942     if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
24943   }
24944   return 0;
24945 }
24946
24947 /*
24948 ** Retry open() calls that fail due to EINTR
24949 */
24950 static int robust_open(const char *z, int f, int m){
24951   int rc;
24952   do{ rc = osOpen(z,f,m); }while( rc<0 && errno==EINTR );
24953   return rc;
24954 }
24955
24956 /*
24957 ** Helper functions to obtain and relinquish the global mutex. The
24958 ** global mutex is used to protect the unixInodeInfo and
24959 ** vxworksFileId objects used by this file, all of which may be 
24960 ** shared by multiple threads.
24961 **
24962 ** Function unixMutexHeld() is used to assert() that the global mutex 
24963 ** is held when required. This function is only used as part of assert() 
24964 ** statements. e.g.
24965 **
24966 **   unixEnterMutex()
24967 **     assert( unixMutexHeld() );
24968 **   unixEnterLeave()
24969 */
24970 static void unixEnterMutex(void){
24971   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
24972 }
24973 static void unixLeaveMutex(void){
24974   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
24975 }
24976 #ifdef SQLITE_DEBUG
24977 static int unixMutexHeld(void) {
24978   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
24979 }
24980 #endif
24981
24982
24983 #ifdef SQLITE_DEBUG
24984 /*
24985 ** Helper function for printing out trace information from debugging
24986 ** binaries. This returns the string represetation of the supplied
24987 ** integer lock-type.
24988 */
24989 static const char *azFileLock(int eFileLock){
24990   switch( eFileLock ){
24991     case NO_LOCK: return "NONE";
24992     case SHARED_LOCK: return "SHARED";
24993     case RESERVED_LOCK: return "RESERVED";
24994     case PENDING_LOCK: return "PENDING";
24995     case EXCLUSIVE_LOCK: return "EXCLUSIVE";
24996   }
24997   return "ERROR";
24998 }
24999 #endif
25000
25001 #ifdef SQLITE_LOCK_TRACE
25002 /*
25003 ** Print out information about all locking operations.
25004 **
25005 ** This routine is used for troubleshooting locks on multithreaded
25006 ** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
25007 ** command-line option on the compiler.  This code is normally
25008 ** turned off.
25009 */
25010 static int lockTrace(int fd, int op, struct flock *p){
25011   char *zOpName, *zType;
25012   int s;
25013   int savedErrno;
25014   if( op==F_GETLK ){
25015     zOpName = "GETLK";
25016   }else if( op==F_SETLK ){
25017     zOpName = "SETLK";
25018   }else{
25019     s = osFcntl(fd, op, p);
25020     sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
25021     return s;
25022   }
25023   if( p->l_type==F_RDLCK ){
25024     zType = "RDLCK";
25025   }else if( p->l_type==F_WRLCK ){
25026     zType = "WRLCK";
25027   }else if( p->l_type==F_UNLCK ){
25028     zType = "UNLCK";
25029   }else{
25030     assert( 0 );
25031   }
25032   assert( p->l_whence==SEEK_SET );
25033   s = osFcntl(fd, op, p);
25034   savedErrno = errno;
25035   sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
25036      threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
25037      (int)p->l_pid, s);
25038   if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
25039     struct flock l2;
25040     l2 = *p;
25041     osFcntl(fd, F_GETLK, &l2);
25042     if( l2.l_type==F_RDLCK ){
25043       zType = "RDLCK";
25044     }else if( l2.l_type==F_WRLCK ){
25045       zType = "WRLCK";
25046     }else if( l2.l_type==F_UNLCK ){
25047       zType = "UNLCK";
25048     }else{
25049       assert( 0 );
25050     }
25051     sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
25052        zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
25053   }
25054   errno = savedErrno;
25055   return s;
25056 }
25057 #undef osFcntl
25058 #define osFcntl lockTrace
25059 #endif /* SQLITE_LOCK_TRACE */
25060
25061 /*
25062 ** Retry ftruncate() calls that fail due to EINTR
25063 */
25064 static int robust_ftruncate(int h, sqlite3_int64 sz){
25065   int rc;
25066   do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
25067   return rc;
25068 }
25069
25070 /*
25071 ** This routine translates a standard POSIX errno code into something
25072 ** useful to the clients of the sqlite3 functions.  Specifically, it is
25073 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
25074 ** and a variety of "please close the file descriptor NOW" errors into 
25075 ** SQLITE_IOERR
25076 ** 
25077 ** Errors during initialization of locks, or file system support for locks,
25078 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
25079 */
25080 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
25081   switch (posixError) {
25082 #if 0
25083   /* At one point this code was not commented out. In theory, this branch
25084   ** should never be hit, as this function should only be called after
25085   ** a locking-related function (i.e. fcntl()) has returned non-zero with
25086   ** the value of errno as the first argument. Since a system call has failed,
25087   ** errno should be non-zero.
25088   **
25089   ** Despite this, if errno really is zero, we still don't want to return
25090   ** SQLITE_OK. The system call failed, and *some* SQLite error should be
25091   ** propagated back to the caller. Commenting this branch out means errno==0
25092   ** will be handled by the "default:" case below.
25093   */
25094   case 0: 
25095     return SQLITE_OK;
25096 #endif
25097
25098   case EAGAIN:
25099   case ETIMEDOUT:
25100   case EBUSY:
25101   case EINTR:
25102   case ENOLCK:  
25103     /* random NFS retry error, unless during file system support 
25104      * introspection, in which it actually means what it says */
25105     return SQLITE_BUSY;
25106     
25107   case EACCES: 
25108     /* EACCES is like EAGAIN during locking operations, but not any other time*/
25109     if( (sqliteIOErr == SQLITE_IOERR_LOCK) || 
25110         (sqliteIOErr == SQLITE_IOERR_UNLOCK) || 
25111         (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
25112         (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
25113       return SQLITE_BUSY;
25114     }
25115     /* else fall through */
25116   case EPERM: 
25117     return SQLITE_PERM;
25118     
25119   /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
25120   ** this module never makes such a call. And the code in SQLite itself 
25121   ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
25122   ** this case is also commented out. If the system does set errno to EDEADLK,
25123   ** the default SQLITE_IOERR_XXX code will be returned. */
25124 #if 0
25125   case EDEADLK:
25126     return SQLITE_IOERR_BLOCKED;
25127 #endif
25128     
25129 #if EOPNOTSUPP!=ENOTSUP
25130   case EOPNOTSUPP: 
25131     /* something went terribly awry, unless during file system support 
25132      * introspection, in which it actually means what it says */
25133 #endif
25134 #ifdef ENOTSUP
25135   case ENOTSUP: 
25136     /* invalid fd, unless during file system support introspection, in which 
25137      * it actually means what it says */
25138 #endif
25139   case EIO:
25140   case EBADF:
25141   case EINVAL:
25142   case ENOTCONN:
25143   case ENODEV:
25144   case ENXIO:
25145   case ENOENT:
25146   case ESTALE:
25147   case ENOSYS:
25148     /* these should force the client to close the file and reconnect */
25149     
25150   default: 
25151     return sqliteIOErr;
25152   }
25153 }
25154
25155
25156
25157 /******************************************************************************
25158 ****************** Begin Unique File ID Utility Used By VxWorks ***************
25159 **
25160 ** On most versions of unix, we can get a unique ID for a file by concatenating
25161 ** the device number and the inode number.  But this does not work on VxWorks.
25162 ** On VxWorks, a unique file id must be based on the canonical filename.
25163 **
25164 ** A pointer to an instance of the following structure can be used as a
25165 ** unique file ID in VxWorks.  Each instance of this structure contains
25166 ** a copy of the canonical filename.  There is also a reference count.  
25167 ** The structure is reclaimed when the number of pointers to it drops to
25168 ** zero.
25169 **
25170 ** There are never very many files open at one time and lookups are not
25171 ** a performance-critical path, so it is sufficient to put these
25172 ** structures on a linked list.
25173 */
25174 struct vxworksFileId {
25175   struct vxworksFileId *pNext;  /* Next in a list of them all */
25176   int nRef;                     /* Number of references to this one */
25177   int nName;                    /* Length of the zCanonicalName[] string */
25178   char *zCanonicalName;         /* Canonical filename */
25179 };
25180
25181 #if OS_VXWORKS
25182 /* 
25183 ** All unique filenames are held on a linked list headed by this
25184 ** variable:
25185 */
25186 static struct vxworksFileId *vxworksFileList = 0;
25187
25188 /*
25189 ** Simplify a filename into its canonical form
25190 ** by making the following changes:
25191 **
25192 **  * removing any trailing and duplicate /
25193 **  * convert /./ into just /
25194 **  * convert /A/../ where A is any simple name into just /
25195 **
25196 ** Changes are made in-place.  Return the new name length.
25197 **
25198 ** The original filename is in z[0..n-1].  Return the number of
25199 ** characters in the simplified name.
25200 */
25201 static int vxworksSimplifyName(char *z, int n){
25202   int i, j;
25203   while( n>1 && z[n-1]=='/' ){ n--; }
25204   for(i=j=0; i<n; i++){
25205     if( z[i]=='/' ){
25206       if( z[i+1]=='/' ) continue;
25207       if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
25208         i += 1;
25209         continue;
25210       }
25211       if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
25212         while( j>0 && z[j-1]!='/' ){ j--; }
25213         if( j>0 ){ j--; }
25214         i += 2;
25215         continue;
25216       }
25217     }
25218     z[j++] = z[i];
25219   }
25220   z[j] = 0;
25221   return j;
25222 }
25223
25224 /*
25225 ** Find a unique file ID for the given absolute pathname.  Return
25226 ** a pointer to the vxworksFileId object.  This pointer is the unique
25227 ** file ID.
25228 **
25229 ** The nRef field of the vxworksFileId object is incremented before
25230 ** the object is returned.  A new vxworksFileId object is created
25231 ** and added to the global list if necessary.
25232 **
25233 ** If a memory allocation error occurs, return NULL.
25234 */
25235 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
25236   struct vxworksFileId *pNew;         /* search key and new file ID */
25237   struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
25238   int n;                              /* Length of zAbsoluteName string */
25239
25240   assert( zAbsoluteName[0]=='/' );
25241   n = (int)strlen(zAbsoluteName);
25242   pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
25243   if( pNew==0 ) return 0;
25244   pNew->zCanonicalName = (char*)&pNew[1];
25245   memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
25246   n = vxworksSimplifyName(pNew->zCanonicalName, n);
25247
25248   /* Search for an existing entry that matching the canonical name.
25249   ** If found, increment the reference count and return a pointer to
25250   ** the existing file ID.
25251   */
25252   unixEnterMutex();
25253   for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
25254     if( pCandidate->nName==n 
25255      && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
25256     ){
25257        sqlite3_free(pNew);
25258        pCandidate->nRef++;
25259        unixLeaveMutex();
25260        return pCandidate;
25261     }
25262   }
25263
25264   /* No match was found.  We will make a new file ID */
25265   pNew->nRef = 1;
25266   pNew->nName = n;
25267   pNew->pNext = vxworksFileList;
25268   vxworksFileList = pNew;
25269   unixLeaveMutex();
25270   return pNew;
25271 }
25272
25273 /*
25274 ** Decrement the reference count on a vxworksFileId object.  Free
25275 ** the object when the reference count reaches zero.
25276 */
25277 static void vxworksReleaseFileId(struct vxworksFileId *pId){
25278   unixEnterMutex();
25279   assert( pId->nRef>0 );
25280   pId->nRef--;
25281   if( pId->nRef==0 ){
25282     struct vxworksFileId **pp;
25283     for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
25284     assert( *pp==pId );
25285     *pp = pId->pNext;
25286     sqlite3_free(pId);
25287   }
25288   unixLeaveMutex();
25289 }
25290 #endif /* OS_VXWORKS */
25291 /*************** End of Unique File ID Utility Used By VxWorks ****************
25292 ******************************************************************************/
25293
25294
25295 /******************************************************************************
25296 *************************** Posix Advisory Locking ****************************
25297 **
25298 ** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
25299 ** section 6.5.2.2 lines 483 through 490 specify that when a process
25300 ** sets or clears a lock, that operation overrides any prior locks set
25301 ** by the same process.  It does not explicitly say so, but this implies
25302 ** that it overrides locks set by the same process using a different
25303 ** file descriptor.  Consider this test case:
25304 **
25305 **       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
25306 **       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
25307 **
25308 ** Suppose ./file1 and ./file2 are really the same file (because
25309 ** one is a hard or symbolic link to the other) then if you set
25310 ** an exclusive lock on fd1, then try to get an exclusive lock
25311 ** on fd2, it works.  I would have expected the second lock to
25312 ** fail since there was already a lock on the file due to fd1.
25313 ** But not so.  Since both locks came from the same process, the
25314 ** second overrides the first, even though they were on different
25315 ** file descriptors opened on different file names.
25316 **
25317 ** This means that we cannot use POSIX locks to synchronize file access
25318 ** among competing threads of the same process.  POSIX locks will work fine
25319 ** to synchronize access for threads in separate processes, but not
25320 ** threads within the same process.
25321 **
25322 ** To work around the problem, SQLite has to manage file locks internally
25323 ** on its own.  Whenever a new database is opened, we have to find the
25324 ** specific inode of the database file (the inode is determined by the
25325 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
25326 ** and check for locks already existing on that inode.  When locks are
25327 ** created or removed, we have to look at our own internal record of the
25328 ** locks to see if another thread has previously set a lock on that same
25329 ** inode.
25330 **
25331 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
25332 ** For VxWorks, we have to use the alternative unique ID system based on
25333 ** canonical filename and implemented in the previous division.)
25334 **
25335 ** The sqlite3_file structure for POSIX is no longer just an integer file
25336 ** descriptor.  It is now a structure that holds the integer file
25337 ** descriptor and a pointer to a structure that describes the internal
25338 ** locks on the corresponding inode.  There is one locking structure
25339 ** per inode, so if the same inode is opened twice, both unixFile structures
25340 ** point to the same locking structure.  The locking structure keeps
25341 ** a reference count (so we will know when to delete it) and a "cnt"
25342 ** field that tells us its internal lock status.  cnt==0 means the
25343 ** file is unlocked.  cnt==-1 means the file has an exclusive lock.
25344 ** cnt>0 means there are cnt shared locks on the file.
25345 **
25346 ** Any attempt to lock or unlock a file first checks the locking
25347 ** structure.  The fcntl() system call is only invoked to set a 
25348 ** POSIX lock if the internal lock structure transitions between
25349 ** a locked and an unlocked state.
25350 **
25351 ** But wait:  there are yet more problems with POSIX advisory locks.
25352 **
25353 ** If you close a file descriptor that points to a file that has locks,
25354 ** all locks on that file that are owned by the current process are
25355 ** released.  To work around this problem, each unixInodeInfo object
25356 ** maintains a count of the number of pending locks on tha inode.
25357 ** When an attempt is made to close an unixFile, if there are
25358 ** other unixFile open on the same inode that are holding locks, the call
25359 ** to close() the file descriptor is deferred until all of the locks clear.
25360 ** The unixInodeInfo structure keeps a list of file descriptors that need to
25361 ** be closed and that list is walked (and cleared) when the last lock
25362 ** clears.
25363 **
25364 ** Yet another problem:  LinuxThreads do not play well with posix locks.
25365 **
25366 ** Many older versions of linux use the LinuxThreads library which is
25367 ** not posix compliant.  Under LinuxThreads, a lock created by thread
25368 ** A cannot be modified or overridden by a different thread B.
25369 ** Only thread A can modify the lock.  Locking behavior is correct
25370 ** if the appliation uses the newer Native Posix Thread Library (NPTL)
25371 ** on linux - with NPTL a lock created by thread A can override locks
25372 ** in thread B.  But there is no way to know at compile-time which
25373 ** threading library is being used.  So there is no way to know at
25374 ** compile-time whether or not thread A can override locks on thread B.
25375 ** One has to do a run-time check to discover the behavior of the
25376 ** current process.
25377 **
25378 ** SQLite used to support LinuxThreads.  But support for LinuxThreads
25379 ** was dropped beginning with version 3.7.0.  SQLite will still work with
25380 ** LinuxThreads provided that (1) there is no more than one connection 
25381 ** per database file in the same process and (2) database connections
25382 ** do not move across threads.
25383 */
25384
25385 /*
25386 ** An instance of the following structure serves as the key used
25387 ** to locate a particular unixInodeInfo object.
25388 */
25389 struct unixFileId {
25390   dev_t dev;                  /* Device number */
25391 #if OS_VXWORKS
25392   struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
25393 #else
25394   ino_t ino;                  /* Inode number */
25395 #endif
25396 };
25397
25398 /*
25399 ** An instance of the following structure is allocated for each open
25400 ** inode.  Or, on LinuxThreads, there is one of these structures for
25401 ** each inode opened by each thread.
25402 **
25403 ** A single inode can have multiple file descriptors, so each unixFile
25404 ** structure contains a pointer to an instance of this object and this
25405 ** object keeps a count of the number of unixFile pointing to it.
25406 */
25407 struct unixInodeInfo {
25408   struct unixFileId fileId;       /* The lookup key */
25409   int nShared;                    /* Number of SHARED locks held */
25410   unsigned char eFileLock;        /* One of SHARED_LOCK, RESERVED_LOCK etc. */
25411   unsigned char bProcessLock;     /* An exclusive process lock is held */
25412   int nRef;                       /* Number of pointers to this structure */
25413   unixShmNode *pShmNode;          /* Shared memory associated with this inode */
25414   int nLock;                      /* Number of outstanding file locks */
25415   UnixUnusedFd *pUnused;          /* Unused file descriptors to close */
25416   unixInodeInfo *pNext;           /* List of all unixInodeInfo objects */
25417   unixInodeInfo *pPrev;           /*    .... doubly linked */
25418 #if SQLITE_ENABLE_LOCKING_STYLE
25419   unsigned long long sharedByte;  /* for AFP simulated shared lock */
25420 #endif
25421 #if OS_VXWORKS
25422   sem_t *pSem;                    /* Named POSIX semaphore */
25423   char aSemName[MAX_PATHNAME+2];  /* Name of that semaphore */
25424 #endif
25425 };
25426
25427 /*
25428 ** A lists of all unixInodeInfo objects.
25429 */
25430 static unixInodeInfo *inodeList = 0;
25431
25432 /*
25433 **
25434 ** This function - unixLogError_x(), is only ever called via the macro
25435 ** unixLogError().
25436 **
25437 ** It is invoked after an error occurs in an OS function and errno has been
25438 ** set. It logs a message using sqlite3_log() containing the current value of
25439 ** errno and, if possible, the human-readable equivalent from strerror() or
25440 ** strerror_r().
25441 **
25442 ** The first argument passed to the macro should be the error code that
25443 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN). 
25444 ** The two subsequent arguments should be the name of the OS function that
25445 ** failed (e.g. "unlink", "open") and the the associated file-system path,
25446 ** if any.
25447 */
25448 #define unixLogError(a,b,c)     unixLogErrorAtLine(a,b,c,__LINE__)
25449 static int unixLogErrorAtLine(
25450   int errcode,                    /* SQLite error code */
25451   const char *zFunc,              /* Name of OS function that failed */
25452   const char *zPath,              /* File path associated with error */
25453   int iLine                       /* Source line number where error occurred */
25454 ){
25455   char *zErr;                     /* Message from strerror() or equivalent */
25456   int iErrno = errno;             /* Saved syscall error number */
25457
25458   /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
25459   ** the strerror() function to obtain the human-readable error message
25460   ** equivalent to errno. Otherwise, use strerror_r().
25461   */ 
25462 #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
25463   char aErr[80];
25464   memset(aErr, 0, sizeof(aErr));
25465   zErr = aErr;
25466
25467   /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
25468   ** assume that the system provides the the GNU version of strerror_r() that 
25469   ** returns a pointer to a buffer containing the error message. That pointer 
25470   ** may point to aErr[], or it may point to some static storage somewhere. 
25471   ** Otherwise, assume that the system provides the POSIX version of 
25472   ** strerror_r(), which always writes an error message into aErr[].
25473   **
25474   ** If the code incorrectly assumes that it is the POSIX version that is
25475   ** available, the error message will often be an empty string. Not a
25476   ** huge problem. Incorrectly concluding that the GNU version is available 
25477   ** could lead to a segfault though.
25478   */
25479 #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
25480   zErr = 
25481 # endif
25482   strerror_r(iErrno, aErr, sizeof(aErr)-1);
25483
25484 #elif SQLITE_THREADSAFE
25485   /* This is a threadsafe build, but strerror_r() is not available. */
25486   zErr = "";
25487 #else
25488   /* Non-threadsafe build, use strerror(). */
25489   zErr = strerror(iErrno);
25490 #endif
25491
25492   assert( errcode!=SQLITE_OK );
25493   if( zPath==0 ) zPath = "";
25494   sqlite3_log(errcode,
25495       "os_unix.c:%d: (%d) %s(%s) - %s",
25496       iLine, iErrno, zFunc, zPath, zErr
25497   );
25498
25499   return errcode;
25500 }
25501
25502 /*
25503 ** Close a file descriptor.
25504 **
25505 ** We assume that close() almost always works, since it is only in a
25506 ** very sick application or on a very sick platform that it might fail.
25507 ** If it does fail, simply leak the file descriptor, but do log the
25508 ** error.
25509 **
25510 ** Note that it is not safe to retry close() after EINTR since the
25511 ** file descriptor might have already been reused by another thread.
25512 ** So we don't even try to recover from an EINTR.  Just log the error
25513 ** and move on.
25514 */
25515 static void robust_close(unixFile *pFile, int h, int lineno){
25516   if( osClose(h) ){
25517     unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
25518                        pFile ? pFile->zPath : 0, lineno);
25519   }
25520 }
25521
25522 /*
25523 ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
25524 */ 
25525 static void closePendingFds(unixFile *pFile){
25526   unixInodeInfo *pInode = pFile->pInode;
25527   UnixUnusedFd *p;
25528   UnixUnusedFd *pNext;
25529   for(p=pInode->pUnused; p; p=pNext){
25530     pNext = p->pNext;
25531     robust_close(pFile, p->fd, __LINE__);
25532     sqlite3_free(p);
25533   }
25534   pInode->pUnused = 0;
25535 }
25536
25537 /*
25538 ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
25539 **
25540 ** The mutex entered using the unixEnterMutex() function must be held
25541 ** when this function is called.
25542 */
25543 static void releaseInodeInfo(unixFile *pFile){
25544   unixInodeInfo *pInode = pFile->pInode;
25545   assert( unixMutexHeld() );
25546   if( ALWAYS(pInode) ){
25547     pInode->nRef--;
25548     if( pInode->nRef==0 ){
25549       assert( pInode->pShmNode==0 );
25550       closePendingFds(pFile);
25551       if( pInode->pPrev ){
25552         assert( pInode->pPrev->pNext==pInode );
25553         pInode->pPrev->pNext = pInode->pNext;
25554       }else{
25555         assert( inodeList==pInode );
25556         inodeList = pInode->pNext;
25557       }
25558       if( pInode->pNext ){
25559         assert( pInode->pNext->pPrev==pInode );
25560         pInode->pNext->pPrev = pInode->pPrev;
25561       }
25562       sqlite3_free(pInode);
25563     }
25564   }
25565 }
25566
25567 /*
25568 ** Given a file descriptor, locate the unixInodeInfo object that
25569 ** describes that file descriptor.  Create a new one if necessary.  The
25570 ** return value might be uninitialized if an error occurs.
25571 **
25572 ** The mutex entered using the unixEnterMutex() function must be held
25573 ** when this function is called.
25574 **
25575 ** Return an appropriate error code.
25576 */
25577 static int findInodeInfo(
25578   unixFile *pFile,               /* Unix file with file desc used in the key */
25579   unixInodeInfo **ppInode        /* Return the unixInodeInfo object here */
25580 ){
25581   int rc;                        /* System call return code */
25582   int fd;                        /* The file descriptor for pFile */
25583   struct unixFileId fileId;      /* Lookup key for the unixInodeInfo */
25584   struct stat statbuf;           /* Low-level file information */
25585   unixInodeInfo *pInode = 0;     /* Candidate unixInodeInfo object */
25586
25587   assert( unixMutexHeld() );
25588
25589   /* Get low-level information about the file that we can used to
25590   ** create a unique name for the file.
25591   */
25592   fd = pFile->h;
25593   rc = osFstat(fd, &statbuf);
25594   if( rc!=0 ){
25595     pFile->lastErrno = errno;
25596 #ifdef EOVERFLOW
25597     if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
25598 #endif
25599     return SQLITE_IOERR;
25600   }
25601
25602 #ifdef __APPLE__
25603   /* On OS X on an msdos filesystem, the inode number is reported
25604   ** incorrectly for zero-size files.  See ticket #3260.  To work
25605   ** around this problem (we consider it a bug in OS X, not SQLite)
25606   ** we always increase the file size to 1 by writing a single byte
25607   ** prior to accessing the inode number.  The one byte written is
25608   ** an ASCII 'S' character which also happens to be the first byte
25609   ** in the header of every SQLite database.  In this way, if there
25610   ** is a race condition such that another thread has already populated
25611   ** the first page of the database, no damage is done.
25612   */
25613   if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
25614     do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
25615     if( rc!=1 ){
25616       pFile->lastErrno = errno;
25617       return SQLITE_IOERR;
25618     }
25619     rc = osFstat(fd, &statbuf);
25620     if( rc!=0 ){
25621       pFile->lastErrno = errno;
25622       return SQLITE_IOERR;
25623     }
25624   }
25625 #endif
25626
25627   memset(&fileId, 0, sizeof(fileId));
25628   fileId.dev = statbuf.st_dev;
25629 #if OS_VXWORKS
25630   fileId.pId = pFile->pId;
25631 #else
25632   fileId.ino = statbuf.st_ino;
25633 #endif
25634   pInode = inodeList;
25635   while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
25636     pInode = pInode->pNext;
25637   }
25638   if( pInode==0 ){
25639     pInode = sqlite3_malloc( sizeof(*pInode) );
25640     if( pInode==0 ){
25641       return SQLITE_NOMEM;
25642     }
25643     memset(pInode, 0, sizeof(*pInode));
25644     memcpy(&pInode->fileId, &fileId, sizeof(fileId));
25645     pInode->nRef = 1;
25646     pInode->pNext = inodeList;
25647     pInode->pPrev = 0;
25648     if( inodeList ) inodeList->pPrev = pInode;
25649     inodeList = pInode;
25650   }else{
25651     pInode->nRef++;
25652   }
25653   *ppInode = pInode;
25654   return SQLITE_OK;
25655 }
25656
25657
25658 /*
25659 ** This routine checks if there is a RESERVED lock held on the specified
25660 ** file by this or any other process. If such a lock is held, set *pResOut
25661 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
25662 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
25663 */
25664 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
25665   int rc = SQLITE_OK;
25666   int reserved = 0;
25667   unixFile *pFile = (unixFile*)id;
25668
25669   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
25670
25671   assert( pFile );
25672   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
25673
25674   /* Check if a thread in this process holds such a lock */
25675   if( pFile->pInode->eFileLock>SHARED_LOCK ){
25676     reserved = 1;
25677   }
25678
25679   /* Otherwise see if some other process holds it.
25680   */
25681 #ifndef __DJGPP__
25682   if( !reserved && !pFile->pInode->bProcessLock ){
25683     struct flock lock;
25684     lock.l_whence = SEEK_SET;
25685     lock.l_start = RESERVED_BYTE;
25686     lock.l_len = 1;
25687     lock.l_type = F_WRLCK;
25688     if( osFcntl(pFile->h, F_GETLK, &lock) ){
25689       rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
25690       pFile->lastErrno = errno;
25691     } else if( lock.l_type!=F_UNLCK ){
25692       reserved = 1;
25693     }
25694   }
25695 #endif
25696   
25697   unixLeaveMutex();
25698   OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
25699
25700   *pResOut = reserved;
25701   return rc;
25702 }
25703
25704 /*
25705 ** Attempt to set a system-lock on the file pFile.  The lock is 
25706 ** described by pLock.
25707 **
25708 ** If the pFile was opened read/write from unix-excl, then the only lock
25709 ** ever obtained is an exclusive lock, and it is obtained exactly once
25710 ** the first time any lock is attempted.  All subsequent system locking
25711 ** operations become no-ops.  Locking operations still happen internally,
25712 ** in order to coordinate access between separate database connections
25713 ** within this process, but all of that is handled in memory and the
25714 ** operating system does not participate.
25715 **
25716 ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
25717 ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
25718 ** and is read-only.
25719 **
25720 ** Zero is returned if the call completes successfully, or -1 if a call
25721 ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
25722 */
25723 static int unixFileLock(unixFile *pFile, struct flock *pLock){
25724   int rc;
25725   unixInodeInfo *pInode = pFile->pInode;
25726   assert( unixMutexHeld() );
25727   assert( pInode!=0 );
25728   if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
25729    && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
25730   ){
25731     if( pInode->bProcessLock==0 ){
25732       struct flock lock;
25733       assert( pInode->nLock==0 );
25734       lock.l_whence = SEEK_SET;
25735       lock.l_start = SHARED_FIRST;
25736       lock.l_len = SHARED_SIZE;
25737       lock.l_type = F_WRLCK;
25738       rc = osFcntl(pFile->h, F_SETLK, &lock);
25739       if( rc<0 ) return rc;
25740       pInode->bProcessLock = 1;
25741       pInode->nLock++;
25742     }else{
25743       rc = 0;
25744     }
25745   }else{
25746     rc = osFcntl(pFile->h, F_SETLK, pLock);
25747   }
25748   return rc;
25749 }
25750
25751 /*
25752 ** Lock the file with the lock specified by parameter eFileLock - one
25753 ** of the following:
25754 **
25755 **     (1) SHARED_LOCK
25756 **     (2) RESERVED_LOCK
25757 **     (3) PENDING_LOCK
25758 **     (4) EXCLUSIVE_LOCK
25759 **
25760 ** Sometimes when requesting one lock state, additional lock states
25761 ** are inserted in between.  The locking might fail on one of the later
25762 ** transitions leaving the lock state different from what it started but
25763 ** still short of its goal.  The following chart shows the allowed
25764 ** transitions and the inserted intermediate states:
25765 **
25766 **    UNLOCKED -> SHARED
25767 **    SHARED -> RESERVED
25768 **    SHARED -> (PENDING) -> EXCLUSIVE
25769 **    RESERVED -> (PENDING) -> EXCLUSIVE
25770 **    PENDING -> EXCLUSIVE
25771 **
25772 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
25773 ** routine to lower a locking level.
25774 */
25775 static int unixLock(sqlite3_file *id, int eFileLock){
25776   /* The following describes the implementation of the various locks and
25777   ** lock transitions in terms of the POSIX advisory shared and exclusive
25778   ** lock primitives (called read-locks and write-locks below, to avoid
25779   ** confusion with SQLite lock names). The algorithms are complicated
25780   ** slightly in order to be compatible with windows systems simultaneously
25781   ** accessing the same database file, in case that is ever required.
25782   **
25783   ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
25784   ** byte', each single bytes at well known offsets, and the 'shared byte
25785   ** range', a range of 510 bytes at a well known offset.
25786   **
25787   ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
25788   ** byte'.  If this is successful, a random byte from the 'shared byte
25789   ** range' is read-locked and the lock on the 'pending byte' released.
25790   **
25791   ** A process may only obtain a RESERVED lock after it has a SHARED lock.
25792   ** A RESERVED lock is implemented by grabbing a write-lock on the
25793   ** 'reserved byte'. 
25794   **
25795   ** A process may only obtain a PENDING lock after it has obtained a
25796   ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
25797   ** on the 'pending byte'. This ensures that no new SHARED locks can be
25798   ** obtained, but existing SHARED locks are allowed to persist. A process
25799   ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
25800   ** This property is used by the algorithm for rolling back a journal file
25801   ** after a crash.
25802   **
25803   ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
25804   ** implemented by obtaining a write-lock on the entire 'shared byte
25805   ** range'. Since all other locks require a read-lock on one of the bytes
25806   ** within this range, this ensures that no other locks are held on the
25807   ** database. 
25808   **
25809   ** The reason a single byte cannot be used instead of the 'shared byte
25810   ** range' is that some versions of windows do not support read-locks. By
25811   ** locking a random byte from a range, concurrent SHARED locks may exist
25812   ** even if the locking primitive used is always a write-lock.
25813   */
25814   int rc = SQLITE_OK;
25815   unixFile *pFile = (unixFile*)id;
25816   unixInodeInfo *pInode = pFile->pInode;
25817   struct flock lock;
25818   int tErrno = 0;
25819
25820   assert( pFile );
25821   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
25822       azFileLock(eFileLock), azFileLock(pFile->eFileLock),
25823       azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
25824
25825   /* If there is already a lock of this type or more restrictive on the
25826   ** unixFile, do nothing. Don't use the end_lock: exit path, as
25827   ** unixEnterMutex() hasn't been called yet.
25828   */
25829   if( pFile->eFileLock>=eFileLock ){
25830     OSTRACE(("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
25831             azFileLock(eFileLock)));
25832     return SQLITE_OK;
25833   }
25834
25835   /* Make sure the locking sequence is correct.
25836   **  (1) We never move from unlocked to anything higher than shared lock.
25837   **  (2) SQLite never explicitly requests a pendig lock.
25838   **  (3) A shared lock is always held when a reserve lock is requested.
25839   */
25840   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
25841   assert( eFileLock!=PENDING_LOCK );
25842   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
25843
25844   /* This mutex is needed because pFile->pInode is shared across threads
25845   */
25846   unixEnterMutex();
25847   pInode = pFile->pInode;
25848
25849   /* If some thread using this PID has a lock via a different unixFile*
25850   ** handle that precludes the requested lock, return BUSY.
25851   */
25852   if( (pFile->eFileLock!=pInode->eFileLock && 
25853           (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
25854   ){
25855     rc = SQLITE_BUSY;
25856     goto end_lock;
25857   }
25858
25859   /* If a SHARED lock is requested, and some thread using this PID already
25860   ** has a SHARED or RESERVED lock, then increment reference counts and
25861   ** return SQLITE_OK.
25862   */
25863   if( eFileLock==SHARED_LOCK && 
25864       (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
25865     assert( eFileLock==SHARED_LOCK );
25866     assert( pFile->eFileLock==0 );
25867     assert( pInode->nShared>0 );
25868     pFile->eFileLock = SHARED_LOCK;
25869     pInode->nShared++;
25870     pInode->nLock++;
25871     goto end_lock;
25872   }
25873
25874
25875   /* A PENDING lock is needed before acquiring a SHARED lock and before
25876   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
25877   ** be released.
25878   */
25879   lock.l_len = 1L;
25880   lock.l_whence = SEEK_SET;
25881   if( eFileLock==SHARED_LOCK 
25882       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
25883   ){
25884     lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
25885     lock.l_start = PENDING_BYTE;
25886     if( unixFileLock(pFile, &lock) ){
25887       tErrno = errno;
25888       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
25889       if( rc!=SQLITE_BUSY ){
25890         pFile->lastErrno = tErrno;
25891       }
25892       goto end_lock;
25893     }
25894   }
25895
25896
25897   /* If control gets to this point, then actually go ahead and make
25898   ** operating system calls for the specified lock.
25899   */
25900   if( eFileLock==SHARED_LOCK ){
25901     assert( pInode->nShared==0 );
25902     assert( pInode->eFileLock==0 );
25903     assert( rc==SQLITE_OK );
25904
25905     /* Now get the read-lock */
25906     lock.l_start = SHARED_FIRST;
25907     lock.l_len = SHARED_SIZE;
25908     if( unixFileLock(pFile, &lock) ){
25909       tErrno = errno;
25910       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
25911     }
25912
25913     /* Drop the temporary PENDING lock */
25914     lock.l_start = PENDING_BYTE;
25915     lock.l_len = 1L;
25916     lock.l_type = F_UNLCK;
25917     if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
25918       /* This could happen with a network mount */
25919       tErrno = errno;
25920       rc = SQLITE_IOERR_UNLOCK; 
25921     }
25922
25923     if( rc ){
25924       if( rc!=SQLITE_BUSY ){
25925         pFile->lastErrno = tErrno;
25926       }
25927       goto end_lock;
25928     }else{
25929       pFile->eFileLock = SHARED_LOCK;
25930       pInode->nLock++;
25931       pInode->nShared = 1;
25932     }
25933   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
25934     /* We are trying for an exclusive lock but another thread in this
25935     ** same process is still holding a shared lock. */
25936     rc = SQLITE_BUSY;
25937   }else{
25938     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
25939     ** assumed that there is a SHARED or greater lock on the file
25940     ** already.
25941     */
25942     assert( 0!=pFile->eFileLock );
25943     lock.l_type = F_WRLCK;
25944
25945     assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
25946     if( eFileLock==RESERVED_LOCK ){
25947       lock.l_start = RESERVED_BYTE;
25948       lock.l_len = 1L;
25949     }else{
25950       lock.l_start = SHARED_FIRST;
25951       lock.l_len = SHARED_SIZE;
25952     }
25953
25954     if( unixFileLock(pFile, &lock) ){
25955       tErrno = errno;
25956       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
25957       if( rc!=SQLITE_BUSY ){
25958         pFile->lastErrno = tErrno;
25959       }
25960     }
25961   }
25962   
25963
25964 #ifndef NDEBUG
25965   /* Set up the transaction-counter change checking flags when
25966   ** transitioning from a SHARED to a RESERVED lock.  The change
25967   ** from SHARED to RESERVED marks the beginning of a normal
25968   ** write operation (not a hot journal rollback).
25969   */
25970   if( rc==SQLITE_OK
25971    && pFile->eFileLock<=SHARED_LOCK
25972    && eFileLock==RESERVED_LOCK
25973   ){
25974     pFile->transCntrChng = 0;
25975     pFile->dbUpdate = 0;
25976     pFile->inNormalWrite = 1;
25977   }
25978 #endif
25979
25980
25981   if( rc==SQLITE_OK ){
25982     pFile->eFileLock = eFileLock;
25983     pInode->eFileLock = eFileLock;
25984   }else if( eFileLock==EXCLUSIVE_LOCK ){
25985     pFile->eFileLock = PENDING_LOCK;
25986     pInode->eFileLock = PENDING_LOCK;
25987   }
25988
25989 end_lock:
25990   unixLeaveMutex();
25991   OSTRACE(("LOCK    %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock), 
25992       rc==SQLITE_OK ? "ok" : "failed"));
25993   return rc;
25994 }
25995
25996 /*
25997 ** Add the file descriptor used by file handle pFile to the corresponding
25998 ** pUnused list.
25999 */
26000 static void setPendingFd(unixFile *pFile){
26001   unixInodeInfo *pInode = pFile->pInode;
26002   UnixUnusedFd *p = pFile->pUnused;
26003   p->pNext = pInode->pUnused;
26004   pInode->pUnused = p;
26005   pFile->h = -1;
26006   pFile->pUnused = 0;
26007 }
26008
26009 /*
26010 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
26011 ** must be either NO_LOCK or SHARED_LOCK.
26012 **
26013 ** If the locking level of the file descriptor is already at or below
26014 ** the requested locking level, this routine is a no-op.
26015 ** 
26016 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
26017 ** the byte range is divided into 2 parts and the first part is unlocked then
26018 ** set to a read lock, then the other part is simply unlocked.  This works 
26019 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to 
26020 ** remove the write lock on a region when a read lock is set.
26021 */
26022 static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
26023   unixFile *pFile = (unixFile*)id;
26024   unixInodeInfo *pInode;
26025   struct flock lock;
26026   int rc = SQLITE_OK;
26027   int h;
26028
26029   assert( pFile );
26030   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
26031       pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
26032       getpid()));
26033
26034   assert( eFileLock<=SHARED_LOCK );
26035   if( pFile->eFileLock<=eFileLock ){
26036     return SQLITE_OK;
26037   }
26038   unixEnterMutex();
26039   h = pFile->h;
26040   pInode = pFile->pInode;
26041   assert( pInode->nShared!=0 );
26042   if( pFile->eFileLock>SHARED_LOCK ){
26043     assert( pInode->eFileLock==pFile->eFileLock );
26044     SimulateIOErrorBenign(1);
26045     SimulateIOError( h=(-1) )
26046     SimulateIOErrorBenign(0);
26047
26048 #ifndef NDEBUG
26049     /* When reducing a lock such that other processes can start
26050     ** reading the database file again, make sure that the
26051     ** transaction counter was updated if any part of the database
26052     ** file changed.  If the transaction counter is not updated,
26053     ** other connections to the same file might not realize that
26054     ** the file has changed and hence might not know to flush their
26055     ** cache.  The use of a stale cache can lead to database corruption.
26056     */
26057 #if 0
26058     assert( pFile->inNormalWrite==0
26059          || pFile->dbUpdate==0
26060          || pFile->transCntrChng==1 );
26061 #endif
26062     pFile->inNormalWrite = 0;
26063 #endif
26064
26065     /* downgrading to a shared lock on NFS involves clearing the write lock
26066     ** before establishing the readlock - to avoid a race condition we downgrade
26067     ** the lock in 2 blocks, so that part of the range will be covered by a 
26068     ** write lock until the rest is covered by a read lock:
26069     **  1:   [WWWWW]
26070     **  2:   [....W]
26071     **  3:   [RRRRW]
26072     **  4:   [RRRR.]
26073     */
26074     if( eFileLock==SHARED_LOCK ){
26075
26076 #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
26077       (void)handleNFSUnlock;
26078       assert( handleNFSUnlock==0 );
26079 #endif
26080 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26081       if( handleNFSUnlock ){
26082         int tErrno;               /* Error code from system call errors */
26083         off_t divSize = SHARED_SIZE - 1;
26084         
26085         lock.l_type = F_UNLCK;
26086         lock.l_whence = SEEK_SET;
26087         lock.l_start = SHARED_FIRST;
26088         lock.l_len = divSize;
26089         if( unixFileLock(pFile, &lock)==(-1) ){
26090           tErrno = errno;
26091           rc = SQLITE_IOERR_UNLOCK;
26092           if( IS_LOCK_ERROR(rc) ){
26093             pFile->lastErrno = tErrno;
26094           }
26095           goto end_unlock;
26096         }
26097         lock.l_type = F_RDLCK;
26098         lock.l_whence = SEEK_SET;
26099         lock.l_start = SHARED_FIRST;
26100         lock.l_len = divSize;
26101         if( unixFileLock(pFile, &lock)==(-1) ){
26102           tErrno = errno;
26103           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
26104           if( IS_LOCK_ERROR(rc) ){
26105             pFile->lastErrno = tErrno;
26106           }
26107           goto end_unlock;
26108         }
26109         lock.l_type = F_UNLCK;
26110         lock.l_whence = SEEK_SET;
26111         lock.l_start = SHARED_FIRST+divSize;
26112         lock.l_len = SHARED_SIZE-divSize;
26113         if( unixFileLock(pFile, &lock)==(-1) ){
26114           tErrno = errno;
26115           rc = SQLITE_IOERR_UNLOCK;
26116           if( IS_LOCK_ERROR(rc) ){
26117             pFile->lastErrno = tErrno;
26118           }
26119           goto end_unlock;
26120         }
26121       }else
26122 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
26123       {
26124         lock.l_type = F_RDLCK;
26125         lock.l_whence = SEEK_SET;
26126         lock.l_start = SHARED_FIRST;
26127         lock.l_len = SHARED_SIZE;
26128         if( unixFileLock(pFile, &lock) ){
26129           /* In theory, the call to unixFileLock() cannot fail because another
26130           ** process is holding an incompatible lock. If it does, this 
26131           ** indicates that the other process is not following the locking
26132           ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
26133           ** SQLITE_BUSY would confuse the upper layer (in practice it causes 
26134           ** an assert to fail). */ 
26135           rc = SQLITE_IOERR_RDLOCK;
26136           pFile->lastErrno = errno;
26137           goto end_unlock;
26138         }
26139       }
26140     }
26141     lock.l_type = F_UNLCK;
26142     lock.l_whence = SEEK_SET;
26143     lock.l_start = PENDING_BYTE;
26144     lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
26145     if( unixFileLock(pFile, &lock)==0 ){
26146       pInode->eFileLock = SHARED_LOCK;
26147     }else{
26148       rc = SQLITE_IOERR_UNLOCK;
26149       pFile->lastErrno = errno;
26150       goto end_unlock;
26151     }
26152   }
26153   if( eFileLock==NO_LOCK ){
26154     /* Decrement the shared lock counter.  Release the lock using an
26155     ** OS call only when all threads in this same process have released
26156     ** the lock.
26157     */
26158     pInode->nShared--;
26159     if( pInode->nShared==0 ){
26160       lock.l_type = F_UNLCK;
26161       lock.l_whence = SEEK_SET;
26162       lock.l_start = lock.l_len = 0L;
26163       SimulateIOErrorBenign(1);
26164       SimulateIOError( h=(-1) )
26165       SimulateIOErrorBenign(0);
26166       if( unixFileLock(pFile, &lock)==0 ){
26167         pInode->eFileLock = NO_LOCK;
26168       }else{
26169         rc = SQLITE_IOERR_UNLOCK;
26170         pFile->lastErrno = errno;
26171         pInode->eFileLock = NO_LOCK;
26172         pFile->eFileLock = NO_LOCK;
26173       }
26174     }
26175
26176     /* Decrement the count of locks against this same file.  When the
26177     ** count reaches zero, close any other file descriptors whose close
26178     ** was deferred because of outstanding locks.
26179     */
26180     pInode->nLock--;
26181     assert( pInode->nLock>=0 );
26182     if( pInode->nLock==0 ){
26183       closePendingFds(pFile);
26184     }
26185   }
26186         
26187 end_unlock:
26188   unixLeaveMutex();
26189   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
26190   return rc;
26191 }
26192
26193 /*
26194 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
26195 ** must be either NO_LOCK or SHARED_LOCK.
26196 **
26197 ** If the locking level of the file descriptor is already at or below
26198 ** the requested locking level, this routine is a no-op.
26199 */
26200 static int unixUnlock(sqlite3_file *id, int eFileLock){
26201   return posixUnlock(id, eFileLock, 0);
26202 }
26203
26204 /*
26205 ** This function performs the parts of the "close file" operation 
26206 ** common to all locking schemes. It closes the directory and file
26207 ** handles, if they are valid, and sets all fields of the unixFile
26208 ** structure to 0.
26209 **
26210 ** It is *not* necessary to hold the mutex when this routine is called,
26211 ** even on VxWorks.  A mutex will be acquired on VxWorks by the
26212 ** vxworksReleaseFileId() routine.
26213 */
26214 static int closeUnixFile(sqlite3_file *id){
26215   unixFile *pFile = (unixFile*)id;
26216   if( pFile->dirfd>=0 ){
26217     robust_close(pFile, pFile->dirfd, __LINE__);
26218     pFile->dirfd=-1;
26219   }
26220   if( pFile->h>=0 ){
26221     robust_close(pFile, pFile->h, __LINE__);
26222     pFile->h = -1;
26223   }
26224 #if OS_VXWORKS
26225   if( pFile->pId ){
26226     if( pFile->isDelete ){
26227       unlink(pFile->pId->zCanonicalName);
26228     }
26229     vxworksReleaseFileId(pFile->pId);
26230     pFile->pId = 0;
26231   }
26232 #endif
26233   OSTRACE(("CLOSE   %-3d\n", pFile->h));
26234   OpenCounter(-1);
26235   sqlite3_free(pFile->pUnused);
26236   memset(pFile, 0, sizeof(unixFile));
26237   return SQLITE_OK;
26238 }
26239
26240 /*
26241 ** Close a file.
26242 */
26243 static int unixClose(sqlite3_file *id){
26244   int rc = SQLITE_OK;
26245   unixFile *pFile = (unixFile *)id;
26246   unixUnlock(id, NO_LOCK);
26247   unixEnterMutex();
26248
26249   /* unixFile.pInode is always valid here. Otherwise, a different close
26250   ** routine (e.g. nolockClose()) would be called instead.
26251   */
26252   assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
26253   if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
26254     /* If there are outstanding locks, do not actually close the file just
26255     ** yet because that would clear those locks.  Instead, add the file
26256     ** descriptor to pInode->pUnused list.  It will be automatically closed 
26257     ** when the last lock is cleared.
26258     */
26259     setPendingFd(pFile);
26260   }
26261   releaseInodeInfo(pFile);
26262   rc = closeUnixFile(id);
26263   unixLeaveMutex();
26264   return rc;
26265 }
26266
26267 /************** End of the posix advisory lock implementation *****************
26268 ******************************************************************************/
26269
26270 /******************************************************************************
26271 ****************************** No-op Locking **********************************
26272 **
26273 ** Of the various locking implementations available, this is by far the
26274 ** simplest:  locking is ignored.  No attempt is made to lock the database
26275 ** file for reading or writing.
26276 **
26277 ** This locking mode is appropriate for use on read-only databases
26278 ** (ex: databases that are burned into CD-ROM, for example.)  It can
26279 ** also be used if the application employs some external mechanism to
26280 ** prevent simultaneous access of the same database by two or more
26281 ** database connections.  But there is a serious risk of database
26282 ** corruption if this locking mode is used in situations where multiple
26283 ** database connections are accessing the same database file at the same
26284 ** time and one or more of those connections are writing.
26285 */
26286
26287 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
26288   UNUSED_PARAMETER(NotUsed);
26289   *pResOut = 0;
26290   return SQLITE_OK;
26291 }
26292 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
26293   UNUSED_PARAMETER2(NotUsed, NotUsed2);
26294   return SQLITE_OK;
26295 }
26296 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
26297   UNUSED_PARAMETER2(NotUsed, NotUsed2);
26298   return SQLITE_OK;
26299 }
26300
26301 /*
26302 ** Close the file.
26303 */
26304 static int nolockClose(sqlite3_file *id) {
26305   return closeUnixFile(id);
26306 }
26307
26308 /******************* End of the no-op lock implementation *********************
26309 ******************************************************************************/
26310
26311 /******************************************************************************
26312 ************************* Begin dot-file Locking ******************************
26313 **
26314 ** The dotfile locking implementation uses the existance of separate lock
26315 ** files in order to control access to the database.  This works on just
26316 ** about every filesystem imaginable.  But there are serious downsides:
26317 **
26318 **    (1)  There is zero concurrency.  A single reader blocks all other
26319 **         connections from reading or writing the database.
26320 **
26321 **    (2)  An application crash or power loss can leave stale lock files
26322 **         sitting around that need to be cleared manually.
26323 **
26324 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
26325 ** other locking strategy is available.
26326 **
26327 ** Dotfile locking works by creating a file in the same directory as the
26328 ** database and with the same name but with a ".lock" extension added.
26329 ** The existance of a lock file implies an EXCLUSIVE lock.  All other lock
26330 ** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
26331 */
26332
26333 /*
26334 ** The file suffix added to the data base filename in order to create the
26335 ** lock file.
26336 */
26337 #define DOTLOCK_SUFFIX ".lock"
26338
26339 /*
26340 ** This routine checks if there is a RESERVED lock held on the specified
26341 ** file by this or any other process. If such a lock is held, set *pResOut
26342 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
26343 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26344 **
26345 ** In dotfile locking, either a lock exists or it does not.  So in this
26346 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
26347 ** is held on the file and false if the file is unlocked.
26348 */
26349 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
26350   int rc = SQLITE_OK;
26351   int reserved = 0;
26352   unixFile *pFile = (unixFile*)id;
26353
26354   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
26355   
26356   assert( pFile );
26357
26358   /* Check if a thread in this process holds such a lock */
26359   if( pFile->eFileLock>SHARED_LOCK ){
26360     /* Either this connection or some other connection in the same process
26361     ** holds a lock on the file.  No need to check further. */
26362     reserved = 1;
26363   }else{
26364     /* The lock is held if and only if the lockfile exists */
26365     const char *zLockFile = (const char*)pFile->lockingContext;
26366     reserved = osAccess(zLockFile, 0)==0;
26367   }
26368   OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
26369   *pResOut = reserved;
26370   return rc;
26371 }
26372
26373 /*
26374 ** Lock the file with the lock specified by parameter eFileLock - one
26375 ** of the following:
26376 **
26377 **     (1) SHARED_LOCK
26378 **     (2) RESERVED_LOCK
26379 **     (3) PENDING_LOCK
26380 **     (4) EXCLUSIVE_LOCK
26381 **
26382 ** Sometimes when requesting one lock state, additional lock states
26383 ** are inserted in between.  The locking might fail on one of the later
26384 ** transitions leaving the lock state different from what it started but
26385 ** still short of its goal.  The following chart shows the allowed
26386 ** transitions and the inserted intermediate states:
26387 **
26388 **    UNLOCKED -> SHARED
26389 **    SHARED -> RESERVED
26390 **    SHARED -> (PENDING) -> EXCLUSIVE
26391 **    RESERVED -> (PENDING) -> EXCLUSIVE
26392 **    PENDING -> EXCLUSIVE
26393 **
26394 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
26395 ** routine to lower a locking level.
26396 **
26397 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
26398 ** But we track the other locking levels internally.
26399 */
26400 static int dotlockLock(sqlite3_file *id, int eFileLock) {
26401   unixFile *pFile = (unixFile*)id;
26402   int fd;
26403   char *zLockFile = (char *)pFile->lockingContext;
26404   int rc = SQLITE_OK;
26405
26406
26407   /* If we have any lock, then the lock file already exists.  All we have
26408   ** to do is adjust our internal record of the lock level.
26409   */
26410   if( pFile->eFileLock > NO_LOCK ){
26411     pFile->eFileLock = eFileLock;
26412     /* Always update the timestamp on the old file */
26413 #ifdef HAVE_UTIME
26414     utime(zLockFile, NULL);
26415 #else
26416     utimes(zLockFile, NULL);
26417 #endif
26418     return SQLITE_OK;
26419   }
26420   
26421   /* grab an exclusive lock */
26422   fd = robust_open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
26423   if( fd<0 ){
26424     /* failed to open/create the file, someone else may have stolen the lock */
26425     int tErrno = errno;
26426     if( EEXIST == tErrno ){
26427       rc = SQLITE_BUSY;
26428     } else {
26429       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26430       if( IS_LOCK_ERROR(rc) ){
26431         pFile->lastErrno = tErrno;
26432       }
26433     }
26434     return rc;
26435   } 
26436   robust_close(pFile, fd, __LINE__);
26437   
26438   /* got it, set the type and return ok */
26439   pFile->eFileLock = eFileLock;
26440   return rc;
26441 }
26442
26443 /*
26444 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
26445 ** must be either NO_LOCK or SHARED_LOCK.
26446 **
26447 ** If the locking level of the file descriptor is already at or below
26448 ** the requested locking level, this routine is a no-op.
26449 **
26450 ** When the locking level reaches NO_LOCK, delete the lock file.
26451 */
26452 static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
26453   unixFile *pFile = (unixFile*)id;
26454   char *zLockFile = (char *)pFile->lockingContext;
26455
26456   assert( pFile );
26457   OSTRACE(("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
26458            pFile->eFileLock, getpid()));
26459   assert( eFileLock<=SHARED_LOCK );
26460   
26461   /* no-op if possible */
26462   if( pFile->eFileLock==eFileLock ){
26463     return SQLITE_OK;
26464   }
26465
26466   /* To downgrade to shared, simply update our internal notion of the
26467   ** lock state.  No need to mess with the file on disk.
26468   */
26469   if( eFileLock==SHARED_LOCK ){
26470     pFile->eFileLock = SHARED_LOCK;
26471     return SQLITE_OK;
26472   }
26473   
26474   /* To fully unlock the database, delete the lock file */
26475   assert( eFileLock==NO_LOCK );
26476   if( unlink(zLockFile) ){
26477     int rc = 0;
26478     int tErrno = errno;
26479     if( ENOENT != tErrno ){
26480       rc = SQLITE_IOERR_UNLOCK;
26481     }
26482     if( IS_LOCK_ERROR(rc) ){
26483       pFile->lastErrno = tErrno;
26484     }
26485     return rc; 
26486   }
26487   pFile->eFileLock = NO_LOCK;
26488   return SQLITE_OK;
26489 }
26490
26491 /*
26492 ** Close a file.  Make sure the lock has been released before closing.
26493 */
26494 static int dotlockClose(sqlite3_file *id) {
26495   int rc;
26496   if( id ){
26497     unixFile *pFile = (unixFile*)id;
26498     dotlockUnlock(id, NO_LOCK);
26499     sqlite3_free(pFile->lockingContext);
26500   }
26501   rc = closeUnixFile(id);
26502   return rc;
26503 }
26504 /****************** End of the dot-file lock implementation *******************
26505 ******************************************************************************/
26506
26507 /******************************************************************************
26508 ************************** Begin flock Locking ********************************
26509 **
26510 ** Use the flock() system call to do file locking.
26511 **
26512 ** flock() locking is like dot-file locking in that the various
26513 ** fine-grain locking levels supported by SQLite are collapsed into
26514 ** a single exclusive lock.  In other words, SHARED, RESERVED, and
26515 ** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
26516 ** still works when you do this, but concurrency is reduced since
26517 ** only a single process can be reading the database at a time.
26518 **
26519 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
26520 ** compiling for VXWORKS.
26521 */
26522 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
26523
26524 /*
26525 ** Retry flock() calls that fail with EINTR
26526 */
26527 #ifdef EINTR
26528 static int robust_flock(int fd, int op){
26529   int rc;
26530   do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
26531   return rc;
26532 }
26533 #else
26534 # define robust_flock(a,b) flock(a,b)
26535 #endif
26536      
26537
26538 /*
26539 ** This routine checks if there is a RESERVED lock held on the specified
26540 ** file by this or any other process. If such a lock is held, set *pResOut
26541 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
26542 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26543 */
26544 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
26545   int rc = SQLITE_OK;
26546   int reserved = 0;
26547   unixFile *pFile = (unixFile*)id;
26548   
26549   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
26550   
26551   assert( pFile );
26552   
26553   /* Check if a thread in this process holds such a lock */
26554   if( pFile->eFileLock>SHARED_LOCK ){
26555     reserved = 1;
26556   }
26557   
26558   /* Otherwise see if some other process holds it. */
26559   if( !reserved ){
26560     /* attempt to get the lock */
26561     int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
26562     if( !lrc ){
26563       /* got the lock, unlock it */
26564       lrc = robust_flock(pFile->h, LOCK_UN);
26565       if ( lrc ) {
26566         int tErrno = errno;
26567         /* unlock failed with an error */
26568         lrc = SQLITE_IOERR_UNLOCK; 
26569         if( IS_LOCK_ERROR(lrc) ){
26570           pFile->lastErrno = tErrno;
26571           rc = lrc;
26572         }
26573       }
26574     } else {
26575       int tErrno = errno;
26576       reserved = 1;
26577       /* someone else might have it reserved */
26578       lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); 
26579       if( IS_LOCK_ERROR(lrc) ){
26580         pFile->lastErrno = tErrno;
26581         rc = lrc;
26582       }
26583     }
26584   }
26585   OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
26586
26587 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
26588   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
26589     rc = SQLITE_OK;
26590     reserved=1;
26591   }
26592 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
26593   *pResOut = reserved;
26594   return rc;
26595 }
26596
26597 /*
26598 ** Lock the file with the lock specified by parameter eFileLock - one
26599 ** of the following:
26600 **
26601 **     (1) SHARED_LOCK
26602 **     (2) RESERVED_LOCK
26603 **     (3) PENDING_LOCK
26604 **     (4) EXCLUSIVE_LOCK
26605 **
26606 ** Sometimes when requesting one lock state, additional lock states
26607 ** are inserted in between.  The locking might fail on one of the later
26608 ** transitions leaving the lock state different from what it started but
26609 ** still short of its goal.  The following chart shows the allowed
26610 ** transitions and the inserted intermediate states:
26611 **
26612 **    UNLOCKED -> SHARED
26613 **    SHARED -> RESERVED
26614 **    SHARED -> (PENDING) -> EXCLUSIVE
26615 **    RESERVED -> (PENDING) -> EXCLUSIVE
26616 **    PENDING -> EXCLUSIVE
26617 **
26618 ** flock() only really support EXCLUSIVE locks.  We track intermediate
26619 ** lock states in the sqlite3_file structure, but all locks SHARED or
26620 ** above are really EXCLUSIVE locks and exclude all other processes from
26621 ** access the file.
26622 **
26623 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
26624 ** routine to lower a locking level.
26625 */
26626 static int flockLock(sqlite3_file *id, int eFileLock) {
26627   int rc = SQLITE_OK;
26628   unixFile *pFile = (unixFile*)id;
26629
26630   assert( pFile );
26631
26632   /* if we already have a lock, it is exclusive.  
26633   ** Just adjust level and punt on outta here. */
26634   if (pFile->eFileLock > NO_LOCK) {
26635     pFile->eFileLock = eFileLock;
26636     return SQLITE_OK;
26637   }
26638   
26639   /* grab an exclusive lock */
26640   
26641   if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
26642     int tErrno = errno;
26643     /* didn't get, must be busy */
26644     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26645     if( IS_LOCK_ERROR(rc) ){
26646       pFile->lastErrno = tErrno;
26647     }
26648   } else {
26649     /* got it, set the type and return ok */
26650     pFile->eFileLock = eFileLock;
26651   }
26652   OSTRACE(("LOCK    %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock), 
26653            rc==SQLITE_OK ? "ok" : "failed"));
26654 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
26655   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
26656     rc = SQLITE_BUSY;
26657   }
26658 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
26659   return rc;
26660 }
26661
26662
26663 /*
26664 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
26665 ** must be either NO_LOCK or SHARED_LOCK.
26666 **
26667 ** If the locking level of the file descriptor is already at or below
26668 ** the requested locking level, this routine is a no-op.
26669 */
26670 static int flockUnlock(sqlite3_file *id, int eFileLock) {
26671   unixFile *pFile = (unixFile*)id;
26672   
26673   assert( pFile );
26674   OSTRACE(("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
26675            pFile->eFileLock, getpid()));
26676   assert( eFileLock<=SHARED_LOCK );
26677   
26678   /* no-op if possible */
26679   if( pFile->eFileLock==eFileLock ){
26680     return SQLITE_OK;
26681   }
26682   
26683   /* shared can just be set because we always have an exclusive */
26684   if (eFileLock==SHARED_LOCK) {
26685     pFile->eFileLock = eFileLock;
26686     return SQLITE_OK;
26687   }
26688   
26689   /* no, really, unlock. */
26690   if( robust_flock(pFile->h, LOCK_UN) ){
26691 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
26692     return SQLITE_OK;
26693 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
26694     return SQLITE_IOERR_UNLOCK;
26695   }else{
26696     pFile->eFileLock = NO_LOCK;
26697     return SQLITE_OK;
26698   }
26699 }
26700
26701 /*
26702 ** Close a file.
26703 */
26704 static int flockClose(sqlite3_file *id) {
26705   if( id ){
26706     flockUnlock(id, NO_LOCK);
26707   }
26708   return closeUnixFile(id);
26709 }
26710
26711 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
26712
26713 /******************* End of the flock lock implementation *********************
26714 ******************************************************************************/
26715
26716 /******************************************************************************
26717 ************************ Begin Named Semaphore Locking ************************
26718 **
26719 ** Named semaphore locking is only supported on VxWorks.
26720 **
26721 ** Semaphore locking is like dot-lock and flock in that it really only
26722 ** supports EXCLUSIVE locking.  Only a single process can read or write
26723 ** the database file at a time.  This reduces potential concurrency, but
26724 ** makes the lock implementation much easier.
26725 */
26726 #if OS_VXWORKS
26727
26728 /*
26729 ** This routine checks if there is a RESERVED lock held on the specified
26730 ** file by this or any other process. If such a lock is held, set *pResOut
26731 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
26732 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26733 */
26734 static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
26735   int rc = SQLITE_OK;
26736   int reserved = 0;
26737   unixFile *pFile = (unixFile*)id;
26738
26739   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
26740   
26741   assert( pFile );
26742
26743   /* Check if a thread in this process holds such a lock */
26744   if( pFile->eFileLock>SHARED_LOCK ){
26745     reserved = 1;
26746   }
26747   
26748   /* Otherwise see if some other process holds it. */
26749   if( !reserved ){
26750     sem_t *pSem = pFile->pInode->pSem;
26751     struct stat statBuf;
26752
26753     if( sem_trywait(pSem)==-1 ){
26754       int tErrno = errno;
26755       if( EAGAIN != tErrno ){
26756         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
26757         pFile->lastErrno = tErrno;
26758       } else {
26759         /* someone else has the lock when we are in NO_LOCK */
26760         reserved = (pFile->eFileLock < SHARED_LOCK);
26761       }
26762     }else{
26763       /* we could have it if we want it */
26764       sem_post(pSem);
26765     }
26766   }
26767   OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
26768
26769   *pResOut = reserved;
26770   return rc;
26771 }
26772
26773 /*
26774 ** Lock the file with the lock specified by parameter eFileLock - one
26775 ** of the following:
26776 **
26777 **     (1) SHARED_LOCK
26778 **     (2) RESERVED_LOCK
26779 **     (3) PENDING_LOCK
26780 **     (4) EXCLUSIVE_LOCK
26781 **
26782 ** Sometimes when requesting one lock state, additional lock states
26783 ** are inserted in between.  The locking might fail on one of the later
26784 ** transitions leaving the lock state different from what it started but
26785 ** still short of its goal.  The following chart shows the allowed
26786 ** transitions and the inserted intermediate states:
26787 **
26788 **    UNLOCKED -> SHARED
26789 **    SHARED -> RESERVED
26790 **    SHARED -> (PENDING) -> EXCLUSIVE
26791 **    RESERVED -> (PENDING) -> EXCLUSIVE
26792 **    PENDING -> EXCLUSIVE
26793 **
26794 ** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
26795 ** lock states in the sqlite3_file structure, but all locks SHARED or
26796 ** above are really EXCLUSIVE locks and exclude all other processes from
26797 ** access the file.
26798 **
26799 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
26800 ** routine to lower a locking level.
26801 */
26802 static int semLock(sqlite3_file *id, int eFileLock) {
26803   unixFile *pFile = (unixFile*)id;
26804   int fd;
26805   sem_t *pSem = pFile->pInode->pSem;
26806   int rc = SQLITE_OK;
26807
26808   /* if we already have a lock, it is exclusive.  
26809   ** Just adjust level and punt on outta here. */
26810   if (pFile->eFileLock > NO_LOCK) {
26811     pFile->eFileLock = eFileLock;
26812     rc = SQLITE_OK;
26813     goto sem_end_lock;
26814   }
26815   
26816   /* lock semaphore now but bail out when already locked. */
26817   if( sem_trywait(pSem)==-1 ){
26818     rc = SQLITE_BUSY;
26819     goto sem_end_lock;
26820   }
26821
26822   /* got it, set the type and return ok */
26823   pFile->eFileLock = eFileLock;
26824
26825  sem_end_lock:
26826   return rc;
26827 }
26828
26829 /*
26830 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
26831 ** must be either NO_LOCK or SHARED_LOCK.
26832 **
26833 ** If the locking level of the file descriptor is already at or below
26834 ** the requested locking level, this routine is a no-op.
26835 */
26836 static int semUnlock(sqlite3_file *id, int eFileLock) {
26837   unixFile *pFile = (unixFile*)id;
26838   sem_t *pSem = pFile->pInode->pSem;
26839
26840   assert( pFile );
26841   assert( pSem );
26842   OSTRACE(("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
26843            pFile->eFileLock, getpid()));
26844   assert( eFileLock<=SHARED_LOCK );
26845   
26846   /* no-op if possible */
26847   if( pFile->eFileLock==eFileLock ){
26848     return SQLITE_OK;
26849   }
26850   
26851   /* shared can just be set because we always have an exclusive */
26852   if (eFileLock==SHARED_LOCK) {
26853     pFile->eFileLock = eFileLock;
26854     return SQLITE_OK;
26855   }
26856   
26857   /* no, really unlock. */
26858   if ( sem_post(pSem)==-1 ) {
26859     int rc, tErrno = errno;
26860     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
26861     if( IS_LOCK_ERROR(rc) ){
26862       pFile->lastErrno = tErrno;
26863     }
26864     return rc; 
26865   }
26866   pFile->eFileLock = NO_LOCK;
26867   return SQLITE_OK;
26868 }
26869
26870 /*
26871  ** Close a file.
26872  */
26873 static int semClose(sqlite3_file *id) {
26874   if( id ){
26875     unixFile *pFile = (unixFile*)id;
26876     semUnlock(id, NO_LOCK);
26877     assert( pFile );
26878     unixEnterMutex();
26879     releaseInodeInfo(pFile);
26880     unixLeaveMutex();
26881     closeUnixFile(id);
26882   }
26883   return SQLITE_OK;
26884 }
26885
26886 #endif /* OS_VXWORKS */
26887 /*
26888 ** Named semaphore locking is only available on VxWorks.
26889 **
26890 *************** End of the named semaphore lock implementation ****************
26891 ******************************************************************************/
26892
26893
26894 /******************************************************************************
26895 *************************** Begin AFP Locking *********************************
26896 **
26897 ** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
26898 ** on Apple Macintosh computers - both OS9 and OSX.
26899 **
26900 ** Third-party implementations of AFP are available.  But this code here
26901 ** only works on OSX.
26902 */
26903
26904 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26905 /*
26906 ** The afpLockingContext structure contains all afp lock specific state
26907 */
26908 typedef struct afpLockingContext afpLockingContext;
26909 struct afpLockingContext {
26910   int reserved;
26911   const char *dbPath;             /* Name of the open file */
26912 };
26913
26914 struct ByteRangeLockPB2
26915 {
26916   unsigned long long offset;        /* offset to first byte to lock */
26917   unsigned long long length;        /* nbr of bytes to lock */
26918   unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
26919   unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
26920   unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
26921   int fd;                           /* file desc to assoc this lock with */
26922 };
26923
26924 #define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
26925
26926 /*
26927 ** This is a utility for setting or clearing a bit-range lock on an
26928 ** AFP filesystem.
26929 ** 
26930 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
26931 */
26932 static int afpSetLock(
26933   const char *path,              /* Name of the file to be locked or unlocked */
26934   unixFile *pFile,               /* Open file descriptor on path */
26935   unsigned long long offset,     /* First byte to be locked */
26936   unsigned long long length,     /* Number of bytes to lock */
26937   int setLockFlag                /* True to set lock.  False to clear lock */
26938 ){
26939   struct ByteRangeLockPB2 pb;
26940   int err;
26941   
26942   pb.unLockFlag = setLockFlag ? 0 : 1;
26943   pb.startEndFlag = 0;
26944   pb.offset = offset;
26945   pb.length = length; 
26946   pb.fd = pFile->h;
26947   
26948   OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n", 
26949     (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
26950     offset, length));
26951   err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
26952   if ( err==-1 ) {
26953     int rc;
26954     int tErrno = errno;
26955     OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
26956              path, tErrno, strerror(tErrno)));
26957 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
26958     rc = SQLITE_BUSY;
26959 #else
26960     rc = sqliteErrorFromPosixError(tErrno,
26961                     setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
26962 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
26963     if( IS_LOCK_ERROR(rc) ){
26964       pFile->lastErrno = tErrno;
26965     }
26966     return rc;
26967   } else {
26968     return SQLITE_OK;
26969   }
26970 }
26971
26972 /*
26973 ** This routine checks if there is a RESERVED lock held on the specified
26974 ** file by this or any other process. If such a lock is held, set *pResOut
26975 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
26976 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26977 */
26978 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
26979   int rc = SQLITE_OK;
26980   int reserved = 0;
26981   unixFile *pFile = (unixFile*)id;
26982   
26983   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
26984   
26985   assert( pFile );
26986   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
26987   if( context->reserved ){
26988     *pResOut = 1;
26989     return SQLITE_OK;
26990   }
26991   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
26992   
26993   /* Check if a thread in this process holds such a lock */
26994   if( pFile->pInode->eFileLock>SHARED_LOCK ){
26995     reserved = 1;
26996   }
26997   
26998   /* Otherwise see if some other process holds it.
26999    */
27000   if( !reserved ){
27001     /* lock the RESERVED byte */
27002     int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);  
27003     if( SQLITE_OK==lrc ){
27004       /* if we succeeded in taking the reserved lock, unlock it to restore
27005       ** the original state */
27006       lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
27007     } else {
27008       /* if we failed to get the lock then someone else must have it */
27009       reserved = 1;
27010     }
27011     if( IS_LOCK_ERROR(lrc) ){
27012       rc=lrc;
27013     }
27014   }
27015   
27016   unixLeaveMutex();
27017   OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
27018   
27019   *pResOut = reserved;
27020   return rc;
27021 }
27022
27023 /*
27024 ** Lock the file with the lock specified by parameter eFileLock - one
27025 ** of the following:
27026 **
27027 **     (1) SHARED_LOCK
27028 **     (2) RESERVED_LOCK
27029 **     (3) PENDING_LOCK
27030 **     (4) EXCLUSIVE_LOCK
27031 **
27032 ** Sometimes when requesting one lock state, additional lock states
27033 ** are inserted in between.  The locking might fail on one of the later
27034 ** transitions leaving the lock state different from what it started but
27035 ** still short of its goal.  The following chart shows the allowed
27036 ** transitions and the inserted intermediate states:
27037 **
27038 **    UNLOCKED -> SHARED
27039 **    SHARED -> RESERVED
27040 **    SHARED -> (PENDING) -> EXCLUSIVE
27041 **    RESERVED -> (PENDING) -> EXCLUSIVE
27042 **    PENDING -> EXCLUSIVE
27043 **
27044 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
27045 ** routine to lower a locking level.
27046 */
27047 static int afpLock(sqlite3_file *id, int eFileLock){
27048   int rc = SQLITE_OK;
27049   unixFile *pFile = (unixFile*)id;
27050   unixInodeInfo *pInode = pFile->pInode;
27051   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
27052   
27053   assert( pFile );
27054   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
27055            azFileLock(eFileLock), azFileLock(pFile->eFileLock),
27056            azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
27057
27058   /* If there is already a lock of this type or more restrictive on the
27059   ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
27060   ** unixEnterMutex() hasn't been called yet.
27061   */
27062   if( pFile->eFileLock>=eFileLock ){
27063     OSTRACE(("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
27064            azFileLock(eFileLock)));
27065     return SQLITE_OK;
27066   }
27067
27068   /* Make sure the locking sequence is correct
27069   **  (1) We never move from unlocked to anything higher than shared lock.
27070   **  (2) SQLite never explicitly requests a pendig lock.
27071   **  (3) A shared lock is always held when a reserve lock is requested.
27072   */
27073   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
27074   assert( eFileLock!=PENDING_LOCK );
27075   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
27076   
27077   /* This mutex is needed because pFile->pInode is shared across threads
27078   */
27079   unixEnterMutex();
27080   pInode = pFile->pInode;
27081
27082   /* If some thread using this PID has a lock via a different unixFile*
27083   ** handle that precludes the requested lock, return BUSY.
27084   */
27085   if( (pFile->eFileLock!=pInode->eFileLock && 
27086        (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
27087      ){
27088     rc = SQLITE_BUSY;
27089     goto afp_end_lock;
27090   }
27091   
27092   /* If a SHARED lock is requested, and some thread using this PID already
27093   ** has a SHARED or RESERVED lock, then increment reference counts and
27094   ** return SQLITE_OK.
27095   */
27096   if( eFileLock==SHARED_LOCK && 
27097      (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
27098     assert( eFileLock==SHARED_LOCK );
27099     assert( pFile->eFileLock==0 );
27100     assert( pInode->nShared>0 );
27101     pFile->eFileLock = SHARED_LOCK;
27102     pInode->nShared++;
27103     pInode->nLock++;
27104     goto afp_end_lock;
27105   }
27106     
27107   /* A PENDING lock is needed before acquiring a SHARED lock and before
27108   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
27109   ** be released.
27110   */
27111   if( eFileLock==SHARED_LOCK 
27112       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
27113   ){
27114     int failed;
27115     failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
27116     if (failed) {
27117       rc = failed;
27118       goto afp_end_lock;
27119     }
27120   }
27121   
27122   /* If control gets to this point, then actually go ahead and make
27123   ** operating system calls for the specified lock.
27124   */
27125   if( eFileLock==SHARED_LOCK ){
27126     int lrc1, lrc2, lrc1Errno;
27127     long lk, mask;
27128     
27129     assert( pInode->nShared==0 );
27130     assert( pInode->eFileLock==0 );
27131         
27132     mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
27133     /* Now get the read-lock SHARED_LOCK */
27134     /* note that the quality of the randomness doesn't matter that much */
27135     lk = random(); 
27136     pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
27137     lrc1 = afpSetLock(context->dbPath, pFile, 
27138           SHARED_FIRST+pInode->sharedByte, 1, 1);
27139     if( IS_LOCK_ERROR(lrc1) ){
27140       lrc1Errno = pFile->lastErrno;
27141     }
27142     /* Drop the temporary PENDING lock */
27143     lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
27144     
27145     if( IS_LOCK_ERROR(lrc1) ) {
27146       pFile->lastErrno = lrc1Errno;
27147       rc = lrc1;
27148       goto afp_end_lock;
27149     } else if( IS_LOCK_ERROR(lrc2) ){
27150       rc = lrc2;
27151       goto afp_end_lock;
27152     } else if( lrc1 != SQLITE_OK ) {
27153       rc = lrc1;
27154     } else {
27155       pFile->eFileLock = SHARED_LOCK;
27156       pInode->nLock++;
27157       pInode->nShared = 1;
27158     }
27159   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
27160     /* We are trying for an exclusive lock but another thread in this
27161      ** same process is still holding a shared lock. */
27162     rc = SQLITE_BUSY;
27163   }else{
27164     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
27165     ** assumed that there is a SHARED or greater lock on the file
27166     ** already.
27167     */
27168     int failed = 0;
27169     assert( 0!=pFile->eFileLock );
27170     if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
27171         /* Acquire a RESERVED lock */
27172         failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
27173       if( !failed ){
27174         context->reserved = 1;
27175       }
27176     }
27177     if (!failed && eFileLock == EXCLUSIVE_LOCK) {
27178       /* Acquire an EXCLUSIVE lock */
27179         
27180       /* Remove the shared lock before trying the range.  we'll need to 
27181       ** reestablish the shared lock if we can't get the  afpUnlock
27182       */
27183       if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
27184                          pInode->sharedByte, 1, 0)) ){
27185         int failed2 = SQLITE_OK;
27186         /* now attemmpt to get the exclusive lock range */
27187         failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST, 
27188                                SHARED_SIZE, 1);
27189         if( failed && (failed2 = afpSetLock(context->dbPath, pFile, 
27190                        SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
27191           /* Can't reestablish the shared lock.  Sqlite can't deal, this is
27192           ** a critical I/O error
27193           */
27194           rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 : 
27195                SQLITE_IOERR_LOCK;
27196           goto afp_end_lock;
27197         } 
27198       }else{
27199         rc = failed; 
27200       }
27201     }
27202     if( failed ){
27203       rc = failed;
27204     }
27205   }
27206   
27207   if( rc==SQLITE_OK ){
27208     pFile->eFileLock = eFileLock;
27209     pInode->eFileLock = eFileLock;
27210   }else if( eFileLock==EXCLUSIVE_LOCK ){
27211     pFile->eFileLock = PENDING_LOCK;
27212     pInode->eFileLock = PENDING_LOCK;
27213   }
27214   
27215 afp_end_lock:
27216   unixLeaveMutex();
27217   OSTRACE(("LOCK    %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock), 
27218          rc==SQLITE_OK ? "ok" : "failed"));
27219   return rc;
27220 }
27221
27222 /*
27223 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
27224 ** must be either NO_LOCK or SHARED_LOCK.
27225 **
27226 ** If the locking level of the file descriptor is already at or below
27227 ** the requested locking level, this routine is a no-op.
27228 */
27229 static int afpUnlock(sqlite3_file *id, int eFileLock) {
27230   int rc = SQLITE_OK;
27231   unixFile *pFile = (unixFile*)id;
27232   unixInodeInfo *pInode;
27233   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
27234   int skipShared = 0;
27235 #ifdef SQLITE_TEST
27236   int h = pFile->h;
27237 #endif
27238
27239   assert( pFile );
27240   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
27241            pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
27242            getpid()));
27243
27244   assert( eFileLock<=SHARED_LOCK );
27245   if( pFile->eFileLock<=eFileLock ){
27246     return SQLITE_OK;
27247   }
27248   unixEnterMutex();
27249   pInode = pFile->pInode;
27250   assert( pInode->nShared!=0 );
27251   if( pFile->eFileLock>SHARED_LOCK ){
27252     assert( pInode->eFileLock==pFile->eFileLock );
27253     SimulateIOErrorBenign(1);
27254     SimulateIOError( h=(-1) )
27255     SimulateIOErrorBenign(0);
27256     
27257 #ifndef NDEBUG
27258     /* When reducing a lock such that other processes can start
27259     ** reading the database file again, make sure that the
27260     ** transaction counter was updated if any part of the database
27261     ** file changed.  If the transaction counter is not updated,
27262     ** other connections to the same file might not realize that
27263     ** the file has changed and hence might not know to flush their
27264     ** cache.  The use of a stale cache can lead to database corruption.
27265     */
27266     assert( pFile->inNormalWrite==0
27267            || pFile->dbUpdate==0
27268            || pFile->transCntrChng==1 );
27269     pFile->inNormalWrite = 0;
27270 #endif
27271     
27272     if( pFile->eFileLock==EXCLUSIVE_LOCK ){
27273       rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
27274       if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
27275         /* only re-establish the shared lock if necessary */
27276         int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
27277         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
27278       } else {
27279         skipShared = 1;
27280       }
27281     }
27282     if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
27283       rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
27284     } 
27285     if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
27286       rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
27287       if( !rc ){ 
27288         context->reserved = 0; 
27289       }
27290     }
27291     if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
27292       pInode->eFileLock = SHARED_LOCK;
27293     }
27294   }
27295   if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
27296
27297     /* Decrement the shared lock counter.  Release the lock using an
27298     ** OS call only when all threads in this same process have released
27299     ** the lock.
27300     */
27301     unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
27302     pInode->nShared--;
27303     if( pInode->nShared==0 ){
27304       SimulateIOErrorBenign(1);
27305       SimulateIOError( h=(-1) )
27306       SimulateIOErrorBenign(0);
27307       if( !skipShared ){
27308         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
27309       }
27310       if( !rc ){
27311         pInode->eFileLock = NO_LOCK;
27312         pFile->eFileLock = NO_LOCK;
27313       }
27314     }
27315     if( rc==SQLITE_OK ){
27316       pInode->nLock--;
27317       assert( pInode->nLock>=0 );
27318       if( pInode->nLock==0 ){
27319         closePendingFds(pFile);
27320       }
27321     }
27322   }
27323   
27324   unixLeaveMutex();
27325   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
27326   return rc;
27327 }
27328
27329 /*
27330 ** Close a file & cleanup AFP specific locking context 
27331 */
27332 static int afpClose(sqlite3_file *id) {
27333   int rc = SQLITE_OK;
27334   if( id ){
27335     unixFile *pFile = (unixFile*)id;
27336     afpUnlock(id, NO_LOCK);
27337     unixEnterMutex();
27338     if( pFile->pInode && pFile->pInode->nLock ){
27339       /* If there are outstanding locks, do not actually close the file just
27340       ** yet because that would clear those locks.  Instead, add the file
27341       ** descriptor to pInode->aPending.  It will be automatically closed when
27342       ** the last lock is cleared.
27343       */
27344       setPendingFd(pFile);
27345     }
27346     releaseInodeInfo(pFile);
27347     sqlite3_free(pFile->lockingContext);
27348     rc = closeUnixFile(id);
27349     unixLeaveMutex();
27350   }
27351   return rc;
27352 }
27353
27354 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
27355 /*
27356 ** The code above is the AFP lock implementation.  The code is specific
27357 ** to MacOSX and does not work on other unix platforms.  No alternative
27358 ** is available.  If you don't compile for a mac, then the "unix-afp"
27359 ** VFS is not available.
27360 **
27361 ********************* End of the AFP lock implementation **********************
27362 ******************************************************************************/
27363
27364 /******************************************************************************
27365 *************************** Begin NFS Locking ********************************/
27366
27367 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27368 /*
27369  ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
27370  ** must be either NO_LOCK or SHARED_LOCK.
27371  **
27372  ** If the locking level of the file descriptor is already at or below
27373  ** the requested locking level, this routine is a no-op.
27374  */
27375 static int nfsUnlock(sqlite3_file *id, int eFileLock){
27376   return posixUnlock(id, eFileLock, 1);
27377 }
27378
27379 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
27380 /*
27381 ** The code above is the NFS lock implementation.  The code is specific
27382 ** to MacOSX and does not work on other unix platforms.  No alternative
27383 ** is available.  
27384 **
27385 ********************* End of the NFS lock implementation **********************
27386 ******************************************************************************/
27387
27388 /******************************************************************************
27389 **************** Non-locking sqlite3_file methods *****************************
27390 **
27391 ** The next division contains implementations for all methods of the 
27392 ** sqlite3_file object other than the locking methods.  The locking
27393 ** methods were defined in divisions above (one locking method per
27394 ** division).  Those methods that are common to all locking modes
27395 ** are gather together into this division.
27396 */
27397
27398 /*
27399 ** Seek to the offset passed as the second argument, then read cnt 
27400 ** bytes into pBuf. Return the number of bytes actually read.
27401 **
27402 ** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
27403 ** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
27404 ** one system to another.  Since SQLite does not define USE_PREAD
27405 ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
27406 ** See tickets #2741 and #2681.
27407 **
27408 ** To avoid stomping the errno value on a failed read the lastErrno value
27409 ** is set before returning.
27410 */
27411 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
27412   int got;
27413 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
27414   i64 newOffset;
27415 #endif
27416   TIMER_START;
27417 #if defined(USE_PREAD)
27418   do{ got = osPread(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
27419   SimulateIOError( got = -1 );
27420 #elif defined(USE_PREAD64)
27421   do{ got = osPread64(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR);
27422   SimulateIOError( got = -1 );
27423 #else
27424   newOffset = lseek(id->h, offset, SEEK_SET);
27425   SimulateIOError( newOffset-- );
27426   if( newOffset!=offset ){
27427     if( newOffset == -1 ){
27428       ((unixFile*)id)->lastErrno = errno;
27429     }else{
27430       ((unixFile*)id)->lastErrno = 0;                   
27431     }
27432     return -1;
27433   }
27434   do{ got = osRead(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
27435 #endif
27436   TIMER_END;
27437   if( got<0 ){
27438     ((unixFile*)id)->lastErrno = errno;
27439   }
27440   OSTRACE(("READ    %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
27441   return got;
27442 }
27443
27444 /*
27445 ** Read data from a file into a buffer.  Return SQLITE_OK if all
27446 ** bytes were read successfully and SQLITE_IOERR if anything goes
27447 ** wrong.
27448 */
27449 static int unixRead(
27450   sqlite3_file *id, 
27451   void *pBuf, 
27452   int amt,
27453   sqlite3_int64 offset
27454 ){
27455   unixFile *pFile = (unixFile *)id;
27456   int got;
27457   assert( id );
27458
27459   /* If this is a database file (not a journal, master-journal or temp
27460   ** file), the bytes in the locking range should never be read or written. */
27461 #if 0
27462   assert( pFile->pUnused==0
27463        || offset>=PENDING_BYTE+512
27464        || offset+amt<=PENDING_BYTE 
27465   );
27466 #endif
27467
27468   got = seekAndRead(pFile, offset, pBuf, amt);
27469   if( got==amt ){
27470     return SQLITE_OK;
27471   }else if( got<0 ){
27472     /* lastErrno set by seekAndRead */
27473     return SQLITE_IOERR_READ;
27474   }else{
27475     pFile->lastErrno = 0; /* not a system error */
27476     /* Unread parts of the buffer must be zero-filled */
27477     memset(&((char*)pBuf)[got], 0, amt-got);
27478     return SQLITE_IOERR_SHORT_READ;
27479   }
27480 }
27481
27482 /*
27483 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
27484 ** Return the number of bytes actually read.  Update the offset.
27485 **
27486 ** To avoid stomping the errno value on a failed write the lastErrno value
27487 ** is set before returning.
27488 */
27489 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
27490   int got;
27491 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
27492   i64 newOffset;
27493 #endif
27494   TIMER_START;
27495 #if defined(USE_PREAD)
27496   do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
27497 #elif defined(USE_PREAD64)
27498   do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
27499 #else
27500   newOffset = lseek(id->h, offset, SEEK_SET);
27501   SimulateIOError( newOffset-- );
27502   if( newOffset!=offset ){
27503     if( newOffset == -1 ){
27504       ((unixFile*)id)->lastErrno = errno;
27505     }else{
27506       ((unixFile*)id)->lastErrno = 0;                   
27507     }
27508     return -1;
27509   }
27510   do{ got = osWrite(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
27511 #endif
27512   TIMER_END;
27513   if( got<0 ){
27514     ((unixFile*)id)->lastErrno = errno;
27515   }
27516
27517   OSTRACE(("WRITE   %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
27518   return got;
27519 }
27520
27521
27522 /*
27523 ** Write data from a buffer into a file.  Return SQLITE_OK on success
27524 ** or some other error code on failure.
27525 */
27526 static int unixWrite(
27527   sqlite3_file *id, 
27528   const void *pBuf, 
27529   int amt,
27530   sqlite3_int64 offset 
27531 ){
27532   unixFile *pFile = (unixFile*)id;
27533   int wrote = 0;
27534   assert( id );
27535   assert( amt>0 );
27536
27537   /* If this is a database file (not a journal, master-journal or temp
27538   ** file), the bytes in the locking range should never be read or written. */
27539 #if 0
27540   assert( pFile->pUnused==0
27541        || offset>=PENDING_BYTE+512
27542        || offset+amt<=PENDING_BYTE 
27543   );
27544 #endif
27545
27546 #ifndef NDEBUG
27547   /* If we are doing a normal write to a database file (as opposed to
27548   ** doing a hot-journal rollback or a write to some file other than a
27549   ** normal database file) then record the fact that the database
27550   ** has changed.  If the transaction counter is modified, record that
27551   ** fact too.
27552   */
27553   if( pFile->inNormalWrite ){
27554     pFile->dbUpdate = 1;  /* The database has been modified */
27555     if( offset<=24 && offset+amt>=27 ){
27556       int rc;
27557       char oldCntr[4];
27558       SimulateIOErrorBenign(1);
27559       rc = seekAndRead(pFile, 24, oldCntr, 4);
27560       SimulateIOErrorBenign(0);
27561       if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
27562         pFile->transCntrChng = 1;  /* The transaction counter has changed */
27563       }
27564     }
27565   }
27566 #endif
27567
27568   while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
27569     amt -= wrote;
27570     offset += wrote;
27571     pBuf = &((char*)pBuf)[wrote];
27572   }
27573   SimulateIOError(( wrote=(-1), amt=1 ));
27574   SimulateDiskfullError(( wrote=0, amt=1 ));
27575
27576   if( amt>0 ){
27577     if( wrote<0 && pFile->lastErrno!=ENOSPC ){
27578       /* lastErrno set by seekAndWrite */
27579       return SQLITE_IOERR_WRITE;
27580     }else{
27581       pFile->lastErrno = 0; /* not a system error */
27582       return SQLITE_FULL;
27583     }
27584   }
27585
27586   return SQLITE_OK;
27587 }
27588
27589 #ifdef SQLITE_TEST
27590 /*
27591 ** Count the number of fullsyncs and normal syncs.  This is used to test
27592 ** that syncs and fullsyncs are occurring at the right times.
27593 */
27594 SQLITE_API int sqlite3_sync_count = 0;
27595 SQLITE_API int sqlite3_fullsync_count = 0;
27596 #endif
27597
27598 /*
27599 ** We do not trust systems to provide a working fdatasync().  Some do.
27600 ** Others do no.  To be safe, we will stick with the (slower) fsync().
27601 ** If you know that your system does support fdatasync() correctly,
27602 ** then simply compile with -Dfdatasync=fdatasync
27603 */
27604 #if !defined(fdatasync) && !defined(__linux__)
27605 # define fdatasync fsync
27606 #endif
27607
27608 /*
27609 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
27610 ** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
27611 ** only available on Mac OS X.  But that could change.
27612 */
27613 #ifdef F_FULLFSYNC
27614 # define HAVE_FULLFSYNC 1
27615 #else
27616 # define HAVE_FULLFSYNC 0
27617 #endif
27618
27619
27620 /*
27621 ** The fsync() system call does not work as advertised on many
27622 ** unix systems.  The following procedure is an attempt to make
27623 ** it work better.
27624 **
27625 ** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
27626 ** for testing when we want to run through the test suite quickly.
27627 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
27628 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
27629 ** or power failure will likely corrupt the database file.
27630 **
27631 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
27632 ** The idea behind dataOnly is that it should only write the file content
27633 ** to disk, not the inode.  We only set dataOnly if the file size is 
27634 ** unchanged since the file size is part of the inode.  However, 
27635 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
27636 ** file size has changed.  The only real difference between fdatasync()
27637 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
27638 ** inode if the mtime or owner or other inode attributes have changed.
27639 ** We only care about the file size, not the other file attributes, so
27640 ** as far as SQLite is concerned, an fdatasync() is always adequate.
27641 ** So, we always use fdatasync() if it is available, regardless of
27642 ** the value of the dataOnly flag.
27643 */
27644 static int full_fsync(int fd, int fullSync, int dataOnly){
27645   int rc;
27646
27647   /* The following "ifdef/elif/else/" block has the same structure as
27648   ** the one below. It is replicated here solely to avoid cluttering 
27649   ** up the real code with the UNUSED_PARAMETER() macros.
27650   */
27651 #ifdef SQLITE_NO_SYNC
27652   UNUSED_PARAMETER(fd);
27653   UNUSED_PARAMETER(fullSync);
27654   UNUSED_PARAMETER(dataOnly);
27655 #elif HAVE_FULLFSYNC
27656   UNUSED_PARAMETER(dataOnly);
27657 #else
27658   UNUSED_PARAMETER(fullSync);
27659   UNUSED_PARAMETER(dataOnly);
27660 #endif
27661
27662   /* Record the number of times that we do a normal fsync() and 
27663   ** FULLSYNC.  This is used during testing to verify that this procedure
27664   ** gets called with the correct arguments.
27665   */
27666 #ifdef SQLITE_TEST
27667   if( fullSync ) sqlite3_fullsync_count++;
27668   sqlite3_sync_count++;
27669 #endif
27670
27671   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
27672   ** no-op
27673   */
27674 #ifdef SQLITE_NO_SYNC
27675   rc = SQLITE_OK;
27676 #elif HAVE_FULLFSYNC
27677   if( fullSync ){
27678     rc = osFcntl(fd, F_FULLFSYNC, 0);
27679   }else{
27680     rc = 1;
27681   }
27682   /* If the FULLFSYNC failed, fall back to attempting an fsync().
27683   ** It shouldn't be possible for fullfsync to fail on the local 
27684   ** file system (on OSX), so failure indicates that FULLFSYNC
27685   ** isn't supported for this file system. So, attempt an fsync 
27686   ** and (for now) ignore the overhead of a superfluous fcntl call.  
27687   ** It'd be better to detect fullfsync support once and avoid 
27688   ** the fcntl call every time sync is called.
27689   */
27690   if( rc ) rc = fsync(fd);
27691
27692 #elif defined(__APPLE__)
27693   /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
27694   ** so currently we default to the macro that redefines fdatasync to fsync
27695   */
27696   rc = fsync(fd);
27697 #else 
27698   rc = fdatasync(fd);
27699 #if OS_VXWORKS
27700   if( rc==-1 && errno==ENOTSUP ){
27701     rc = fsync(fd);
27702   }
27703 #endif /* OS_VXWORKS */
27704 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
27705
27706   if( OS_VXWORKS && rc!= -1 ){
27707     rc = 0;
27708   }
27709   return rc;
27710 }
27711
27712 /*
27713 ** Make sure all writes to a particular file are committed to disk.
27714 **
27715 ** If dataOnly==0 then both the file itself and its metadata (file
27716 ** size, access time, etc) are synced.  If dataOnly!=0 then only the
27717 ** file data is synced.
27718 **
27719 ** Under Unix, also make sure that the directory entry for the file
27720 ** has been created by fsync-ing the directory that contains the file.
27721 ** If we do not do this and we encounter a power failure, the directory
27722 ** entry for the journal might not exist after we reboot.  The next
27723 ** SQLite to access the file will not know that the journal exists (because
27724 ** the directory entry for the journal was never created) and the transaction
27725 ** will not roll back - possibly leading to database corruption.
27726 */
27727 static int unixSync(sqlite3_file *id, int flags){
27728   int rc;
27729   unixFile *pFile = (unixFile*)id;
27730
27731   int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
27732   int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
27733
27734   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
27735   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
27736       || (flags&0x0F)==SQLITE_SYNC_FULL
27737   );
27738
27739   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
27740   ** line is to test that doing so does not cause any problems.
27741   */
27742   SimulateDiskfullError( return SQLITE_FULL );
27743
27744   assert( pFile );
27745   OSTRACE(("SYNC    %-3d\n", pFile->h));
27746   rc = full_fsync(pFile->h, isFullsync, isDataOnly);
27747   SimulateIOError( rc=1 );
27748   if( rc ){
27749     pFile->lastErrno = errno;
27750     return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
27751   }
27752   if( pFile->dirfd>=0 ){
27753     OSTRACE(("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
27754             HAVE_FULLFSYNC, isFullsync));
27755 #ifndef SQLITE_DISABLE_DIRSYNC
27756     /* The directory sync is only attempted if full_fsync is
27757     ** turned off or unavailable.  If a full_fsync occurred above,
27758     ** then the directory sync is superfluous.
27759     */
27760     if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
27761        /*
27762        ** We have received multiple reports of fsync() returning
27763        ** errors when applied to directories on certain file systems.
27764        ** A failed directory sync is not a big deal.  So it seems
27765        ** better to ignore the error.  Ticket #1657
27766        */
27767        /* pFile->lastErrno = errno; */
27768        /* return SQLITE_IOERR; */
27769     }
27770 #endif
27771     /* Only need to sync once, so close the  directory when we are done */
27772     robust_close(pFile, pFile->dirfd, __LINE__);
27773     pFile->dirfd = -1;
27774   }
27775   return rc;
27776 }
27777
27778 /*
27779 ** Truncate an open file to a specified size
27780 */
27781 static int unixTruncate(sqlite3_file *id, i64 nByte){
27782   unixFile *pFile = (unixFile *)id;
27783   int rc;
27784   assert( pFile );
27785   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
27786
27787   /* If the user has configured a chunk-size for this file, truncate the
27788   ** file so that it consists of an integer number of chunks (i.e. the
27789   ** actual file size after the operation may be larger than the requested
27790   ** size).
27791   */
27792   if( pFile->szChunk ){
27793     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
27794   }
27795
27796   rc = robust_ftruncate(pFile->h, (off_t)nByte);
27797   if( rc ){
27798     pFile->lastErrno = errno;
27799     return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
27800   }else{
27801 #ifndef NDEBUG
27802     /* If we are doing a normal write to a database file (as opposed to
27803     ** doing a hot-journal rollback or a write to some file other than a
27804     ** normal database file) and we truncate the file to zero length,
27805     ** that effectively updates the change counter.  This might happen
27806     ** when restoring a database using the backup API from a zero-length
27807     ** source.
27808     */
27809     if( pFile->inNormalWrite && nByte==0 ){
27810       pFile->transCntrChng = 1;
27811     }
27812 #endif
27813
27814     return SQLITE_OK;
27815   }
27816 }
27817
27818 /*
27819 ** Determine the current size of a file in bytes
27820 */
27821 static int unixFileSize(sqlite3_file *id, i64 *pSize){
27822   int rc;
27823   struct stat buf;
27824   assert( id );
27825   rc = osFstat(((unixFile*)id)->h, &buf);
27826   SimulateIOError( rc=1 );
27827   if( rc!=0 ){
27828     ((unixFile*)id)->lastErrno = errno;
27829     return SQLITE_IOERR_FSTAT;
27830   }
27831   *pSize = buf.st_size;
27832
27833   /* When opening a zero-size database, the findInodeInfo() procedure
27834   ** writes a single byte into that file in order to work around a bug
27835   ** in the OS-X msdos filesystem.  In order to avoid problems with upper
27836   ** layers, we need to report this file size as zero even though it is
27837   ** really 1.   Ticket #3260.
27838   */
27839   if( *pSize==1 ) *pSize = 0;
27840
27841
27842   return SQLITE_OK;
27843 }
27844
27845 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
27846 /*
27847 ** Handler for proxy-locking file-control verbs.  Defined below in the
27848 ** proxying locking division.
27849 */
27850 static int proxyFileControl(sqlite3_file*,int,void*);
27851 #endif
27852
27853 /* 
27854 ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT 
27855 ** file-control operation.
27856 **
27857 ** If the user has configured a chunk-size for this file, it could be
27858 ** that the file needs to be extended at this point. Otherwise, the
27859 ** SQLITE_FCNTL_SIZE_HINT operation is a no-op for Unix.
27860 */
27861 static int fcntlSizeHint(unixFile *pFile, i64 nByte){
27862   if( pFile->szChunk ){
27863     i64 nSize;                    /* Required file size */
27864     struct stat buf;              /* Used to hold return values of fstat() */
27865    
27866     if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
27867
27868     nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
27869     if( nSize>(i64)buf.st_size ){
27870
27871 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
27872       /* The code below is handling the return value of osFallocate() 
27873       ** correctly. posix_fallocate() is defined to "returns zero on success, 
27874       ** or an error number on  failure". See the manpage for details. */
27875       int err;
27876       do{
27877         err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
27878       }while( err==EINTR );
27879       if( err ) return SQLITE_IOERR_WRITE;
27880 #else
27881       /* If the OS does not have posix_fallocate(), fake it. First use
27882       ** ftruncate() to set the file size, then write a single byte to
27883       ** the last byte in each block within the extended region. This
27884       ** is the same technique used by glibc to implement posix_fallocate()
27885       ** on systems that do not have a real fallocate() system call.
27886       */
27887       int nBlk = buf.st_blksize;  /* File-system block size */
27888       i64 iWrite;                 /* Next offset to write to */
27889
27890       if( robust_ftruncate(pFile->h, nSize) ){
27891         pFile->lastErrno = errno;
27892         return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
27893       }
27894       iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
27895       while( iWrite<nSize ){
27896         int nWrite = seekAndWrite(pFile, iWrite, "", 1);
27897         if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
27898         iWrite += nBlk;
27899       }
27900 #endif
27901     }
27902   }
27903
27904   return SQLITE_OK;
27905 }
27906
27907 /*
27908 ** Information and control of an open file handle.
27909 */
27910 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
27911   switch( op ){
27912     case SQLITE_FCNTL_LOCKSTATE: {
27913       *(int*)pArg = ((unixFile*)id)->eFileLock;
27914       return SQLITE_OK;
27915     }
27916     case SQLITE_LAST_ERRNO: {
27917       *(int*)pArg = ((unixFile*)id)->lastErrno;
27918       return SQLITE_OK;
27919     }
27920     case SQLITE_FCNTL_CHUNK_SIZE: {
27921       ((unixFile*)id)->szChunk = *(int *)pArg;
27922       return SQLITE_OK;
27923     }
27924     case SQLITE_FCNTL_SIZE_HINT: {
27925       return fcntlSizeHint((unixFile *)id, *(i64 *)pArg);
27926     }
27927 #ifndef NDEBUG
27928     /* The pager calls this method to signal that it has done
27929     ** a rollback and that the database is therefore unchanged and
27930     ** it hence it is OK for the transaction change counter to be
27931     ** unchanged.
27932     */
27933     case SQLITE_FCNTL_DB_UNCHANGED: {
27934       ((unixFile*)id)->dbUpdate = 0;
27935       return SQLITE_OK;
27936     }
27937 #endif
27938 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
27939     case SQLITE_SET_LOCKPROXYFILE:
27940     case SQLITE_GET_LOCKPROXYFILE: {
27941       return proxyFileControl(id,op,pArg);
27942     }
27943 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
27944     case SQLITE_FCNTL_SYNC_OMITTED: {
27945       return SQLITE_OK;  /* A no-op */
27946     }
27947   }
27948   return SQLITE_NOTFOUND;
27949 }
27950
27951 /*
27952 ** Return the sector size in bytes of the underlying block device for
27953 ** the specified file. This is almost always 512 bytes, but may be
27954 ** larger for some devices.
27955 **
27956 ** SQLite code assumes this function cannot fail. It also assumes that
27957 ** if two files are created in the same file-system directory (i.e.
27958 ** a database and its journal file) that the sector size will be the
27959 ** same for both.
27960 */
27961 static int unixSectorSize(sqlite3_file *NotUsed){
27962   UNUSED_PARAMETER(NotUsed);
27963   return SQLITE_DEFAULT_SECTOR_SIZE;
27964 }
27965
27966 /*
27967 ** Return the device characteristics for the file. This is always 0 for unix.
27968 */
27969 static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
27970   UNUSED_PARAMETER(NotUsed);
27971   return 0;
27972 }
27973
27974 #ifndef SQLITE_OMIT_WAL
27975
27976
27977 /*
27978 ** Object used to represent an shared memory buffer.  
27979 **
27980 ** When multiple threads all reference the same wal-index, each thread
27981 ** has its own unixShm object, but they all point to a single instance
27982 ** of this unixShmNode object.  In other words, each wal-index is opened
27983 ** only once per process.
27984 **
27985 ** Each unixShmNode object is connected to a single unixInodeInfo object.
27986 ** We could coalesce this object into unixInodeInfo, but that would mean
27987 ** every open file that does not use shared memory (in other words, most
27988 ** open files) would have to carry around this extra information.  So
27989 ** the unixInodeInfo object contains a pointer to this unixShmNode object
27990 ** and the unixShmNode object is created only when needed.
27991 **
27992 ** unixMutexHeld() must be true when creating or destroying
27993 ** this object or while reading or writing the following fields:
27994 **
27995 **      nRef
27996 **
27997 ** The following fields are read-only after the object is created:
27998 ** 
27999 **      fid
28000 **      zFilename
28001 **
28002 ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
28003 ** unixMutexHeld() is true when reading or writing any other field
28004 ** in this structure.
28005 */
28006 struct unixShmNode {
28007   unixInodeInfo *pInode;     /* unixInodeInfo that owns this SHM node */
28008   sqlite3_mutex *mutex;      /* Mutex to access this object */
28009   char *zFilename;           /* Name of the mmapped file */
28010   int h;                     /* Open file descriptor */
28011   int szRegion;              /* Size of shared-memory regions */
28012   u16 nRegion;               /* Size of array apRegion */
28013   u8 isReadonly;             /* True if read-only */
28014   char **apRegion;           /* Array of mapped shared-memory regions */
28015   int nRef;                  /* Number of unixShm objects pointing to this */
28016   unixShm *pFirst;           /* All unixShm objects pointing to this */
28017 #ifdef SQLITE_DEBUG
28018   u8 exclMask;               /* Mask of exclusive locks held */
28019   u8 sharedMask;             /* Mask of shared locks held */
28020   u8 nextShmId;              /* Next available unixShm.id value */
28021 #endif
28022 };
28023
28024 /*
28025 ** Structure used internally by this VFS to record the state of an
28026 ** open shared memory connection.
28027 **
28028 ** The following fields are initialized when this object is created and
28029 ** are read-only thereafter:
28030 **
28031 **    unixShm.pFile
28032 **    unixShm.id
28033 **
28034 ** All other fields are read/write.  The unixShm.pFile->mutex must be held
28035 ** while accessing any read/write fields.
28036 */
28037 struct unixShm {
28038   unixShmNode *pShmNode;     /* The underlying unixShmNode object */
28039   unixShm *pNext;            /* Next unixShm with the same unixShmNode */
28040   u8 hasMutex;               /* True if holding the unixShmNode mutex */
28041   u16 sharedMask;            /* Mask of shared locks held */
28042   u16 exclMask;              /* Mask of exclusive locks held */
28043 #ifdef SQLITE_DEBUG
28044   u8 id;                     /* Id of this connection within its unixShmNode */
28045 #endif
28046 };
28047
28048 /*
28049 ** Constants used for locking
28050 */
28051 #define UNIX_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)         /* first lock byte */
28052 #define UNIX_SHM_DMS    (UNIX_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
28053
28054 /*
28055 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
28056 **
28057 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
28058 ** otherwise.
28059 */
28060 static int unixShmSystemLock(
28061   unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
28062   int lockType,          /* F_UNLCK, F_RDLCK, or F_WRLCK */
28063   int ofst,              /* First byte of the locking range */
28064   int n                  /* Number of bytes to lock */
28065 ){
28066   struct flock f;       /* The posix advisory locking structure */
28067   int rc = SQLITE_OK;   /* Result code form fcntl() */
28068
28069   /* Access to the unixShmNode object is serialized by the caller */
28070   assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
28071
28072   /* Shared locks never span more than one byte */
28073   assert( n==1 || lockType!=F_RDLCK );
28074
28075   /* Locks are within range */
28076   assert( n>=1 && n<SQLITE_SHM_NLOCK );
28077
28078   if( pShmNode->h>=0 ){
28079     /* Initialize the locking parameters */
28080     memset(&f, 0, sizeof(f));
28081     f.l_type = lockType;
28082     f.l_whence = SEEK_SET;
28083     f.l_start = ofst;
28084     f.l_len = n;
28085
28086     rc = osFcntl(pShmNode->h, F_SETLK, &f);
28087     rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
28088   }
28089
28090   /* Update the global lock state and do debug tracing */
28091 #ifdef SQLITE_DEBUG
28092   { u16 mask;
28093   OSTRACE(("SHM-LOCK "));
28094   mask = (1<<(ofst+n)) - (1<<ofst);
28095   if( rc==SQLITE_OK ){
28096     if( lockType==F_UNLCK ){
28097       OSTRACE(("unlock %d ok", ofst));
28098       pShmNode->exclMask &= ~mask;
28099       pShmNode->sharedMask &= ~mask;
28100     }else if( lockType==F_RDLCK ){
28101       OSTRACE(("read-lock %d ok", ofst));
28102       pShmNode->exclMask &= ~mask;
28103       pShmNode->sharedMask |= mask;
28104     }else{
28105       assert( lockType==F_WRLCK );
28106       OSTRACE(("write-lock %d ok", ofst));
28107       pShmNode->exclMask |= mask;
28108       pShmNode->sharedMask &= ~mask;
28109     }
28110   }else{
28111     if( lockType==F_UNLCK ){
28112       OSTRACE(("unlock %d failed", ofst));
28113     }else if( lockType==F_RDLCK ){
28114       OSTRACE(("read-lock failed"));
28115     }else{
28116       assert( lockType==F_WRLCK );
28117       OSTRACE(("write-lock %d failed", ofst));
28118     }
28119   }
28120   OSTRACE((" - afterwards %03x,%03x\n",
28121            pShmNode->sharedMask, pShmNode->exclMask));
28122   }
28123 #endif
28124
28125   return rc;        
28126 }
28127
28128
28129 /*
28130 ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
28131 **
28132 ** This is not a VFS shared-memory method; it is a utility function called
28133 ** by VFS shared-memory methods.
28134 */
28135 static void unixShmPurge(unixFile *pFd){
28136   unixShmNode *p = pFd->pInode->pShmNode;
28137   assert( unixMutexHeld() );
28138   if( p && p->nRef==0 ){
28139     int i;
28140     assert( p->pInode==pFd->pInode );
28141     if( p->mutex ) sqlite3_mutex_free(p->mutex);
28142     for(i=0; i<p->nRegion; i++){
28143       if( p->h>=0 ){
28144         munmap(p->apRegion[i], p->szRegion);
28145       }else{
28146         sqlite3_free(p->apRegion[i]);
28147       }
28148     }
28149     sqlite3_free(p->apRegion);
28150     if( p->h>=0 ){
28151       robust_close(pFd, p->h, __LINE__);
28152       p->h = -1;
28153     }
28154     p->pInode->pShmNode = 0;
28155     sqlite3_free(p);
28156   }
28157 }
28158
28159 /*
28160 ** Open a shared-memory area associated with open database file pDbFd.  
28161 ** This particular implementation uses mmapped files.
28162 **
28163 ** The file used to implement shared-memory is in the same directory
28164 ** as the open database file and has the same name as the open database
28165 ** file with the "-shm" suffix added.  For example, if the database file
28166 ** is "/home/user1/config.db" then the file that is created and mmapped
28167 ** for shared memory will be called "/home/user1/config.db-shm".  
28168 **
28169 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
28170 ** some other tmpfs mount. But if a file in a different directory
28171 ** from the database file is used, then differing access permissions
28172 ** or a chroot() might cause two different processes on the same
28173 ** database to end up using different files for shared memory - 
28174 ** meaning that their memory would not really be shared - resulting
28175 ** in database corruption.  Nevertheless, this tmpfs file usage
28176 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
28177 ** or the equivalent.  The use of the SQLITE_SHM_DIRECTORY compile-time
28178 ** option results in an incompatible build of SQLite;  builds of SQLite
28179 ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
28180 ** same database file at the same time, database corruption will likely
28181 ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
28182 ** "unsupported" and may go away in a future SQLite release.
28183 **
28184 ** When opening a new shared-memory file, if no other instances of that
28185 ** file are currently open, in this process or in other processes, then
28186 ** the file must be truncated to zero length or have its header cleared.
28187 **
28188 ** If the original database file (pDbFd) is using the "unix-excl" VFS
28189 ** that means that an exclusive lock is held on the database file and
28190 ** that no other processes are able to read or write the database.  In
28191 ** that case, we do not really need shared memory.  No shared memory
28192 ** file is created.  The shared memory will be simulated with heap memory.
28193 */
28194 static int unixOpenSharedMemory(unixFile *pDbFd){
28195   struct unixShm *p = 0;          /* The connection to be opened */
28196   struct unixShmNode *pShmNode;   /* The underlying mmapped file */
28197   int rc;                         /* Result code */
28198   unixInodeInfo *pInode;          /* The inode of fd */
28199   char *zShmFilename;             /* Name of the file used for SHM */
28200   int nShmFilename;               /* Size of the SHM filename in bytes */
28201
28202   /* Allocate space for the new unixShm object. */
28203   p = sqlite3_malloc( sizeof(*p) );
28204   if( p==0 ) return SQLITE_NOMEM;
28205   memset(p, 0, sizeof(*p));
28206   assert( pDbFd->pShm==0 );
28207
28208   /* Check to see if a unixShmNode object already exists. Reuse an existing
28209   ** one if present. Create a new one if necessary.
28210   */
28211   unixEnterMutex();
28212   pInode = pDbFd->pInode;
28213   pShmNode = pInode->pShmNode;
28214   if( pShmNode==0 ){
28215     struct stat sStat;                 /* fstat() info for database file */
28216
28217     /* Call fstat() to figure out the permissions on the database file. If
28218     ** a new *-shm file is created, an attempt will be made to create it
28219     ** with the same permissions. The actual permissions the file is created
28220     ** with are subject to the current umask setting.
28221     */
28222     if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
28223       rc = SQLITE_IOERR_FSTAT;
28224       goto shm_open_err;
28225     }
28226
28227 #ifdef SQLITE_SHM_DIRECTORY
28228     nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 30;
28229 #else
28230     nShmFilename = 5 + (int)strlen(pDbFd->zPath);
28231 #endif
28232     pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
28233     if( pShmNode==0 ){
28234       rc = SQLITE_NOMEM;
28235       goto shm_open_err;
28236     }
28237     memset(pShmNode, 0, sizeof(*pShmNode));
28238     zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
28239 #ifdef SQLITE_SHM_DIRECTORY
28240     sqlite3_snprintf(nShmFilename, zShmFilename, 
28241                      SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
28242                      (u32)sStat.st_ino, (u32)sStat.st_dev);
28243 #else
28244     sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
28245     sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
28246 #endif
28247     pShmNode->h = -1;
28248     pDbFd->pInode->pShmNode = pShmNode;
28249     pShmNode->pInode = pDbFd->pInode;
28250     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
28251     if( pShmNode->mutex==0 ){
28252       rc = SQLITE_NOMEM;
28253       goto shm_open_err;
28254     }
28255
28256     if( pInode->bProcessLock==0 ){
28257       pShmNode->h = robust_open(zShmFilename, O_RDWR|O_CREAT,
28258                                (sStat.st_mode & 0777));
28259       if( pShmNode->h<0 ){
28260         const char *zRO;
28261         zRO = sqlite3_uri_parameter(pDbFd->zPath, "readonly_shm");
28262         if( zRO && sqlite3GetBoolean(zRO) ){
28263           pShmNode->h = robust_open(zShmFilename, O_RDONLY,
28264                                     (sStat.st_mode & 0777));
28265           pShmNode->isReadonly = 1;
28266         }
28267         if( pShmNode->h<0 ){
28268           rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
28269           goto shm_open_err;
28270         }
28271       }
28272   
28273       /* Check to see if another process is holding the dead-man switch.
28274       ** If not, truncate the file to zero length. 
28275       */
28276       rc = SQLITE_OK;
28277       if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
28278         if( robust_ftruncate(pShmNode->h, 0) ){
28279           rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
28280         }
28281       }
28282       if( rc==SQLITE_OK ){
28283         rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
28284       }
28285       if( rc ) goto shm_open_err;
28286     }
28287   }
28288
28289   /* Make the new connection a child of the unixShmNode */
28290   p->pShmNode = pShmNode;
28291 #ifdef SQLITE_DEBUG
28292   p->id = pShmNode->nextShmId++;
28293 #endif
28294   pShmNode->nRef++;
28295   pDbFd->pShm = p;
28296   unixLeaveMutex();
28297
28298   /* The reference count on pShmNode has already been incremented under
28299   ** the cover of the unixEnterMutex() mutex and the pointer from the
28300   ** new (struct unixShm) object to the pShmNode has been set. All that is
28301   ** left to do is to link the new object into the linked list starting
28302   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex 
28303   ** mutex.
28304   */
28305   sqlite3_mutex_enter(pShmNode->mutex);
28306   p->pNext = pShmNode->pFirst;
28307   pShmNode->pFirst = p;
28308   sqlite3_mutex_leave(pShmNode->mutex);
28309   return SQLITE_OK;
28310
28311   /* Jump here on any error */
28312 shm_open_err:
28313   unixShmPurge(pDbFd);       /* This call frees pShmNode if required */
28314   sqlite3_free(p);
28315   unixLeaveMutex();
28316   return rc;
28317 }
28318
28319 /*
28320 ** This function is called to obtain a pointer to region iRegion of the 
28321 ** shared-memory associated with the database file fd. Shared-memory regions 
28322 ** are numbered starting from zero. Each shared-memory region is szRegion 
28323 ** bytes in size.
28324 **
28325 ** If an error occurs, an error code is returned and *pp is set to NULL.
28326 **
28327 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
28328 ** region has not been allocated (by any client, including one running in a
28329 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If 
28330 ** bExtend is non-zero and the requested shared-memory region has not yet 
28331 ** been allocated, it is allocated by this function.
28332 **
28333 ** If the shared-memory region has already been allocated or is allocated by
28334 ** this call as described above, then it is mapped into this processes 
28335 ** address space (if it is not already), *pp is set to point to the mapped 
28336 ** memory and SQLITE_OK returned.
28337 */
28338 static int unixShmMap(
28339   sqlite3_file *fd,               /* Handle open on database file */
28340   int iRegion,                    /* Region to retrieve */
28341   int szRegion,                   /* Size of regions */
28342   int bExtend,                    /* True to extend file if necessary */
28343   void volatile **pp              /* OUT: Mapped memory */
28344 ){
28345   unixFile *pDbFd = (unixFile*)fd;
28346   unixShm *p;
28347   unixShmNode *pShmNode;
28348   int rc = SQLITE_OK;
28349
28350   /* If the shared-memory file has not yet been opened, open it now. */
28351   if( pDbFd->pShm==0 ){
28352     rc = unixOpenSharedMemory(pDbFd);
28353     if( rc!=SQLITE_OK ) return rc;
28354   }
28355
28356   p = pDbFd->pShm;
28357   pShmNode = p->pShmNode;
28358   sqlite3_mutex_enter(pShmNode->mutex);
28359   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
28360   assert( pShmNode->pInode==pDbFd->pInode );
28361   assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
28362   assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
28363
28364   if( pShmNode->nRegion<=iRegion ){
28365     char **apNew;                      /* New apRegion[] array */
28366     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
28367     struct stat sStat;                 /* Used by fstat() */
28368
28369     pShmNode->szRegion = szRegion;
28370
28371     if( pShmNode->h>=0 ){
28372       /* The requested region is not mapped into this processes address space.
28373       ** Check to see if it has been allocated (i.e. if the wal-index file is
28374       ** large enough to contain the requested region).
28375       */
28376       if( osFstat(pShmNode->h, &sStat) ){
28377         rc = SQLITE_IOERR_SHMSIZE;
28378         goto shmpage_out;
28379       }
28380   
28381       if( sStat.st_size<nByte ){
28382         /* The requested memory region does not exist. If bExtend is set to
28383         ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
28384         **
28385         ** Alternatively, if bExtend is true, use ftruncate() to allocate
28386         ** the requested memory region.
28387         */
28388         if( !bExtend ) goto shmpage_out;
28389         if( robust_ftruncate(pShmNode->h, nByte) ){
28390           rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
28391                             pShmNode->zFilename);
28392           goto shmpage_out;
28393         }
28394       }
28395     }
28396
28397     /* Map the requested memory region into this processes address space. */
28398     apNew = (char **)sqlite3_realloc(
28399         pShmNode->apRegion, (iRegion+1)*sizeof(char *)
28400     );
28401     if( !apNew ){
28402       rc = SQLITE_IOERR_NOMEM;
28403       goto shmpage_out;
28404     }
28405     pShmNode->apRegion = apNew;
28406     while(pShmNode->nRegion<=iRegion){
28407       void *pMem;
28408       if( pShmNode->h>=0 ){
28409         pMem = mmap(0, szRegion,
28410             pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE, 
28411             MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
28412         );
28413         if( pMem==MAP_FAILED ){
28414           rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
28415           goto shmpage_out;
28416         }
28417       }else{
28418         pMem = sqlite3_malloc(szRegion);
28419         if( pMem==0 ){
28420           rc = SQLITE_NOMEM;
28421           goto shmpage_out;
28422         }
28423         memset(pMem, 0, szRegion);
28424       }
28425       pShmNode->apRegion[pShmNode->nRegion] = pMem;
28426       pShmNode->nRegion++;
28427     }
28428   }
28429
28430 shmpage_out:
28431   if( pShmNode->nRegion>iRegion ){
28432     *pp = pShmNode->apRegion[iRegion];
28433   }else{
28434     *pp = 0;
28435   }
28436   if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
28437   sqlite3_mutex_leave(pShmNode->mutex);
28438   return rc;
28439 }
28440
28441 /*
28442 ** Change the lock state for a shared-memory segment.
28443 **
28444 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
28445 ** different here than in posix.  In xShmLock(), one can go from unlocked
28446 ** to shared and back or from unlocked to exclusive and back.  But one may
28447 ** not go from shared to exclusive or from exclusive to shared.
28448 */
28449 static int unixShmLock(
28450   sqlite3_file *fd,          /* Database file holding the shared memory */
28451   int ofst,                  /* First lock to acquire or release */
28452   int n,                     /* Number of locks to acquire or release */
28453   int flags                  /* What to do with the lock */
28454 ){
28455   unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */
28456   unixShm *p = pDbFd->pShm;             /* The shared memory being locked */
28457   unixShm *pX;                          /* For looping over all siblings */
28458   unixShmNode *pShmNode = p->pShmNode;  /* The underlying file iNode */
28459   int rc = SQLITE_OK;                   /* Result code */
28460   u16 mask;                             /* Mask of locks to take or release */
28461
28462   assert( pShmNode==pDbFd->pInode->pShmNode );
28463   assert( pShmNode->pInode==pDbFd->pInode );
28464   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
28465   assert( n>=1 );
28466   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
28467        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
28468        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
28469        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
28470   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
28471   assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
28472   assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
28473
28474   mask = (1<<(ofst+n)) - (1<<ofst);
28475   assert( n>1 || mask==(1<<ofst) );
28476   sqlite3_mutex_enter(pShmNode->mutex);
28477   if( flags & SQLITE_SHM_UNLOCK ){
28478     u16 allMask = 0; /* Mask of locks held by siblings */
28479
28480     /* See if any siblings hold this same lock */
28481     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
28482       if( pX==p ) continue;
28483       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
28484       allMask |= pX->sharedMask;
28485     }
28486
28487     /* Unlock the system-level locks */
28488     if( (mask & allMask)==0 ){
28489       rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
28490     }else{
28491       rc = SQLITE_OK;
28492     }
28493
28494     /* Undo the local locks */
28495     if( rc==SQLITE_OK ){
28496       p->exclMask &= ~mask;
28497       p->sharedMask &= ~mask;
28498     } 
28499   }else if( flags & SQLITE_SHM_SHARED ){
28500     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
28501
28502     /* Find out which shared locks are already held by sibling connections.
28503     ** If any sibling already holds an exclusive lock, go ahead and return
28504     ** SQLITE_BUSY.
28505     */
28506     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
28507       if( (pX->exclMask & mask)!=0 ){
28508         rc = SQLITE_BUSY;
28509         break;
28510       }
28511       allShared |= pX->sharedMask;
28512     }
28513
28514     /* Get shared locks at the system level, if necessary */
28515     if( rc==SQLITE_OK ){
28516       if( (allShared & mask)==0 ){
28517         rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
28518       }else{
28519         rc = SQLITE_OK;
28520       }
28521     }
28522
28523     /* Get the local shared locks */
28524     if( rc==SQLITE_OK ){
28525       p->sharedMask |= mask;
28526     }
28527   }else{
28528     /* Make sure no sibling connections hold locks that will block this
28529     ** lock.  If any do, return SQLITE_BUSY right away.
28530     */
28531     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
28532       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
28533         rc = SQLITE_BUSY;
28534         break;
28535       }
28536     }
28537   
28538     /* Get the exclusive locks at the system level.  Then if successful
28539     ** also mark the local connection as being locked.
28540     */
28541     if( rc==SQLITE_OK ){
28542       rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
28543       if( rc==SQLITE_OK ){
28544         assert( (p->sharedMask & mask)==0 );
28545         p->exclMask |= mask;
28546       }
28547     }
28548   }
28549   sqlite3_mutex_leave(pShmNode->mutex);
28550   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
28551            p->id, getpid(), p->sharedMask, p->exclMask));
28552   return rc;
28553 }
28554
28555 /*
28556 ** Implement a memory barrier or memory fence on shared memory.  
28557 **
28558 ** All loads and stores begun before the barrier must complete before
28559 ** any load or store begun after the barrier.
28560 */
28561 static void unixShmBarrier(
28562   sqlite3_file *fd                /* Database file holding the shared memory */
28563 ){
28564   UNUSED_PARAMETER(fd);
28565   unixEnterMutex();
28566   unixLeaveMutex();
28567 }
28568
28569 /*
28570 ** Close a connection to shared-memory.  Delete the underlying 
28571 ** storage if deleteFlag is true.
28572 **
28573 ** If there is no shared memory associated with the connection then this
28574 ** routine is a harmless no-op.
28575 */
28576 static int unixShmUnmap(
28577   sqlite3_file *fd,               /* The underlying database file */
28578   int deleteFlag                  /* Delete shared-memory if true */
28579 ){
28580   unixShm *p;                     /* The connection to be closed */
28581   unixShmNode *pShmNode;          /* The underlying shared-memory file */
28582   unixShm **pp;                   /* For looping over sibling connections */
28583   unixFile *pDbFd;                /* The underlying database file */
28584
28585   pDbFd = (unixFile*)fd;
28586   p = pDbFd->pShm;
28587   if( p==0 ) return SQLITE_OK;
28588   pShmNode = p->pShmNode;
28589
28590   assert( pShmNode==pDbFd->pInode->pShmNode );
28591   assert( pShmNode->pInode==pDbFd->pInode );
28592
28593   /* Remove connection p from the set of connections associated
28594   ** with pShmNode */
28595   sqlite3_mutex_enter(pShmNode->mutex);
28596   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
28597   *pp = p->pNext;
28598
28599   /* Free the connection p */
28600   sqlite3_free(p);
28601   pDbFd->pShm = 0;
28602   sqlite3_mutex_leave(pShmNode->mutex);
28603
28604   /* If pShmNode->nRef has reached 0, then close the underlying
28605   ** shared-memory file, too */
28606   unixEnterMutex();
28607   assert( pShmNode->nRef>0 );
28608   pShmNode->nRef--;
28609   if( pShmNode->nRef==0 ){
28610     if( deleteFlag && pShmNode->h>=0 ) unlink(pShmNode->zFilename);
28611     unixShmPurge(pDbFd);
28612   }
28613   unixLeaveMutex();
28614
28615   return SQLITE_OK;
28616 }
28617
28618
28619 #else
28620 # define unixShmMap     0
28621 # define unixShmLock    0
28622 # define unixShmBarrier 0
28623 # define unixShmUnmap   0
28624 #endif /* #ifndef SQLITE_OMIT_WAL */
28625
28626 /*
28627 ** Here ends the implementation of all sqlite3_file methods.
28628 **
28629 ********************** End sqlite3_file Methods *******************************
28630 ******************************************************************************/
28631
28632 /*
28633 ** This division contains definitions of sqlite3_io_methods objects that
28634 ** implement various file locking strategies.  It also contains definitions
28635 ** of "finder" functions.  A finder-function is used to locate the appropriate
28636 ** sqlite3_io_methods object for a particular database file.  The pAppData
28637 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
28638 ** the correct finder-function for that VFS.
28639 **
28640 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
28641 ** object.  The only interesting finder-function is autolockIoFinder, which
28642 ** looks at the filesystem type and tries to guess the best locking
28643 ** strategy from that.
28644 **
28645 ** For finder-funtion F, two objects are created:
28646 **
28647 **    (1) The real finder-function named "FImpt()".
28648 **
28649 **    (2) A constant pointer to this function named just "F".
28650 **
28651 **
28652 ** A pointer to the F pointer is used as the pAppData value for VFS
28653 ** objects.  We have to do this instead of letting pAppData point
28654 ** directly at the finder-function since C90 rules prevent a void*
28655 ** from be cast into a function pointer.
28656 **
28657 **
28658 ** Each instance of this macro generates two objects:
28659 **
28660 **   *  A constant sqlite3_io_methods object call METHOD that has locking
28661 **      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
28662 **
28663 **   *  An I/O method finder function called FINDER that returns a pointer
28664 **      to the METHOD object in the previous bullet.
28665 */
28666 #define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK)      \
28667 static const sqlite3_io_methods METHOD = {                                   \
28668    VERSION,                    /* iVersion */                                \
28669    CLOSE,                      /* xClose */                                  \
28670    unixRead,                   /* xRead */                                   \
28671    unixWrite,                  /* xWrite */                                  \
28672    unixTruncate,               /* xTruncate */                               \
28673    unixSync,                   /* xSync */                                   \
28674    unixFileSize,               /* xFileSize */                               \
28675    LOCK,                       /* xLock */                                   \
28676    UNLOCK,                     /* xUnlock */                                 \
28677    CKLOCK,                     /* xCheckReservedLock */                      \
28678    unixFileControl,            /* xFileControl */                            \
28679    unixSectorSize,             /* xSectorSize */                             \
28680    unixDeviceCharacteristics,  /* xDeviceCapabilities */                     \
28681    unixShmMap,                 /* xShmMap */                                 \
28682    unixShmLock,                /* xShmLock */                                \
28683    unixShmBarrier,             /* xShmBarrier */                             \
28684    unixShmUnmap                /* xShmUnmap */                               \
28685 };                                                                           \
28686 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
28687   UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
28688   return &METHOD;                                                            \
28689 }                                                                            \
28690 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
28691     = FINDER##Impl;
28692
28693 /*
28694 ** Here are all of the sqlite3_io_methods objects for each of the
28695 ** locking strategies.  Functions that return pointers to these methods
28696 ** are also created.
28697 */
28698 IOMETHODS(
28699   posixIoFinder,            /* Finder function name */
28700   posixIoMethods,           /* sqlite3_io_methods object name */
28701   2,                        /* shared memory is enabled */
28702   unixClose,                /* xClose method */
28703   unixLock,                 /* xLock method */
28704   unixUnlock,               /* xUnlock method */
28705   unixCheckReservedLock     /* xCheckReservedLock method */
28706 )
28707 IOMETHODS(
28708   nolockIoFinder,           /* Finder function name */
28709   nolockIoMethods,          /* sqlite3_io_methods object name */
28710   1,                        /* shared memory is disabled */
28711   nolockClose,              /* xClose method */
28712   nolockLock,               /* xLock method */
28713   nolockUnlock,             /* xUnlock method */
28714   nolockCheckReservedLock   /* xCheckReservedLock method */
28715 )
28716 IOMETHODS(
28717   dotlockIoFinder,          /* Finder function name */
28718   dotlockIoMethods,         /* sqlite3_io_methods object name */
28719   1,                        /* shared memory is disabled */
28720   dotlockClose,             /* xClose method */
28721   dotlockLock,              /* xLock method */
28722   dotlockUnlock,            /* xUnlock method */
28723   dotlockCheckReservedLock  /* xCheckReservedLock method */
28724 )
28725
28726 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
28727 IOMETHODS(
28728   flockIoFinder,            /* Finder function name */
28729   flockIoMethods,           /* sqlite3_io_methods object name */
28730   1,                        /* shared memory is disabled */
28731   flockClose,               /* xClose method */
28732   flockLock,                /* xLock method */
28733   flockUnlock,              /* xUnlock method */
28734   flockCheckReservedLock    /* xCheckReservedLock method */
28735 )
28736 #endif
28737
28738 #if OS_VXWORKS
28739 IOMETHODS(
28740   semIoFinder,              /* Finder function name */
28741   semIoMethods,             /* sqlite3_io_methods object name */
28742   1,                        /* shared memory is disabled */
28743   semClose,                 /* xClose method */
28744   semLock,                  /* xLock method */
28745   semUnlock,                /* xUnlock method */
28746   semCheckReservedLock      /* xCheckReservedLock method */
28747 )
28748 #endif
28749
28750 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28751 IOMETHODS(
28752   afpIoFinder,              /* Finder function name */
28753   afpIoMethods,             /* sqlite3_io_methods object name */
28754   1,                        /* shared memory is disabled */
28755   afpClose,                 /* xClose method */
28756   afpLock,                  /* xLock method */
28757   afpUnlock,                /* xUnlock method */
28758   afpCheckReservedLock      /* xCheckReservedLock method */
28759 )
28760 #endif
28761
28762 /*
28763 ** The proxy locking method is a "super-method" in the sense that it
28764 ** opens secondary file descriptors for the conch and lock files and
28765 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
28766 ** secondary files.  For this reason, the division that implements
28767 ** proxy locking is located much further down in the file.  But we need
28768 ** to go ahead and define the sqlite3_io_methods and finder function
28769 ** for proxy locking here.  So we forward declare the I/O methods.
28770 */
28771 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28772 static int proxyClose(sqlite3_file*);
28773 static int proxyLock(sqlite3_file*, int);
28774 static int proxyUnlock(sqlite3_file*, int);
28775 static int proxyCheckReservedLock(sqlite3_file*, int*);
28776 IOMETHODS(
28777   proxyIoFinder,            /* Finder function name */
28778   proxyIoMethods,           /* sqlite3_io_methods object name */
28779   1,                        /* shared memory is disabled */
28780   proxyClose,               /* xClose method */
28781   proxyLock,                /* xLock method */
28782   proxyUnlock,              /* xUnlock method */
28783   proxyCheckReservedLock    /* xCheckReservedLock method */
28784 )
28785 #endif
28786
28787 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
28788 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28789 IOMETHODS(
28790   nfsIoFinder,               /* Finder function name */
28791   nfsIoMethods,              /* sqlite3_io_methods object name */
28792   1,                         /* shared memory is disabled */
28793   unixClose,                 /* xClose method */
28794   unixLock,                  /* xLock method */
28795   nfsUnlock,                 /* xUnlock method */
28796   unixCheckReservedLock      /* xCheckReservedLock method */
28797 )
28798 #endif
28799
28800 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28801 /* 
28802 ** This "finder" function attempts to determine the best locking strategy 
28803 ** for the database file "filePath".  It then returns the sqlite3_io_methods
28804 ** object that implements that strategy.
28805 **
28806 ** This is for MacOSX only.
28807 */
28808 static const sqlite3_io_methods *autolockIoFinderImpl(
28809   const char *filePath,    /* name of the database file */
28810   unixFile *pNew           /* open file object for the database file */
28811 ){
28812   static const struct Mapping {
28813     const char *zFilesystem;              /* Filesystem type name */
28814     const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
28815   } aMap[] = {
28816     { "hfs",    &posixIoMethods },
28817     { "ufs",    &posixIoMethods },
28818     { "afpfs",  &afpIoMethods },
28819     { "smbfs",  &afpIoMethods },
28820     { "webdav", &nolockIoMethods },
28821     { 0, 0 }
28822   };
28823   int i;
28824   struct statfs fsInfo;
28825   struct flock lockInfo;
28826
28827   if( !filePath ){
28828     /* If filePath==NULL that means we are dealing with a transient file
28829     ** that does not need to be locked. */
28830     return &nolockIoMethods;
28831   }
28832   if( statfs(filePath, &fsInfo) != -1 ){
28833     if( fsInfo.f_flags & MNT_RDONLY ){
28834       return &nolockIoMethods;
28835     }
28836     for(i=0; aMap[i].zFilesystem; i++){
28837       if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
28838         return aMap[i].pMethods;
28839       }
28840     }
28841   }
28842
28843   /* Default case. Handles, amongst others, "nfs".
28844   ** Test byte-range lock using fcntl(). If the call succeeds, 
28845   ** assume that the file-system supports POSIX style locks. 
28846   */
28847   lockInfo.l_len = 1;
28848   lockInfo.l_start = 0;
28849   lockInfo.l_whence = SEEK_SET;
28850   lockInfo.l_type = F_RDLCK;
28851   if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
28852     if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
28853       return &nfsIoMethods;
28854     } else {
28855       return &posixIoMethods;
28856     }
28857   }else{
28858     return &dotlockIoMethods;
28859   }
28860 }
28861 static const sqlite3_io_methods 
28862   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
28863
28864 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
28865
28866 #if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
28867 /* 
28868 ** This "finder" function attempts to determine the best locking strategy 
28869 ** for the database file "filePath".  It then returns the sqlite3_io_methods
28870 ** object that implements that strategy.
28871 **
28872 ** This is for VXWorks only.
28873 */
28874 static const sqlite3_io_methods *autolockIoFinderImpl(
28875   const char *filePath,    /* name of the database file */
28876   unixFile *pNew           /* the open file object */
28877 ){
28878   struct flock lockInfo;
28879
28880   if( !filePath ){
28881     /* If filePath==NULL that means we are dealing with a transient file
28882     ** that does not need to be locked. */
28883     return &nolockIoMethods;
28884   }
28885
28886   /* Test if fcntl() is supported and use POSIX style locks.
28887   ** Otherwise fall back to the named semaphore method.
28888   */
28889   lockInfo.l_len = 1;
28890   lockInfo.l_start = 0;
28891   lockInfo.l_whence = SEEK_SET;
28892   lockInfo.l_type = F_RDLCK;
28893   if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
28894     return &posixIoMethods;
28895   }else{
28896     return &semIoMethods;
28897   }
28898 }
28899 static const sqlite3_io_methods 
28900   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
28901
28902 #endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
28903
28904 /*
28905 ** An abstract type for a pointer to a IO method finder function:
28906 */
28907 typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
28908
28909
28910 /****************************************************************************
28911 **************************** sqlite3_vfs methods ****************************
28912 **
28913 ** This division contains the implementation of methods on the
28914 ** sqlite3_vfs object.
28915 */
28916
28917 /*
28918 ** Initialize the contents of the unixFile structure pointed to by pId.
28919 */
28920 static int fillInUnixFile(
28921   sqlite3_vfs *pVfs,      /* Pointer to vfs object */
28922   int h,                  /* Open file descriptor of file being opened */
28923   int dirfd,              /* Directory file descriptor */
28924   sqlite3_file *pId,      /* Write to the unixFile structure here */
28925   const char *zFilename,  /* Name of the file being opened */
28926   int noLock,             /* Omit locking if true */
28927   int isDelete,           /* Delete on close if true */
28928   int isReadOnly          /* True if the file is opened read-only */
28929 ){
28930   const sqlite3_io_methods *pLockingStyle;
28931   unixFile *pNew = (unixFile *)pId;
28932   int rc = SQLITE_OK;
28933
28934   assert( pNew->pInode==NULL );
28935
28936   /* Parameter isDelete is only used on vxworks. Express this explicitly 
28937   ** here to prevent compiler warnings about unused parameters.
28938   */
28939   UNUSED_PARAMETER(isDelete);
28940
28941   /* Usually the path zFilename should not be a relative pathname. The
28942   ** exception is when opening the proxy "conch" file in builds that
28943   ** include the special Apple locking styles.
28944   */
28945 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28946   assert( zFilename==0 || zFilename[0]=='/' 
28947     || pVfs->pAppData==(void*)&autolockIoFinder );
28948 #else
28949   assert( zFilename==0 || zFilename[0]=='/' );
28950 #endif
28951
28952   OSTRACE(("OPEN    %-3d %s\n", h, zFilename));
28953   pNew->h = h;
28954   pNew->dirfd = dirfd;
28955   pNew->zPath = zFilename;
28956   if( memcmp(pVfs->zName,"unix-excl",10)==0 ){
28957     pNew->ctrlFlags = UNIXFILE_EXCL;
28958   }else{
28959     pNew->ctrlFlags = 0;
28960   }
28961   if( isReadOnly ){
28962     pNew->ctrlFlags |= UNIXFILE_RDONLY;
28963   }
28964
28965 #if OS_VXWORKS
28966   pNew->pId = vxworksFindFileId(zFilename);
28967   if( pNew->pId==0 ){
28968     noLock = 1;
28969     rc = SQLITE_NOMEM;
28970   }
28971 #endif
28972
28973   if( noLock ){
28974     pLockingStyle = &nolockIoMethods;
28975   }else{
28976     pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
28977 #if SQLITE_ENABLE_LOCKING_STYLE
28978     /* Cache zFilename in the locking context (AFP and dotlock override) for
28979     ** proxyLock activation is possible (remote proxy is based on db name)
28980     ** zFilename remains valid until file is closed, to support */
28981     pNew->lockingContext = (void*)zFilename;
28982 #endif
28983   }
28984
28985   if( pLockingStyle == &posixIoMethods
28986 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28987     || pLockingStyle == &nfsIoMethods
28988 #endif
28989   ){
28990     unixEnterMutex();
28991     rc = findInodeInfo(pNew, &pNew->pInode);
28992     if( rc!=SQLITE_OK ){
28993       /* If an error occured in findInodeInfo(), close the file descriptor
28994       ** immediately, before releasing the mutex. findInodeInfo() may fail
28995       ** in two scenarios:
28996       **
28997       **   (a) A call to fstat() failed.
28998       **   (b) A malloc failed.
28999       **
29000       ** Scenario (b) may only occur if the process is holding no other
29001       ** file descriptors open on the same file. If there were other file
29002       ** descriptors on this file, then no malloc would be required by
29003       ** findInodeInfo(). If this is the case, it is quite safe to close
29004       ** handle h - as it is guaranteed that no posix locks will be released
29005       ** by doing so.
29006       **
29007       ** If scenario (a) caused the error then things are not so safe. The
29008       ** implicit assumption here is that if fstat() fails, things are in
29009       ** such bad shape that dropping a lock or two doesn't matter much.
29010       */
29011       robust_close(pNew, h, __LINE__);
29012       h = -1;
29013     }
29014     unixLeaveMutex();
29015   }
29016
29017 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
29018   else if( pLockingStyle == &afpIoMethods ){
29019     /* AFP locking uses the file path so it needs to be included in
29020     ** the afpLockingContext.
29021     */
29022     afpLockingContext *pCtx;
29023     pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
29024     if( pCtx==0 ){
29025       rc = SQLITE_NOMEM;
29026     }else{
29027       /* NB: zFilename exists and remains valid until the file is closed
29028       ** according to requirement F11141.  So we do not need to make a
29029       ** copy of the filename. */
29030       pCtx->dbPath = zFilename;
29031       pCtx->reserved = 0;
29032       srandomdev();
29033       unixEnterMutex();
29034       rc = findInodeInfo(pNew, &pNew->pInode);
29035       if( rc!=SQLITE_OK ){
29036         sqlite3_free(pNew->lockingContext);
29037         robust_close(pNew, h, __LINE__);
29038         h = -1;
29039       }
29040       unixLeaveMutex();        
29041     }
29042   }
29043 #endif
29044
29045   else if( pLockingStyle == &dotlockIoMethods ){
29046     /* Dotfile locking uses the file path so it needs to be included in
29047     ** the dotlockLockingContext 
29048     */
29049     char *zLockFile;
29050     int nFilename;
29051     nFilename = (int)strlen(zFilename) + 6;
29052     zLockFile = (char *)sqlite3_malloc(nFilename);
29053     if( zLockFile==0 ){
29054       rc = SQLITE_NOMEM;
29055     }else{
29056       sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
29057     }
29058     pNew->lockingContext = zLockFile;
29059   }
29060
29061 #if OS_VXWORKS
29062   else if( pLockingStyle == &semIoMethods ){
29063     /* Named semaphore locking uses the file path so it needs to be
29064     ** included in the semLockingContext
29065     */
29066     unixEnterMutex();
29067     rc = findInodeInfo(pNew, &pNew->pInode);
29068     if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
29069       char *zSemName = pNew->pInode->aSemName;
29070       int n;
29071       sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
29072                        pNew->pId->zCanonicalName);
29073       for( n=1; zSemName[n]; n++ )
29074         if( zSemName[n]=='/' ) zSemName[n] = '_';
29075       pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
29076       if( pNew->pInode->pSem == SEM_FAILED ){
29077         rc = SQLITE_NOMEM;
29078         pNew->pInode->aSemName[0] = '\0';
29079       }
29080     }
29081     unixLeaveMutex();
29082   }
29083 #endif
29084   
29085   pNew->lastErrno = 0;
29086 #if OS_VXWORKS
29087   if( rc!=SQLITE_OK ){
29088     if( h>=0 ) robust_close(pNew, h, __LINE__);
29089     h = -1;
29090     unlink(zFilename);
29091     isDelete = 0;
29092   }
29093   pNew->isDelete = isDelete;
29094 #endif
29095   if( rc!=SQLITE_OK ){
29096     if( dirfd>=0 ) robust_close(pNew, dirfd, __LINE__);
29097     if( h>=0 ) robust_close(pNew, h, __LINE__);
29098   }else{
29099     pNew->pMethod = pLockingStyle;
29100     OpenCounter(+1);
29101   }
29102   return rc;
29103 }
29104
29105 /*
29106 ** Open a file descriptor to the directory containing file zFilename.
29107 ** If successful, *pFd is set to the opened file descriptor and
29108 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
29109 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
29110 ** value.
29111 **
29112 ** If SQLITE_OK is returned, the caller is responsible for closing
29113 ** the file descriptor *pFd using close().
29114 */
29115 static int openDirectory(const char *zFilename, int *pFd){
29116   int ii;
29117   int fd = -1;
29118   char zDirname[MAX_PATHNAME+1];
29119
29120   sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
29121   for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
29122   if( ii>0 ){
29123     zDirname[ii] = '\0';
29124     fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
29125     if( fd>=0 ){
29126 #ifdef FD_CLOEXEC
29127       osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
29128 #endif
29129       OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
29130     }
29131   }
29132   *pFd = fd;
29133   return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
29134 }
29135
29136 /*
29137 ** Return the name of a directory in which to put temporary files.
29138 ** If no suitable temporary file directory can be found, return NULL.
29139 */
29140 static const char *unixTempFileDir(void){
29141   static const char *azDirs[] = {
29142      0,
29143      0,
29144      "/var/tmp",
29145      "/usr/tmp",
29146      "/tmp",
29147      0        /* List terminator */
29148   };
29149   unsigned int i;
29150   struct stat buf;
29151   const char *zDir = 0;
29152
29153   azDirs[0] = sqlite3_temp_directory;
29154   if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
29155   for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
29156     if( zDir==0 ) continue;
29157     if( osStat(zDir, &buf) ) continue;
29158     if( !S_ISDIR(buf.st_mode) ) continue;
29159     if( osAccess(zDir, 07) ) continue;
29160     break;
29161   }
29162   return zDir;
29163 }
29164
29165 /*
29166 ** Create a temporary file name in zBuf.  zBuf must be allocated
29167 ** by the calling process and must be big enough to hold at least
29168 ** pVfs->mxPathname bytes.
29169 */
29170 static int unixGetTempname(int nBuf, char *zBuf){
29171   static const unsigned char zChars[] =
29172     "abcdefghijklmnopqrstuvwxyz"
29173     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
29174     "0123456789";
29175   unsigned int i, j;
29176   const char *zDir;
29177
29178   /* It's odd to simulate an io-error here, but really this is just
29179   ** using the io-error infrastructure to test that SQLite handles this
29180   ** function failing. 
29181   */
29182   SimulateIOError( return SQLITE_IOERR );
29183
29184   zDir = unixTempFileDir();
29185   if( zDir==0 ) zDir = ".";
29186
29187   /* Check that the output buffer is large enough for the temporary file 
29188   ** name. If it is not, return SQLITE_ERROR.
29189   */
29190   if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
29191     return SQLITE_ERROR;
29192   }
29193
29194   do{
29195     sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
29196     j = (int)strlen(zBuf);
29197     sqlite3_randomness(15, &zBuf[j]);
29198     for(i=0; i<15; i++, j++){
29199       zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
29200     }
29201     zBuf[j] = 0;
29202   }while( osAccess(zBuf,0)==0 );
29203   return SQLITE_OK;
29204 }
29205
29206 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
29207 /*
29208 ** Routine to transform a unixFile into a proxy-locking unixFile.
29209 ** Implementation in the proxy-lock division, but used by unixOpen()
29210 ** if SQLITE_PREFER_PROXY_LOCKING is defined.
29211 */
29212 static int proxyTransformUnixFile(unixFile*, const char*);
29213 #endif
29214
29215 /*
29216 ** Search for an unused file descriptor that was opened on the database 
29217 ** file (not a journal or master-journal file) identified by pathname
29218 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
29219 ** argument to this function.
29220 **
29221 ** Such a file descriptor may exist if a database connection was closed
29222 ** but the associated file descriptor could not be closed because some
29223 ** other file descriptor open on the same file is holding a file-lock.
29224 ** Refer to comments in the unixClose() function and the lengthy comment
29225 ** describing "Posix Advisory Locking" at the start of this file for 
29226 ** further details. Also, ticket #4018.
29227 **
29228 ** If a suitable file descriptor is found, then it is returned. If no
29229 ** such file descriptor is located, -1 is returned.
29230 */
29231 static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
29232   UnixUnusedFd *pUnused = 0;
29233
29234   /* Do not search for an unused file descriptor on vxworks. Not because
29235   ** vxworks would not benefit from the change (it might, we're not sure),
29236   ** but because no way to test it is currently available. It is better 
29237   ** not to risk breaking vxworks support for the sake of such an obscure 
29238   ** feature.  */
29239 #if !OS_VXWORKS
29240   struct stat sStat;                   /* Results of stat() call */
29241
29242   /* A stat() call may fail for various reasons. If this happens, it is
29243   ** almost certain that an open() call on the same path will also fail.
29244   ** For this reason, if an error occurs in the stat() call here, it is
29245   ** ignored and -1 is returned. The caller will try to open a new file
29246   ** descriptor on the same path, fail, and return an error to SQLite.
29247   **
29248   ** Even if a subsequent open() call does succeed, the consequences of
29249   ** not searching for a resusable file descriptor are not dire.  */
29250   if( 0==stat(zPath, &sStat) ){
29251     unixInodeInfo *pInode;
29252
29253     unixEnterMutex();
29254     pInode = inodeList;
29255     while( pInode && (pInode->fileId.dev!=sStat.st_dev
29256                      || pInode->fileId.ino!=sStat.st_ino) ){
29257        pInode = pInode->pNext;
29258     }
29259     if( pInode ){
29260       UnixUnusedFd **pp;
29261       for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
29262       pUnused = *pp;
29263       if( pUnused ){
29264         *pp = pUnused->pNext;
29265       }
29266     }
29267     unixLeaveMutex();
29268   }
29269 #endif    /* if !OS_VXWORKS */
29270   return pUnused;
29271 }
29272
29273 /*
29274 ** This function is called by unixOpen() to determine the unix permissions
29275 ** to create new files with. If no error occurs, then SQLITE_OK is returned
29276 ** and a value suitable for passing as the third argument to open(2) is
29277 ** written to *pMode. If an IO error occurs, an SQLite error code is 
29278 ** returned and the value of *pMode is not modified.
29279 **
29280 ** If the file being opened is a temporary file, it is always created with
29281 ** the octal permissions 0600 (read/writable by owner only). If the file
29282 ** is a database or master journal file, it is created with the permissions 
29283 ** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
29284 **
29285 ** Finally, if the file being opened is a WAL or regular journal file, then 
29286 ** this function queries the file-system for the permissions on the 
29287 ** corresponding database file and sets *pMode to this value. Whenever 
29288 ** possible, WAL and journal files are created using the same permissions 
29289 ** as the associated database file.
29290 **
29291 ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
29292 ** original filename is unavailable.  But 8_3_NAMES is only used for
29293 ** FAT filesystems and permissions do not matter there, so just use
29294 ** the default permissions.
29295 */
29296 static int findCreateFileMode(
29297   const char *zPath,              /* Path of file (possibly) being created */
29298   int flags,                      /* Flags passed as 4th argument to xOpen() */
29299   mode_t *pMode                   /* OUT: Permissions to open file with */
29300 ){
29301   int rc = SQLITE_OK;             /* Return Code */
29302   *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
29303   if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
29304     char zDb[MAX_PATHNAME+1];     /* Database file path */
29305     int nDb;                      /* Number of valid bytes in zDb */
29306     struct stat sStat;            /* Output of stat() on database file */
29307
29308     /* zPath is a path to a WAL or journal file. The following block derives
29309     ** the path to the associated database file from zPath. This block handles
29310     ** the following naming conventions:
29311     **
29312     **   "<path to db>-journal"
29313     **   "<path to db>-wal"
29314     **   "<path to db>-journalNN"
29315     **   "<path to db>-walNN"
29316     **
29317     ** where NN is a 4 digit decimal number. The NN naming schemes are 
29318     ** used by the test_multiplex.c module.
29319     */
29320     nDb = sqlite3Strlen30(zPath) - 1; 
29321     while( nDb>0 && zPath[nDb]!='-' ) nDb--;
29322     if( nDb==0 ) return SQLITE_OK;
29323     memcpy(zDb, zPath, nDb);
29324     zDb[nDb] = '\0';
29325
29326     if( 0==stat(zDb, &sStat) ){
29327       *pMode = sStat.st_mode & 0777;
29328     }else{
29329       rc = SQLITE_IOERR_FSTAT;
29330     }
29331   }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
29332     *pMode = 0600;
29333   }
29334   return rc;
29335 }
29336
29337 /*
29338 ** Open the file zPath.
29339 ** 
29340 ** Previously, the SQLite OS layer used three functions in place of this
29341 ** one:
29342 **
29343 **     sqlite3OsOpenReadWrite();
29344 **     sqlite3OsOpenReadOnly();
29345 **     sqlite3OsOpenExclusive();
29346 **
29347 ** These calls correspond to the following combinations of flags:
29348 **
29349 **     ReadWrite() ->     (READWRITE | CREATE)
29350 **     ReadOnly()  ->     (READONLY) 
29351 **     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
29352 **
29353 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
29354 ** true, the file was configured to be automatically deleted when the
29355 ** file handle closed. To achieve the same effect using this new 
29356 ** interface, add the DELETEONCLOSE flag to those specified above for 
29357 ** OpenExclusive().
29358 */
29359 static int unixOpen(
29360   sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
29361   const char *zPath,           /* Pathname of file to be opened */
29362   sqlite3_file *pFile,         /* The file descriptor to be filled in */
29363   int flags,                   /* Input flags to control the opening */
29364   int *pOutFlags               /* Output flags returned to SQLite core */
29365 ){
29366   unixFile *p = (unixFile *)pFile;
29367   int fd = -1;                   /* File descriptor returned by open() */
29368   int dirfd = -1;                /* Directory file descriptor */
29369   int openFlags = 0;             /* Flags to pass to open() */
29370   int eType = flags&0xFFFFFF00;  /* Type of file to open */
29371   int noLock;                    /* True to omit locking primitives */
29372   int rc = SQLITE_OK;            /* Function Return Code */
29373
29374   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
29375   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
29376   int isCreate     = (flags & SQLITE_OPEN_CREATE);
29377   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
29378   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
29379 #if SQLITE_ENABLE_LOCKING_STYLE
29380   int isAutoProxy  = (flags & SQLITE_OPEN_AUTOPROXY);
29381 #endif
29382
29383   /* If creating a master or main-file journal, this function will open
29384   ** a file-descriptor on the directory too. The first time unixSync()
29385   ** is called the directory file descriptor will be fsync()ed and close()d.
29386   */
29387   int isOpenDirectory = (isCreate && (
29388         eType==SQLITE_OPEN_MASTER_JOURNAL 
29389      || eType==SQLITE_OPEN_MAIN_JOURNAL 
29390      || eType==SQLITE_OPEN_WAL
29391   ));
29392
29393   /* If argument zPath is a NULL pointer, this function is required to open
29394   ** a temporary file. Use this buffer to store the file name in.
29395   */
29396   char zTmpname[MAX_PATHNAME+1];
29397   const char *zName = zPath;
29398
29399   /* Check the following statements are true: 
29400   **
29401   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
29402   **   (b) if CREATE is set, then READWRITE must also be set, and
29403   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
29404   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
29405   */
29406   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
29407   assert(isCreate==0 || isReadWrite);
29408   assert(isExclusive==0 || isCreate);
29409   assert(isDelete==0 || isCreate);
29410
29411   /* The main DB, main journal, WAL file and master journal are never 
29412   ** automatically deleted. Nor are they ever temporary files.  */
29413   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
29414   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
29415   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
29416   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
29417
29418   /* Assert that the upper layer has set one of the "file-type" flags. */
29419   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
29420        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
29421        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
29422        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
29423   );
29424
29425   memset(p, 0, sizeof(unixFile));
29426
29427   if( eType==SQLITE_OPEN_MAIN_DB ){
29428     UnixUnusedFd *pUnused;
29429     pUnused = findReusableFd(zName, flags);
29430     if( pUnused ){
29431       fd = pUnused->fd;
29432     }else{
29433       pUnused = sqlite3_malloc(sizeof(*pUnused));
29434       if( !pUnused ){
29435         return SQLITE_NOMEM;
29436       }
29437     }
29438     p->pUnused = pUnused;
29439   }else if( !zName ){
29440     /* If zName is NULL, the upper layer is requesting a temp file. */
29441     assert(isDelete && !isOpenDirectory);
29442     rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
29443     if( rc!=SQLITE_OK ){
29444       return rc;
29445     }
29446     zName = zTmpname;
29447   }
29448
29449   /* Determine the value of the flags parameter passed to POSIX function
29450   ** open(). These must be calculated even if open() is not called, as
29451   ** they may be stored as part of the file handle and used by the 
29452   ** 'conch file' locking functions later on.  */
29453   if( isReadonly )  openFlags |= O_RDONLY;
29454   if( isReadWrite ) openFlags |= O_RDWR;
29455   if( isCreate )    openFlags |= O_CREAT;
29456   if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
29457   openFlags |= (O_LARGEFILE|O_BINARY);
29458
29459   if( fd<0 ){
29460     mode_t openMode;              /* Permissions to create file with */
29461     rc = findCreateFileMode(zName, flags, &openMode);
29462     if( rc!=SQLITE_OK ){
29463       assert( !p->pUnused );
29464       assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
29465       return rc;
29466     }
29467     fd = robust_open(zName, openFlags, openMode);
29468     OSTRACE(("OPENX   %-3d %s 0%o\n", fd, zName, openFlags));
29469     if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
29470       /* Failed to open the file for read/write access. Try read-only. */
29471       flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
29472       openFlags &= ~(O_RDWR|O_CREAT);
29473       flags |= SQLITE_OPEN_READONLY;
29474       openFlags |= O_RDONLY;
29475       isReadonly = 1;
29476       fd = robust_open(zName, openFlags, openMode);
29477     }
29478     if( fd<0 ){
29479       rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
29480       goto open_finished;
29481     }
29482   }
29483   assert( fd>=0 );
29484   if( pOutFlags ){
29485     *pOutFlags = flags;
29486   }
29487
29488   if( p->pUnused ){
29489     p->pUnused->fd = fd;
29490     p->pUnused->flags = flags;
29491   }
29492
29493   if( isDelete ){
29494 #if OS_VXWORKS
29495     zPath = zName;
29496 #else
29497     unlink(zName);
29498 #endif
29499   }
29500 #if SQLITE_ENABLE_LOCKING_STYLE
29501   else{
29502     p->openFlags = openFlags;
29503   }
29504 #endif
29505
29506   if( isOpenDirectory ){
29507     rc = openDirectory(zPath, &dirfd);
29508     if( rc!=SQLITE_OK ){
29509       /* It is safe to close fd at this point, because it is guaranteed not
29510       ** to be open on a database file. If it were open on a database file,
29511       ** it would not be safe to close as this would release any locks held
29512       ** on the file by this process.  */
29513       assert( eType!=SQLITE_OPEN_MAIN_DB );
29514       robust_close(p, fd, __LINE__);
29515       goto open_finished;
29516     }
29517   }
29518
29519 #ifdef FD_CLOEXEC
29520   osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
29521 #endif
29522
29523   noLock = eType!=SQLITE_OPEN_MAIN_DB;
29524
29525   
29526 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
29527   struct statfs fsInfo;
29528   if( fstatfs(fd, &fsInfo) == -1 ){
29529     ((unixFile*)pFile)->lastErrno = errno;
29530     if( dirfd>=0 ) robust_close(p, dirfd, __LINE__);
29531     robust_close(p, fd, __LINE__);
29532     return SQLITE_IOERR_ACCESS;
29533   }
29534   if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
29535     ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
29536   }
29537 #endif
29538   
29539 #if SQLITE_ENABLE_LOCKING_STYLE
29540 #if SQLITE_PREFER_PROXY_LOCKING
29541   isAutoProxy = 1;
29542 #endif
29543   if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
29544     char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
29545     int useProxy = 0;
29546
29547     /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means 
29548     ** never use proxy, NULL means use proxy for non-local files only.  */
29549     if( envforce!=NULL ){
29550       useProxy = atoi(envforce)>0;
29551     }else{
29552       struct statfs fsInfo;
29553       if( statfs(zPath, &fsInfo) == -1 ){
29554         /* In theory, the close(fd) call is sub-optimal. If the file opened
29555         ** with fd is a database file, and there are other connections open
29556         ** on that file that are currently holding advisory locks on it,
29557         ** then the call to close() will cancel those locks. In practice,
29558         ** we're assuming that statfs() doesn't fail very often. At least
29559         ** not while other file descriptors opened by the same process on
29560         ** the same file are working.  */
29561         p->lastErrno = errno;
29562         if( dirfd>=0 ){
29563           robust_close(p, dirfd, __LINE__);
29564         }
29565         robust_close(p, fd, __LINE__);
29566         rc = SQLITE_IOERR_ACCESS;
29567         goto open_finished;
29568       }
29569       useProxy = !(fsInfo.f_flags&MNT_LOCAL);
29570     }
29571     if( useProxy ){
29572       rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock,
29573                           isDelete, isReadonly);
29574       if( rc==SQLITE_OK ){
29575         rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
29576         if( rc!=SQLITE_OK ){
29577           /* Use unixClose to clean up the resources added in fillInUnixFile 
29578           ** and clear all the structure's references.  Specifically, 
29579           ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op 
29580           */
29581           unixClose(pFile);
29582           return rc;
29583         }
29584       }
29585       goto open_finished;
29586     }
29587   }
29588 #endif
29589   
29590   rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock,
29591                       isDelete, isReadonly);
29592 open_finished:
29593   if( rc!=SQLITE_OK ){
29594     sqlite3_free(p->pUnused);
29595   }
29596   return rc;
29597 }
29598
29599
29600 /*
29601 ** Delete the file at zPath. If the dirSync argument is true, fsync()
29602 ** the directory after deleting the file.
29603 */
29604 static int unixDelete(
29605   sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
29606   const char *zPath,        /* Name of file to be deleted */
29607   int dirSync               /* If true, fsync() directory after deleting file */
29608 ){
29609   int rc = SQLITE_OK;
29610   UNUSED_PARAMETER(NotUsed);
29611   SimulateIOError(return SQLITE_IOERR_DELETE);
29612   if( unlink(zPath)==(-1) && errno!=ENOENT ){
29613     return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
29614   }
29615 #ifndef SQLITE_DISABLE_DIRSYNC
29616   if( dirSync ){
29617     int fd;
29618     rc = openDirectory(zPath, &fd);
29619     if( rc==SQLITE_OK ){
29620 #if OS_VXWORKS
29621       if( fsync(fd)==-1 )
29622 #else
29623       if( fsync(fd) )
29624 #endif
29625       {
29626         rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
29627       }
29628       robust_close(0, fd, __LINE__);
29629     }
29630   }
29631 #endif
29632   return rc;
29633 }
29634
29635 /*
29636 ** Test the existance of or access permissions of file zPath. The
29637 ** test performed depends on the value of flags:
29638 **
29639 **     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
29640 **     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
29641 **     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
29642 **
29643 ** Otherwise return 0.
29644 */
29645 static int unixAccess(
29646   sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
29647   const char *zPath,      /* Path of the file to examine */
29648   int flags,              /* What do we want to learn about the zPath file? */
29649   int *pResOut            /* Write result boolean here */
29650 ){
29651   int amode = 0;
29652   UNUSED_PARAMETER(NotUsed);
29653   SimulateIOError( return SQLITE_IOERR_ACCESS; );
29654   switch( flags ){
29655     case SQLITE_ACCESS_EXISTS:
29656       amode = F_OK;
29657       break;
29658     case SQLITE_ACCESS_READWRITE:
29659       amode = W_OK|R_OK;
29660       break;
29661     case SQLITE_ACCESS_READ:
29662       amode = R_OK;
29663       break;
29664
29665     default:
29666       assert(!"Invalid flags argument");
29667   }
29668   *pResOut = (osAccess(zPath, amode)==0);
29669   if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
29670     struct stat buf;
29671     if( 0==stat(zPath, &buf) && buf.st_size==0 ){
29672       *pResOut = 0;
29673     }
29674   }
29675   return SQLITE_OK;
29676 }
29677
29678
29679 /*
29680 ** Turn a relative pathname into a full pathname. The relative path
29681 ** is stored as a nul-terminated string in the buffer pointed to by
29682 ** zPath. 
29683 **
29684 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes 
29685 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
29686 ** this buffer before returning.
29687 */
29688 static int unixFullPathname(
29689   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
29690   const char *zPath,            /* Possibly relative input path */
29691   int nOut,                     /* Size of output buffer in bytes */
29692   char *zOut                    /* Output buffer */
29693 ){
29694
29695   /* It's odd to simulate an io-error here, but really this is just
29696   ** using the io-error infrastructure to test that SQLite handles this
29697   ** function failing. This function could fail if, for example, the
29698   ** current working directory has been unlinked.
29699   */
29700   SimulateIOError( return SQLITE_ERROR );
29701
29702   assert( pVfs->mxPathname==MAX_PATHNAME );
29703   UNUSED_PARAMETER(pVfs);
29704
29705   zOut[nOut-1] = '\0';
29706   if( zPath[0]=='/' ){
29707     sqlite3_snprintf(nOut, zOut, "%s", zPath);
29708   }else{
29709     int nCwd;
29710     if( osGetcwd(zOut, nOut-1)==0 ){
29711       return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
29712     }
29713     nCwd = (int)strlen(zOut);
29714     sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
29715   }
29716   return SQLITE_OK;
29717 }
29718
29719
29720 #ifndef SQLITE_OMIT_LOAD_EXTENSION
29721 /*
29722 ** Interfaces for opening a shared library, finding entry points
29723 ** within the shared library, and closing the shared library.
29724 */
29725 #include <dlfcn.h>
29726 static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
29727   UNUSED_PARAMETER(NotUsed);
29728   return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
29729 }
29730
29731 /*
29732 ** SQLite calls this function immediately after a call to unixDlSym() or
29733 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
29734 ** message is available, it is written to zBufOut. If no error message
29735 ** is available, zBufOut is left unmodified and SQLite uses a default
29736 ** error message.
29737 */
29738 static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
29739   const char *zErr;
29740   UNUSED_PARAMETER(NotUsed);
29741   unixEnterMutex();
29742   zErr = dlerror();
29743   if( zErr ){
29744     sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
29745   }
29746   unixLeaveMutex();
29747 }
29748 static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
29749   /* 
29750   ** GCC with -pedantic-errors says that C90 does not allow a void* to be
29751   ** cast into a pointer to a function.  And yet the library dlsym() routine
29752   ** returns a void* which is really a pointer to a function.  So how do we
29753   ** use dlsym() with -pedantic-errors?
29754   **
29755   ** Variable x below is defined to be a pointer to a function taking
29756   ** parameters void* and const char* and returning a pointer to a function.
29757   ** We initialize x by assigning it a pointer to the dlsym() function.
29758   ** (That assignment requires a cast.)  Then we call the function that
29759   ** x points to.  
29760   **
29761   ** This work-around is unlikely to work correctly on any system where
29762   ** you really cannot cast a function pointer into void*.  But then, on the
29763   ** other hand, dlsym() will not work on such a system either, so we have
29764   ** not really lost anything.
29765   */
29766   void (*(*x)(void*,const char*))(void);
29767   UNUSED_PARAMETER(NotUsed);
29768   x = (void(*(*)(void*,const char*))(void))dlsym;
29769   return (*x)(p, zSym);
29770 }
29771 static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
29772   UNUSED_PARAMETER(NotUsed);
29773   dlclose(pHandle);
29774 }
29775 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
29776   #define unixDlOpen  0
29777   #define unixDlError 0
29778   #define unixDlSym   0
29779   #define unixDlClose 0
29780 #endif
29781
29782 /*
29783 ** Write nBuf bytes of random data to the supplied buffer zBuf.
29784 */
29785 static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
29786   UNUSED_PARAMETER(NotUsed);
29787   assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
29788
29789   /* We have to initialize zBuf to prevent valgrind from reporting
29790   ** errors.  The reports issued by valgrind are incorrect - we would
29791   ** prefer that the randomness be increased by making use of the
29792   ** uninitialized space in zBuf - but valgrind errors tend to worry
29793   ** some users.  Rather than argue, it seems easier just to initialize
29794   ** the whole array and silence valgrind, even if that means less randomness
29795   ** in the random seed.
29796   **
29797   ** When testing, initializing zBuf[] to zero is all we do.  That means
29798   ** that we always use the same random number sequence.  This makes the
29799   ** tests repeatable.
29800   */
29801   memset(zBuf, 0, nBuf);
29802 #if !defined(SQLITE_TEST)
29803   {
29804     int pid, fd;
29805     fd = robust_open("/dev/urandom", O_RDONLY, 0);
29806     if( fd<0 ){
29807       time_t t;
29808       time(&t);
29809       memcpy(zBuf, &t, sizeof(t));
29810       pid = getpid();
29811       memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
29812       assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
29813       nBuf = sizeof(t) + sizeof(pid);
29814     }else{
29815       do{ nBuf = osRead(fd, zBuf, nBuf); }while( nBuf<0 && errno==EINTR );
29816       robust_close(0, fd, __LINE__);
29817     }
29818   }
29819 #endif
29820   return nBuf;
29821 }
29822
29823
29824 /*
29825 ** Sleep for a little while.  Return the amount of time slept.
29826 ** The argument is the number of microseconds we want to sleep.
29827 ** The return value is the number of microseconds of sleep actually
29828 ** requested from the underlying operating system, a number which
29829 ** might be greater than or equal to the argument, but not less
29830 ** than the argument.
29831 */
29832 static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
29833 #if OS_VXWORKS
29834   struct timespec sp;
29835
29836   sp.tv_sec = microseconds / 1000000;
29837   sp.tv_nsec = (microseconds % 1000000) * 1000;
29838   nanosleep(&sp, NULL);
29839   UNUSED_PARAMETER(NotUsed);
29840   return microseconds;
29841 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
29842   usleep(microseconds);
29843   UNUSED_PARAMETER(NotUsed);
29844   return microseconds;
29845 #else
29846   int seconds = (microseconds+999999)/1000000;
29847   sleep(seconds);
29848   UNUSED_PARAMETER(NotUsed);
29849   return seconds*1000000;
29850 #endif
29851 }
29852
29853 /*
29854 ** The following variable, if set to a non-zero value, is interpreted as
29855 ** the number of seconds since 1970 and is used to set the result of
29856 ** sqlite3OsCurrentTime() during testing.
29857 */
29858 #ifdef SQLITE_TEST
29859 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
29860 #endif
29861
29862 /*
29863 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
29864 ** the current time and date as a Julian Day number times 86_400_000.  In
29865 ** other words, write into *piNow the number of milliseconds since the Julian
29866 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
29867 ** proleptic Gregorian calendar.
29868 **
29869 ** On success, return 0.  Return 1 if the time and date cannot be found.
29870 */
29871 static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
29872   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
29873 #if defined(NO_GETTOD)
29874   time_t t;
29875   time(&t);
29876   *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
29877 #elif OS_VXWORKS
29878   struct timespec sNow;
29879   clock_gettime(CLOCK_REALTIME, &sNow);
29880   *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
29881 #else
29882   struct timeval sNow;
29883   gettimeofday(&sNow, 0);
29884   *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
29885 #endif
29886
29887 #ifdef SQLITE_TEST
29888   if( sqlite3_current_time ){
29889     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
29890   }
29891 #endif
29892   UNUSED_PARAMETER(NotUsed);
29893   return 0;
29894 }
29895
29896 /*
29897 ** Find the current time (in Universal Coordinated Time).  Write the
29898 ** current time and date as a Julian Day number into *prNow and
29899 ** return 0.  Return 1 if the time and date cannot be found.
29900 */
29901 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
29902   sqlite3_int64 i;
29903   UNUSED_PARAMETER(NotUsed);
29904   unixCurrentTimeInt64(0, &i);
29905   *prNow = i/86400000.0;
29906   return 0;
29907 }
29908
29909 /*
29910 ** We added the xGetLastError() method with the intention of providing
29911 ** better low-level error messages when operating-system problems come up
29912 ** during SQLite operation.  But so far, none of that has been implemented
29913 ** in the core.  So this routine is never called.  For now, it is merely
29914 ** a place-holder.
29915 */
29916 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
29917   UNUSED_PARAMETER(NotUsed);
29918   UNUSED_PARAMETER(NotUsed2);
29919   UNUSED_PARAMETER(NotUsed3);
29920   return 0;
29921 }
29922
29923
29924 /*
29925 ************************ End of sqlite3_vfs methods ***************************
29926 ******************************************************************************/
29927
29928 /******************************************************************************
29929 ************************** Begin Proxy Locking ********************************
29930 **
29931 ** Proxy locking is a "uber-locking-method" in this sense:  It uses the
29932 ** other locking methods on secondary lock files.  Proxy locking is a
29933 ** meta-layer over top of the primitive locking implemented above.  For
29934 ** this reason, the division that implements of proxy locking is deferred
29935 ** until late in the file (here) after all of the other I/O methods have
29936 ** been defined - so that the primitive locking methods are available
29937 ** as services to help with the implementation of proxy locking.
29938 **
29939 ****
29940 **
29941 ** The default locking schemes in SQLite use byte-range locks on the
29942 ** database file to coordinate safe, concurrent access by multiple readers
29943 ** and writers [http://sqlite.org/lockingv3.html].  The five file locking
29944 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
29945 ** as POSIX read & write locks over fixed set of locations (via fsctl),
29946 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
29947 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
29948 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
29949 ** address in the shared range is taken for a SHARED lock, the entire
29950 ** shared range is taken for an EXCLUSIVE lock):
29951 **
29952 **      PENDING_BYTE        0x40000000                  
29953 **      RESERVED_BYTE       0x40000001
29954 **      SHARED_RANGE        0x40000002 -> 0x40000200
29955 **
29956 ** This works well on the local file system, but shows a nearly 100x
29957 ** slowdown in read performance on AFP because the AFP client disables
29958 ** the read cache when byte-range locks are present.  Enabling the read
29959 ** cache exposes a cache coherency problem that is present on all OS X
29960 ** supported network file systems.  NFS and AFP both observe the
29961 ** close-to-open semantics for ensuring cache coherency
29962 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
29963 ** address the requirements for concurrent database access by multiple
29964 ** readers and writers
29965 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
29966 **
29967 ** To address the performance and cache coherency issues, proxy file locking
29968 ** changes the way database access is controlled by limiting access to a
29969 ** single host at a time and moving file locks off of the database file
29970 ** and onto a proxy file on the local file system.  
29971 **
29972 **
29973 ** Using proxy locks
29974 ** -----------------
29975 **
29976 ** C APIs
29977 **
29978 **  sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
29979 **                       <proxy_path> | ":auto:");
29980 **  sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
29981 **
29982 **
29983 ** SQL pragmas
29984 **
29985 **  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
29986 **  PRAGMA [database.]lock_proxy_file
29987 **
29988 ** Specifying ":auto:" means that if there is a conch file with a matching
29989 ** host ID in it, the proxy path in the conch file will be used, otherwise
29990 ** a proxy path based on the user's temp dir
29991 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
29992 ** actual proxy file name is generated from the name and path of the
29993 ** database file.  For example:
29994 **
29995 **       For database path "/Users/me/foo.db" 
29996 **       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
29997 **
29998 ** Once a lock proxy is configured for a database connection, it can not
29999 ** be removed, however it may be switched to a different proxy path via
30000 ** the above APIs (assuming the conch file is not being held by another
30001 ** connection or process). 
30002 **
30003 **
30004 ** How proxy locking works
30005 ** -----------------------
30006 **
30007 ** Proxy file locking relies primarily on two new supporting files: 
30008 **
30009 **   *  conch file to limit access to the database file to a single host
30010 **      at a time
30011 **
30012 **   *  proxy file to act as a proxy for the advisory locks normally
30013 **      taken on the database
30014 **
30015 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
30016 ** by taking an sqlite-style shared lock on the conch file, reading the
30017 ** contents and comparing the host's unique host ID (see below) and lock
30018 ** proxy path against the values stored in the conch.  The conch file is
30019 ** stored in the same directory as the database file and the file name
30020 ** is patterned after the database file name as ".<databasename>-conch".
30021 ** If the conch file does not exist, or it's contents do not match the
30022 ** host ID and/or proxy path, then the lock is escalated to an exclusive
30023 ** lock and the conch file contents is updated with the host ID and proxy
30024 ** path and the lock is downgraded to a shared lock again.  If the conch
30025 ** is held by another process (with a shared lock), the exclusive lock
30026 ** will fail and SQLITE_BUSY is returned.
30027 **
30028 ** The proxy file - a single-byte file used for all advisory file locks
30029 ** normally taken on the database file.   This allows for safe sharing
30030 ** of the database file for multiple readers and writers on the same
30031 ** host (the conch ensures that they all use the same local lock file).
30032 **
30033 ** Requesting the lock proxy does not immediately take the conch, it is
30034 ** only taken when the first request to lock database file is made.  
30035 ** This matches the semantics of the traditional locking behavior, where
30036 ** opening a connection to a database file does not take a lock on it.
30037 ** The shared lock and an open file descriptor are maintained until 
30038 ** the connection to the database is closed. 
30039 **
30040 ** The proxy file and the lock file are never deleted so they only need
30041 ** to be created the first time they are used.
30042 **
30043 ** Configuration options
30044 ** ---------------------
30045 **
30046 **  SQLITE_PREFER_PROXY_LOCKING
30047 **
30048 **       Database files accessed on non-local file systems are
30049 **       automatically configured for proxy locking, lock files are
30050 **       named automatically using the same logic as
30051 **       PRAGMA lock_proxy_file=":auto:"
30052 **    
30053 **  SQLITE_PROXY_DEBUG
30054 **
30055 **       Enables the logging of error messages during host id file
30056 **       retrieval and creation
30057 **
30058 **  LOCKPROXYDIR
30059 **
30060 **       Overrides the default directory used for lock proxy files that
30061 **       are named automatically via the ":auto:" setting
30062 **
30063 **  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
30064 **
30065 **       Permissions to use when creating a directory for storing the
30066 **       lock proxy files, only used when LOCKPROXYDIR is not set.
30067 **    
30068 **    
30069 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
30070 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
30071 ** force proxy locking to be used for every database file opened, and 0
30072 ** will force automatic proxy locking to be disabled for all database
30073 ** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
30074 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
30075 */
30076
30077 /*
30078 ** Proxy locking is only available on MacOSX 
30079 */
30080 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
30081
30082 /*
30083 ** The proxyLockingContext has the path and file structures for the remote 
30084 ** and local proxy files in it
30085 */
30086 typedef struct proxyLockingContext proxyLockingContext;
30087 struct proxyLockingContext {
30088   unixFile *conchFile;         /* Open conch file */
30089   char *conchFilePath;         /* Name of the conch file */
30090   unixFile *lockProxy;         /* Open proxy lock file */
30091   char *lockProxyPath;         /* Name of the proxy lock file */
30092   char *dbPath;                /* Name of the open file */
30093   int conchHeld;               /* 1 if the conch is held, -1 if lockless */
30094   void *oldLockingContext;     /* Original lockingcontext to restore on close */
30095   sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
30096 };
30097
30098 /* 
30099 ** The proxy lock file path for the database at dbPath is written into lPath, 
30100 ** which must point to valid, writable memory large enough for a maxLen length
30101 ** file path. 
30102 */
30103 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
30104   int len;
30105   int dbLen;
30106   int i;
30107
30108 #ifdef LOCKPROXYDIR
30109   len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
30110 #else
30111 # ifdef _CS_DARWIN_USER_TEMP_DIR
30112   {
30113     if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
30114       OSTRACE(("GETLOCKPATH  failed %s errno=%d pid=%d\n",
30115                lPath, errno, getpid()));
30116       return SQLITE_IOERR_LOCK;
30117     }
30118     len = strlcat(lPath, "sqliteplocks", maxLen);    
30119   }
30120 # else
30121   len = strlcpy(lPath, "/tmp/", maxLen);
30122 # endif
30123 #endif
30124
30125   if( lPath[len-1]!='/' ){
30126     len = strlcat(lPath, "/", maxLen);
30127   }
30128   
30129   /* transform the db path to a unique cache name */
30130   dbLen = (int)strlen(dbPath);
30131   for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
30132     char c = dbPath[i];
30133     lPath[i+len] = (c=='/')?'_':c;
30134   }
30135   lPath[i+len]='\0';
30136   strlcat(lPath, ":auto:", maxLen);
30137   OSTRACE(("GETLOCKPATH  proxy lock path=%s pid=%d\n", lPath, getpid()));
30138   return SQLITE_OK;
30139 }
30140
30141 /* 
30142  ** Creates the lock file and any missing directories in lockPath
30143  */
30144 static int proxyCreateLockPath(const char *lockPath){
30145   int i, len;
30146   char buf[MAXPATHLEN];
30147   int start = 0;
30148   
30149   assert(lockPath!=NULL);
30150   /* try to create all the intermediate directories */
30151   len = (int)strlen(lockPath);
30152   buf[0] = lockPath[0];
30153   for( i=1; i<len; i++ ){
30154     if( lockPath[i] == '/' && (i - start > 0) ){
30155       /* only mkdir if leaf dir != "." or "/" or ".." */
30156       if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/') 
30157          || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
30158         buf[i]='\0';
30159         if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
30160           int err=errno;
30161           if( err!=EEXIST ) {
30162             OSTRACE(("CREATELOCKPATH  FAILED creating %s, "
30163                      "'%s' proxy lock path=%s pid=%d\n",
30164                      buf, strerror(err), lockPath, getpid()));
30165             return err;
30166           }
30167         }
30168       }
30169       start=i+1;
30170     }
30171     buf[i] = lockPath[i];
30172   }
30173   OSTRACE(("CREATELOCKPATH  proxy lock path=%s pid=%d\n", lockPath, getpid()));
30174   return 0;
30175 }
30176
30177 /*
30178 ** Create a new VFS file descriptor (stored in memory obtained from
30179 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
30180 **
30181 ** The caller is responsible not only for closing the file descriptor
30182 ** but also for freeing the memory associated with the file descriptor.
30183 */
30184 static int proxyCreateUnixFile(
30185     const char *path,        /* path for the new unixFile */
30186     unixFile **ppFile,       /* unixFile created and returned by ref */
30187     int islockfile           /* if non zero missing dirs will be created */
30188 ) {
30189   int fd = -1;
30190   int dirfd = -1;
30191   unixFile *pNew;
30192   int rc = SQLITE_OK;
30193   int openFlags = O_RDWR | O_CREAT;
30194   sqlite3_vfs dummyVfs;
30195   int terrno = 0;
30196   UnixUnusedFd *pUnused = NULL;
30197
30198   /* 1. first try to open/create the file
30199   ** 2. if that fails, and this is a lock file (not-conch), try creating
30200   ** the parent directories and then try again.
30201   ** 3. if that fails, try to open the file read-only
30202   ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
30203   */
30204   pUnused = findReusableFd(path, openFlags);
30205   if( pUnused ){
30206     fd = pUnused->fd;
30207   }else{
30208     pUnused = sqlite3_malloc(sizeof(*pUnused));
30209     if( !pUnused ){
30210       return SQLITE_NOMEM;
30211     }
30212   }
30213   if( fd<0 ){
30214     fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
30215     terrno = errno;
30216     if( fd<0 && errno==ENOENT && islockfile ){
30217       if( proxyCreateLockPath(path) == SQLITE_OK ){
30218         fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
30219       }
30220     }
30221   }
30222   if( fd<0 ){
30223     openFlags = O_RDONLY;
30224     fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
30225     terrno = errno;
30226   }
30227   if( fd<0 ){
30228     if( islockfile ){
30229       return SQLITE_BUSY;
30230     }
30231     switch (terrno) {
30232       case EACCES:
30233         return SQLITE_PERM;
30234       case EIO: 
30235         return SQLITE_IOERR_LOCK; /* even though it is the conch */
30236       default:
30237         return SQLITE_CANTOPEN_BKPT;
30238     }
30239   }
30240   
30241   pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
30242   if( pNew==NULL ){
30243     rc = SQLITE_NOMEM;
30244     goto end_create_proxy;
30245   }
30246   memset(pNew, 0, sizeof(unixFile));
30247   pNew->openFlags = openFlags;
30248   memset(&dummyVfs, 0, sizeof(dummyVfs));
30249   dummyVfs.pAppData = (void*)&autolockIoFinder;
30250   dummyVfs.zName = "dummy";
30251   pUnused->fd = fd;
30252   pUnused->flags = openFlags;
30253   pNew->pUnused = pUnused;
30254   
30255   rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0, 0);
30256   if( rc==SQLITE_OK ){
30257     *ppFile = pNew;
30258     return SQLITE_OK;
30259   }
30260 end_create_proxy:    
30261   robust_close(pNew, fd, __LINE__);
30262   sqlite3_free(pNew);
30263   sqlite3_free(pUnused);
30264   return rc;
30265 }
30266
30267 #ifdef SQLITE_TEST
30268 /* simulate multiple hosts by creating unique hostid file paths */
30269 SQLITE_API int sqlite3_hostid_num = 0;
30270 #endif
30271
30272 #define PROXY_HOSTIDLEN    16  /* conch file host id length */
30273
30274 /* Not always defined in the headers as it ought to be */
30275 extern int gethostuuid(uuid_t id, const struct timespec *wait);
30276
30277 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN 
30278 ** bytes of writable memory.
30279 */
30280 static int proxyGetHostID(unsigned char *pHostID, int *pError){
30281   assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
30282   memset(pHostID, 0, PROXY_HOSTIDLEN);
30283 #if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
30284                && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
30285   {
30286     static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
30287     if( gethostuuid(pHostID, &timeout) ){
30288       int err = errno;
30289       if( pError ){
30290         *pError = err;
30291       }
30292       return SQLITE_IOERR;
30293     }
30294   }
30295 #endif
30296 #ifdef SQLITE_TEST
30297   /* simulate multiple hosts by creating unique hostid file paths */
30298   if( sqlite3_hostid_num != 0){
30299     pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
30300   }
30301 #endif
30302   
30303   return SQLITE_OK;
30304 }
30305
30306 /* The conch file contains the header, host id and lock file path
30307  */
30308 #define PROXY_CONCHVERSION 2   /* 1-byte header, 16-byte host id, path */
30309 #define PROXY_HEADERLEN    1   /* conch file header length */
30310 #define PROXY_PATHINDEX    (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
30311 #define PROXY_MAXCONCHLEN  (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
30312
30313 /* 
30314 ** Takes an open conch file, copies the contents to a new path and then moves 
30315 ** it back.  The newly created file's file descriptor is assigned to the
30316 ** conch file structure and finally the original conch file descriptor is 
30317 ** closed.  Returns zero if successful.
30318 */
30319 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
30320   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
30321   unixFile *conchFile = pCtx->conchFile;
30322   char tPath[MAXPATHLEN];
30323   char buf[PROXY_MAXCONCHLEN];
30324   char *cPath = pCtx->conchFilePath;
30325   size_t readLen = 0;
30326   size_t pathLen = 0;
30327   char errmsg[64] = "";
30328   int fd = -1;
30329   int rc = -1;
30330   UNUSED_PARAMETER(myHostID);
30331
30332   /* create a new path by replace the trailing '-conch' with '-break' */
30333   pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
30334   if( pathLen>MAXPATHLEN || pathLen<6 || 
30335      (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
30336     sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
30337     goto end_breaklock;
30338   }
30339   /* read the conch content */
30340   readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
30341   if( readLen<PROXY_PATHINDEX ){
30342     sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
30343     goto end_breaklock;
30344   }
30345   /* write it out to the temporary break file */
30346   fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL),
30347                    SQLITE_DEFAULT_FILE_PERMISSIONS);
30348   if( fd<0 ){
30349     sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
30350     goto end_breaklock;
30351   }
30352   if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
30353     sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
30354     goto end_breaklock;
30355   }
30356   if( rename(tPath, cPath) ){
30357     sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
30358     goto end_breaklock;
30359   }
30360   rc = 0;
30361   fprintf(stderr, "broke stale lock on %s\n", cPath);
30362   robust_close(pFile, conchFile->h, __LINE__);
30363   conchFile->h = fd;
30364   conchFile->openFlags = O_RDWR | O_CREAT;
30365
30366 end_breaklock:
30367   if( rc ){
30368     if( fd>=0 ){
30369       unlink(tPath);
30370       robust_close(pFile, fd, __LINE__);
30371     }
30372     fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
30373   }
30374   return rc;
30375 }
30376
30377 /* Take the requested lock on the conch file and break a stale lock if the 
30378 ** host id matches.
30379 */
30380 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
30381   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
30382   unixFile *conchFile = pCtx->conchFile;
30383   int rc = SQLITE_OK;
30384   int nTries = 0;
30385   struct timespec conchModTime;
30386   
30387   do {
30388     rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
30389     nTries ++;
30390     if( rc==SQLITE_BUSY ){
30391       /* If the lock failed (busy):
30392        * 1st try: get the mod time of the conch, wait 0.5s and try again. 
30393        * 2nd try: fail if the mod time changed or host id is different, wait 
30394        *           10 sec and try again
30395        * 3rd try: break the lock unless the mod time has changed.
30396        */
30397       struct stat buf;
30398       if( osFstat(conchFile->h, &buf) ){
30399         pFile->lastErrno = errno;
30400         return SQLITE_IOERR_LOCK;
30401       }
30402       
30403       if( nTries==1 ){
30404         conchModTime = buf.st_mtimespec;
30405         usleep(500000); /* wait 0.5 sec and try the lock again*/
30406         continue;  
30407       }
30408
30409       assert( nTries>1 );
30410       if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec || 
30411          conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
30412         return SQLITE_BUSY;
30413       }
30414       
30415       if( nTries==2 ){  
30416         char tBuf[PROXY_MAXCONCHLEN];
30417         int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
30418         if( len<0 ){
30419           pFile->lastErrno = errno;
30420           return SQLITE_IOERR_LOCK;
30421         }
30422         if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
30423           /* don't break the lock if the host id doesn't match */
30424           if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
30425             return SQLITE_BUSY;
30426           }
30427         }else{
30428           /* don't break the lock on short read or a version mismatch */
30429           return SQLITE_BUSY;
30430         }
30431         usleep(10000000); /* wait 10 sec and try the lock again */
30432         continue; 
30433       }
30434       
30435       assert( nTries==3 );
30436       if( 0==proxyBreakConchLock(pFile, myHostID) ){
30437         rc = SQLITE_OK;
30438         if( lockType==EXCLUSIVE_LOCK ){
30439           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);          
30440         }
30441         if( !rc ){
30442           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
30443         }
30444       }
30445     }
30446   } while( rc==SQLITE_BUSY && nTries<3 );
30447   
30448   return rc;
30449 }
30450
30451 /* Takes the conch by taking a shared lock and read the contents conch, if 
30452 ** lockPath is non-NULL, the host ID and lock file path must match.  A NULL 
30453 ** lockPath means that the lockPath in the conch file will be used if the 
30454 ** host IDs match, or a new lock path will be generated automatically 
30455 ** and written to the conch file.
30456 */
30457 static int proxyTakeConch(unixFile *pFile){
30458   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
30459   
30460   if( pCtx->conchHeld!=0 ){
30461     return SQLITE_OK;
30462   }else{
30463     unixFile *conchFile = pCtx->conchFile;
30464     uuid_t myHostID;
30465     int pError = 0;
30466     char readBuf[PROXY_MAXCONCHLEN];
30467     char lockPath[MAXPATHLEN];
30468     char *tempLockPath = NULL;
30469     int rc = SQLITE_OK;
30470     int createConch = 0;
30471     int hostIdMatch = 0;
30472     int readLen = 0;
30473     int tryOldLockPath = 0;
30474     int forceNewLockPath = 0;
30475     
30476     OSTRACE(("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
30477              (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
30478
30479     rc = proxyGetHostID(myHostID, &pError);
30480     if( (rc&0xff)==SQLITE_IOERR ){
30481       pFile->lastErrno = pError;
30482       goto end_takeconch;
30483     }
30484     rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
30485     if( rc!=SQLITE_OK ){
30486       goto end_takeconch;
30487     }
30488     /* read the existing conch file */
30489     readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
30490     if( readLen<0 ){
30491       /* I/O error: lastErrno set by seekAndRead */
30492       pFile->lastErrno = conchFile->lastErrno;
30493       rc = SQLITE_IOERR_READ;
30494       goto end_takeconch;
30495     }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) || 
30496              readBuf[0]!=(char)PROXY_CONCHVERSION ){
30497       /* a short read or version format mismatch means we need to create a new 
30498       ** conch file. 
30499       */
30500       createConch = 1;
30501     }
30502     /* if the host id matches and the lock path already exists in the conch
30503     ** we'll try to use the path there, if we can't open that path, we'll 
30504     ** retry with a new auto-generated path 
30505     */
30506     do { /* in case we need to try again for an :auto: named lock file */
30507
30508       if( !createConch && !forceNewLockPath ){
30509         hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID, 
30510                                   PROXY_HOSTIDLEN);
30511         /* if the conch has data compare the contents */
30512         if( !pCtx->lockProxyPath ){
30513           /* for auto-named local lock file, just check the host ID and we'll
30514            ** use the local lock file path that's already in there
30515            */
30516           if( hostIdMatch ){
30517             size_t pathLen = (readLen - PROXY_PATHINDEX);
30518             
30519             if( pathLen>=MAXPATHLEN ){
30520               pathLen=MAXPATHLEN-1;
30521             }
30522             memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
30523             lockPath[pathLen] = 0;
30524             tempLockPath = lockPath;
30525             tryOldLockPath = 1;
30526             /* create a copy of the lock path if the conch is taken */
30527             goto end_takeconch;
30528           }
30529         }else if( hostIdMatch
30530                && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
30531                            readLen-PROXY_PATHINDEX)
30532         ){
30533           /* conch host and lock path match */
30534           goto end_takeconch; 
30535         }
30536       }
30537       
30538       /* if the conch isn't writable and doesn't match, we can't take it */
30539       if( (conchFile->openFlags&O_RDWR) == 0 ){
30540         rc = SQLITE_BUSY;
30541         goto end_takeconch;
30542       }
30543       
30544       /* either the conch didn't match or we need to create a new one */
30545       if( !pCtx->lockProxyPath ){
30546         proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
30547         tempLockPath = lockPath;
30548         /* create a copy of the lock path _only_ if the conch is taken */
30549       }
30550       
30551       /* update conch with host and path (this will fail if other process
30552       ** has a shared lock already), if the host id matches, use the big
30553       ** stick.
30554       */
30555       futimes(conchFile->h, NULL);
30556       if( hostIdMatch && !createConch ){
30557         if( conchFile->pInode && conchFile->pInode->nShared>1 ){
30558           /* We are trying for an exclusive lock but another thread in this
30559            ** same process is still holding a shared lock. */
30560           rc = SQLITE_BUSY;
30561         } else {          
30562           rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
30563         }
30564       }else{
30565         rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
30566       }
30567       if( rc==SQLITE_OK ){
30568         char writeBuffer[PROXY_MAXCONCHLEN];
30569         int writeSize = 0;
30570         
30571         writeBuffer[0] = (char)PROXY_CONCHVERSION;
30572         memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
30573         if( pCtx->lockProxyPath!=NULL ){
30574           strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
30575         }else{
30576           strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
30577         }
30578         writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
30579         robust_ftruncate(conchFile->h, writeSize);
30580         rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
30581         fsync(conchFile->h);
30582         /* If we created a new conch file (not just updated the contents of a 
30583          ** valid conch file), try to match the permissions of the database 
30584          */
30585         if( rc==SQLITE_OK && createConch ){
30586           struct stat buf;
30587           int err = osFstat(pFile->h, &buf);
30588           if( err==0 ){
30589             mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
30590                                         S_IROTH|S_IWOTH);
30591             /* try to match the database file R/W permissions, ignore failure */
30592 #ifndef SQLITE_PROXY_DEBUG
30593             osFchmod(conchFile->h, cmode);
30594 #else
30595             do{
30596               rc = osFchmod(conchFile->h, cmode);
30597             }while( rc==(-1) && errno==EINTR );
30598             if( rc!=0 ){
30599               int code = errno;
30600               fprintf(stderr, "fchmod %o FAILED with %d %s\n",
30601                       cmode, code, strerror(code));
30602             } else {
30603               fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
30604             }
30605           }else{
30606             int code = errno;
30607             fprintf(stderr, "STAT FAILED[%d] with %d %s\n", 
30608                     err, code, strerror(code));
30609 #endif
30610           }
30611         }
30612       }
30613       conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
30614       
30615     end_takeconch:
30616       OSTRACE(("TRANSPROXY: CLOSE  %d\n", pFile->h));
30617       if( rc==SQLITE_OK && pFile->openFlags ){
30618         if( pFile->h>=0 ){
30619           robust_close(pFile, pFile->h, __LINE__);
30620         }
30621         pFile->h = -1;
30622         int fd = robust_open(pCtx->dbPath, pFile->openFlags,
30623                       SQLITE_DEFAULT_FILE_PERMISSIONS);
30624         OSTRACE(("TRANSPROXY: OPEN  %d\n", fd));
30625         if( fd>=0 ){
30626           pFile->h = fd;
30627         }else{
30628           rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
30629            during locking */
30630         }
30631       }
30632       if( rc==SQLITE_OK && !pCtx->lockProxy ){
30633         char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
30634         rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
30635         if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
30636           /* we couldn't create the proxy lock file with the old lock file path
30637            ** so try again via auto-naming 
30638            */
30639           forceNewLockPath = 1;
30640           tryOldLockPath = 0;
30641           continue; /* go back to the do {} while start point, try again */
30642         }
30643       }
30644       if( rc==SQLITE_OK ){
30645         /* Need to make a copy of path if we extracted the value
30646          ** from the conch file or the path was allocated on the stack
30647          */
30648         if( tempLockPath ){
30649           pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
30650           if( !pCtx->lockProxyPath ){
30651             rc = SQLITE_NOMEM;
30652           }
30653         }
30654       }
30655       if( rc==SQLITE_OK ){
30656         pCtx->conchHeld = 1;
30657         
30658         if( pCtx->lockProxy->pMethod == &afpIoMethods ){
30659           afpLockingContext *afpCtx;
30660           afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
30661           afpCtx->dbPath = pCtx->lockProxyPath;
30662         }
30663       } else {
30664         conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
30665       }
30666       OSTRACE(("TAKECONCH  %d %s\n", conchFile->h,
30667                rc==SQLITE_OK?"ok":"failed"));
30668       return rc;
30669     } while (1); /* in case we need to retry the :auto: lock file - 
30670                  ** we should never get here except via the 'continue' call. */
30671   }
30672 }
30673
30674 /*
30675 ** If pFile holds a lock on a conch file, then release that lock.
30676 */
30677 static int proxyReleaseConch(unixFile *pFile){
30678   int rc = SQLITE_OK;         /* Subroutine return code */
30679   proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
30680   unixFile *conchFile;        /* Name of the conch file */
30681
30682   pCtx = (proxyLockingContext *)pFile->lockingContext;
30683   conchFile = pCtx->conchFile;
30684   OSTRACE(("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
30685            (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), 
30686            getpid()));
30687   if( pCtx->conchHeld>0 ){
30688     rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
30689   }
30690   pCtx->conchHeld = 0;
30691   OSTRACE(("RELEASECONCH  %d %s\n", conchFile->h,
30692            (rc==SQLITE_OK ? "ok" : "failed")));
30693   return rc;
30694 }
30695
30696 /*
30697 ** Given the name of a database file, compute the name of its conch file.
30698 ** Store the conch filename in memory obtained from sqlite3_malloc().
30699 ** Make *pConchPath point to the new name.  Return SQLITE_OK on success
30700 ** or SQLITE_NOMEM if unable to obtain memory.
30701 **
30702 ** The caller is responsible for ensuring that the allocated memory
30703 ** space is eventually freed.
30704 **
30705 ** *pConchPath is set to NULL if a memory allocation error occurs.
30706 */
30707 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
30708   int i;                        /* Loop counter */
30709   int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
30710   char *conchPath;              /* buffer in which to construct conch name */
30711
30712   /* Allocate space for the conch filename and initialize the name to
30713   ** the name of the original database file. */  
30714   *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
30715   if( conchPath==0 ){
30716     return SQLITE_NOMEM;
30717   }
30718   memcpy(conchPath, dbPath, len+1);
30719   
30720   /* now insert a "." before the last / character */
30721   for( i=(len-1); i>=0; i-- ){
30722     if( conchPath[i]=='/' ){
30723       i++;
30724       break;
30725     }
30726   }
30727   conchPath[i]='.';
30728   while ( i<len ){
30729     conchPath[i+1]=dbPath[i];
30730     i++;
30731   }
30732
30733   /* append the "-conch" suffix to the file */
30734   memcpy(&conchPath[i+1], "-conch", 7);
30735   assert( (int)strlen(conchPath) == len+7 );
30736
30737   return SQLITE_OK;
30738 }
30739
30740
30741 /* Takes a fully configured proxy locking-style unix file and switches
30742 ** the local lock file path 
30743 */
30744 static int switchLockProxyPath(unixFile *pFile, const char *path) {
30745   proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
30746   char *oldPath = pCtx->lockProxyPath;
30747   int rc = SQLITE_OK;
30748
30749   if( pFile->eFileLock!=NO_LOCK ){
30750     return SQLITE_BUSY;
30751   }  
30752
30753   /* nothing to do if the path is NULL, :auto: or matches the existing path */
30754   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
30755     (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
30756     return SQLITE_OK;
30757   }else{
30758     unixFile *lockProxy = pCtx->lockProxy;
30759     pCtx->lockProxy=NULL;
30760     pCtx->conchHeld = 0;
30761     if( lockProxy!=NULL ){
30762       rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
30763       if( rc ) return rc;
30764       sqlite3_free(lockProxy);
30765     }
30766     sqlite3_free(oldPath);
30767     pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
30768   }
30769   
30770   return rc;
30771 }
30772
30773 /*
30774 ** pFile is a file that has been opened by a prior xOpen call.  dbPath
30775 ** is a string buffer at least MAXPATHLEN+1 characters in size.
30776 **
30777 ** This routine find the filename associated with pFile and writes it
30778 ** int dbPath.
30779 */
30780 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
30781 #if defined(__APPLE__)
30782   if( pFile->pMethod == &afpIoMethods ){
30783     /* afp style keeps a reference to the db path in the filePath field 
30784     ** of the struct */
30785     assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
30786     strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
30787   } else
30788 #endif
30789   if( pFile->pMethod == &dotlockIoMethods ){
30790     /* dot lock style uses the locking context to store the dot lock
30791     ** file path */
30792     int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
30793     memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
30794   }else{
30795     /* all other styles use the locking context to store the db file path */
30796     assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
30797     strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
30798   }
30799   return SQLITE_OK;
30800 }
30801
30802 /*
30803 ** Takes an already filled in unix file and alters it so all file locking 
30804 ** will be performed on the local proxy lock file.  The following fields
30805 ** are preserved in the locking context so that they can be restored and 
30806 ** the unix structure properly cleaned up at close time:
30807 **  ->lockingContext
30808 **  ->pMethod
30809 */
30810 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
30811   proxyLockingContext *pCtx;
30812   char dbPath[MAXPATHLEN+1];       /* Name of the database file */
30813   char *lockPath=NULL;
30814   int rc = SQLITE_OK;
30815   
30816   if( pFile->eFileLock!=NO_LOCK ){
30817     return SQLITE_BUSY;
30818   }
30819   proxyGetDbPathForUnixFile(pFile, dbPath);
30820   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
30821     lockPath=NULL;
30822   }else{
30823     lockPath=(char *)path;
30824   }
30825   
30826   OSTRACE(("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
30827            (lockPath ? lockPath : ":auto:"), getpid()));
30828
30829   pCtx = sqlite3_malloc( sizeof(*pCtx) );
30830   if( pCtx==0 ){
30831     return SQLITE_NOMEM;
30832   }
30833   memset(pCtx, 0, sizeof(*pCtx));
30834
30835   rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
30836   if( rc==SQLITE_OK ){
30837     rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
30838     if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
30839       /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
30840       ** (c) the file system is read-only, then enable no-locking access.
30841       ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
30842       ** that openFlags will have only one of O_RDONLY or O_RDWR.
30843       */
30844       struct statfs fsInfo;
30845       struct stat conchInfo;
30846       int goLockless = 0;
30847
30848       if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
30849         int err = errno;
30850         if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
30851           goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
30852         }
30853       }
30854       if( goLockless ){
30855         pCtx->conchHeld = -1; /* read only FS/ lockless */
30856         rc = SQLITE_OK;
30857       }
30858     }
30859   }  
30860   if( rc==SQLITE_OK && lockPath ){
30861     pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
30862   }
30863
30864   if( rc==SQLITE_OK ){
30865     pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
30866     if( pCtx->dbPath==NULL ){
30867       rc = SQLITE_NOMEM;
30868     }
30869   }
30870   if( rc==SQLITE_OK ){
30871     /* all memory is allocated, proxys are created and assigned, 
30872     ** switch the locking context and pMethod then return.
30873     */
30874     pCtx->oldLockingContext = pFile->lockingContext;
30875     pFile->lockingContext = pCtx;
30876     pCtx->pOldMethod = pFile->pMethod;
30877     pFile->pMethod = &proxyIoMethods;
30878   }else{
30879     if( pCtx->conchFile ){ 
30880       pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
30881       sqlite3_free(pCtx->conchFile);
30882     }
30883     sqlite3DbFree(0, pCtx->lockProxyPath);
30884     sqlite3_free(pCtx->conchFilePath); 
30885     sqlite3_free(pCtx);
30886   }
30887   OSTRACE(("TRANSPROXY  %d %s\n", pFile->h,
30888            (rc==SQLITE_OK ? "ok" : "failed")));
30889   return rc;
30890 }
30891
30892
30893 /*
30894 ** This routine handles sqlite3_file_control() calls that are specific
30895 ** to proxy locking.
30896 */
30897 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
30898   switch( op ){
30899     case SQLITE_GET_LOCKPROXYFILE: {
30900       unixFile *pFile = (unixFile*)id;
30901       if( pFile->pMethod == &proxyIoMethods ){
30902         proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
30903         proxyTakeConch(pFile);
30904         if( pCtx->lockProxyPath ){
30905           *(const char **)pArg = pCtx->lockProxyPath;
30906         }else{
30907           *(const char **)pArg = ":auto: (not held)";
30908         }
30909       } else {
30910         *(const char **)pArg = NULL;
30911       }
30912       return SQLITE_OK;
30913     }
30914     case SQLITE_SET_LOCKPROXYFILE: {
30915       unixFile *pFile = (unixFile*)id;
30916       int rc = SQLITE_OK;
30917       int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
30918       if( pArg==NULL || (const char *)pArg==0 ){
30919         if( isProxyStyle ){
30920           /* turn off proxy locking - not supported */
30921           rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
30922         }else{
30923           /* turn off proxy locking - already off - NOOP */
30924           rc = SQLITE_OK;
30925         }
30926       }else{
30927         const char *proxyPath = (const char *)pArg;
30928         if( isProxyStyle ){
30929           proxyLockingContext *pCtx = 
30930             (proxyLockingContext*)pFile->lockingContext;
30931           if( !strcmp(pArg, ":auto:") 
30932            || (pCtx->lockProxyPath &&
30933                !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
30934           ){
30935             rc = SQLITE_OK;
30936           }else{
30937             rc = switchLockProxyPath(pFile, proxyPath);
30938           }
30939         }else{
30940           /* turn on proxy file locking */
30941           rc = proxyTransformUnixFile(pFile, proxyPath);
30942         }
30943       }
30944       return rc;
30945     }
30946     default: {
30947       assert( 0 );  /* The call assures that only valid opcodes are sent */
30948     }
30949   }
30950   /*NOTREACHED*/
30951   return SQLITE_ERROR;
30952 }
30953
30954 /*
30955 ** Within this division (the proxying locking implementation) the procedures
30956 ** above this point are all utilities.  The lock-related methods of the
30957 ** proxy-locking sqlite3_io_method object follow.
30958 */
30959
30960
30961 /*
30962 ** This routine checks if there is a RESERVED lock held on the specified
30963 ** file by this or any other process. If such a lock is held, set *pResOut
30964 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
30965 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
30966 */
30967 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
30968   unixFile *pFile = (unixFile*)id;
30969   int rc = proxyTakeConch(pFile);
30970   if( rc==SQLITE_OK ){
30971     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30972     if( pCtx->conchHeld>0 ){
30973       unixFile *proxy = pCtx->lockProxy;
30974       return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
30975     }else{ /* conchHeld < 0 is lockless */
30976       pResOut=0;
30977     }
30978   }
30979   return rc;
30980 }
30981
30982 /*
30983 ** Lock the file with the lock specified by parameter eFileLock - one
30984 ** of the following:
30985 **
30986 **     (1) SHARED_LOCK
30987 **     (2) RESERVED_LOCK
30988 **     (3) PENDING_LOCK
30989 **     (4) EXCLUSIVE_LOCK
30990 **
30991 ** Sometimes when requesting one lock state, additional lock states
30992 ** are inserted in between.  The locking might fail on one of the later
30993 ** transitions leaving the lock state different from what it started but
30994 ** still short of its goal.  The following chart shows the allowed
30995 ** transitions and the inserted intermediate states:
30996 **
30997 **    UNLOCKED -> SHARED
30998 **    SHARED -> RESERVED
30999 **    SHARED -> (PENDING) -> EXCLUSIVE
31000 **    RESERVED -> (PENDING) -> EXCLUSIVE
31001 **    PENDING -> EXCLUSIVE
31002 **
31003 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
31004 ** routine to lower a locking level.
31005 */
31006 static int proxyLock(sqlite3_file *id, int eFileLock) {
31007   unixFile *pFile = (unixFile*)id;
31008   int rc = proxyTakeConch(pFile);
31009   if( rc==SQLITE_OK ){
31010     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
31011     if( pCtx->conchHeld>0 ){
31012       unixFile *proxy = pCtx->lockProxy;
31013       rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
31014       pFile->eFileLock = proxy->eFileLock;
31015     }else{
31016       /* conchHeld < 0 is lockless */
31017     }
31018   }
31019   return rc;
31020 }
31021
31022
31023 /*
31024 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
31025 ** must be either NO_LOCK or SHARED_LOCK.
31026 **
31027 ** If the locking level of the file descriptor is already at or below
31028 ** the requested locking level, this routine is a no-op.
31029 */
31030 static int proxyUnlock(sqlite3_file *id, int eFileLock) {
31031   unixFile *pFile = (unixFile*)id;
31032   int rc = proxyTakeConch(pFile);
31033   if( rc==SQLITE_OK ){
31034     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
31035     if( pCtx->conchHeld>0 ){
31036       unixFile *proxy = pCtx->lockProxy;
31037       rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
31038       pFile->eFileLock = proxy->eFileLock;
31039     }else{
31040       /* conchHeld < 0 is lockless */
31041     }
31042   }
31043   return rc;
31044 }
31045
31046 /*
31047 ** Close a file that uses proxy locks.
31048 */
31049 static int proxyClose(sqlite3_file *id) {
31050   if( id ){
31051     unixFile *pFile = (unixFile*)id;
31052     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
31053     unixFile *lockProxy = pCtx->lockProxy;
31054     unixFile *conchFile = pCtx->conchFile;
31055     int rc = SQLITE_OK;
31056     
31057     if( lockProxy ){
31058       rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
31059       if( rc ) return rc;
31060       rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
31061       if( rc ) return rc;
31062       sqlite3_free(lockProxy);
31063       pCtx->lockProxy = 0;
31064     }
31065     if( conchFile ){
31066       if( pCtx->conchHeld ){
31067         rc = proxyReleaseConch(pFile);
31068         if( rc ) return rc;
31069       }
31070       rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
31071       if( rc ) return rc;
31072       sqlite3_free(conchFile);
31073     }
31074     sqlite3DbFree(0, pCtx->lockProxyPath);
31075     sqlite3_free(pCtx->conchFilePath);
31076     sqlite3DbFree(0, pCtx->dbPath);
31077     /* restore the original locking context and pMethod then close it */
31078     pFile->lockingContext = pCtx->oldLockingContext;
31079     pFile->pMethod = pCtx->pOldMethod;
31080     sqlite3_free(pCtx);
31081     return pFile->pMethod->xClose(id);
31082   }
31083   return SQLITE_OK;
31084 }
31085
31086
31087
31088 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
31089 /*
31090 ** The proxy locking style is intended for use with AFP filesystems.
31091 ** And since AFP is only supported on MacOSX, the proxy locking is also
31092 ** restricted to MacOSX.
31093 ** 
31094 **
31095 ******************* End of the proxy lock implementation **********************
31096 ******************************************************************************/
31097
31098 /*
31099 ** Initialize the operating system interface.
31100 **
31101 ** This routine registers all VFS implementations for unix-like operating
31102 ** systems.  This routine, and the sqlite3_os_end() routine that follows,
31103 ** should be the only routines in this file that are visible from other
31104 ** files.
31105 **
31106 ** This routine is called once during SQLite initialization and by a
31107 ** single thread.  The memory allocation and mutex subsystems have not
31108 ** necessarily been initialized when this routine is called, and so they
31109 ** should not be used.
31110 */
31111 SQLITE_API int sqlite3_os_init(void){ 
31112   /* 
31113   ** The following macro defines an initializer for an sqlite3_vfs object.
31114   ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
31115   ** to the "finder" function.  (pAppData is a pointer to a pointer because
31116   ** silly C90 rules prohibit a void* from being cast to a function pointer
31117   ** and so we have to go through the intermediate pointer to avoid problems
31118   ** when compiling with -pedantic-errors on GCC.)
31119   **
31120   ** The FINDER parameter to this macro is the name of the pointer to the
31121   ** finder-function.  The finder-function returns a pointer to the
31122   ** sqlite_io_methods object that implements the desired locking
31123   ** behaviors.  See the division above that contains the IOMETHODS
31124   ** macro for addition information on finder-functions.
31125   **
31126   ** Most finders simply return a pointer to a fixed sqlite3_io_methods
31127   ** object.  But the "autolockIoFinder" available on MacOSX does a little
31128   ** more than that; it looks at the filesystem type that hosts the 
31129   ** database file and tries to choose an locking method appropriate for
31130   ** that filesystem time.
31131   */
31132   #define UNIXVFS(VFSNAME, FINDER) {                        \
31133     3,                    /* iVersion */                    \
31134     sizeof(unixFile),     /* szOsFile */                    \
31135     MAX_PATHNAME,         /* mxPathname */                  \
31136     0,                    /* pNext */                       \
31137     VFSNAME,              /* zName */                       \
31138     (void*)&FINDER,       /* pAppData */                    \
31139     unixOpen,             /* xOpen */                       \
31140     unixDelete,           /* xDelete */                     \
31141     unixAccess,           /* xAccess */                     \
31142     unixFullPathname,     /* xFullPathname */               \
31143     unixDlOpen,           /* xDlOpen */                     \
31144     unixDlError,          /* xDlError */                    \
31145     unixDlSym,            /* xDlSym */                      \
31146     unixDlClose,          /* xDlClose */                    \
31147     unixRandomness,       /* xRandomness */                 \
31148     unixSleep,            /* xSleep */                      \
31149     unixCurrentTime,      /* xCurrentTime */                \
31150     unixGetLastError,     /* xGetLastError */               \
31151     unixCurrentTimeInt64, /* xCurrentTimeInt64 */           \
31152     unixSetSystemCall,    /* xSetSystemCall */              \
31153     unixGetSystemCall,    /* xGetSystemCall */              \
31154     unixNextSystemCall,   /* xNextSystemCall */             \
31155   }
31156
31157   /*
31158   ** All default VFSes for unix are contained in the following array.
31159   **
31160   ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
31161   ** by the SQLite core when the VFS is registered.  So the following
31162   ** array cannot be const.
31163   */
31164   static sqlite3_vfs aVfs[] = {
31165 #if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
31166     UNIXVFS("unix",          autolockIoFinder ),
31167 #else
31168     UNIXVFS("unix",          posixIoFinder ),
31169 #endif
31170     UNIXVFS("unix-none",     nolockIoFinder ),
31171     UNIXVFS("unix-dotfile",  dotlockIoFinder ),
31172     UNIXVFS("unix-excl",     posixIoFinder ),
31173 #if OS_VXWORKS
31174     UNIXVFS("unix-namedsem", semIoFinder ),
31175 #endif
31176 #if SQLITE_ENABLE_LOCKING_STYLE
31177     UNIXVFS("unix-posix",    posixIoFinder ),
31178 #if !OS_VXWORKS
31179     UNIXVFS("unix-flock",    flockIoFinder ),
31180 #endif
31181 #endif
31182 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
31183     UNIXVFS("unix-afp",      afpIoFinder ),
31184     UNIXVFS("unix-nfs",      nfsIoFinder ),
31185     UNIXVFS("unix-proxy",    proxyIoFinder ),
31186 #endif
31187   };
31188   unsigned int i;          /* Loop counter */
31189
31190   /* Double-check that the aSyscall[] array has been constructed
31191   ** correctly.  See ticket [bb3a86e890c8e96ab] */
31192   assert( ArraySize(aSyscall)==16 );
31193
31194   /* Register all VFSes defined in the aVfs[] array */
31195   for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
31196     sqlite3_vfs_register(&aVfs[i], i==0);
31197   }
31198   return SQLITE_OK; 
31199 }
31200
31201 /*
31202 ** Shutdown the operating system interface.
31203 **
31204 ** Some operating systems might need to do some cleanup in this routine,
31205 ** to release dynamically allocated objects.  But not on unix.
31206 ** This routine is a no-op for unix.
31207 */
31208 SQLITE_API int sqlite3_os_end(void){ 
31209   return SQLITE_OK; 
31210 }
31211  
31212 #endif /* SQLITE_OS_UNIX */
31213
31214 /************** End of os_unix.c *********************************************/
31215 /************** Begin file os_win.c ******************************************/
31216 /*
31217 ** 2004 May 22
31218 **
31219 ** The author disclaims copyright to this source code.  In place of
31220 ** a legal notice, here is a blessing:
31221 **
31222 **    May you do good and not evil.
31223 **    May you find forgiveness for yourself and forgive others.
31224 **    May you share freely, never taking more than you give.
31225 **
31226 ******************************************************************************
31227 **
31228 ** This file contains code that is specific to windows.
31229 */
31230 #if SQLITE_OS_WIN               /* This file is used for windows only */
31231
31232
31233 /*
31234 ** A Note About Memory Allocation:
31235 **
31236 ** This driver uses malloc()/free() directly rather than going through
31237 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
31238 ** are designed for use on embedded systems where memory is scarce and
31239 ** malloc failures happen frequently.  Win32 does not typically run on
31240 ** embedded systems, and when it does the developers normally have bigger
31241 ** problems to worry about than running out of memory.  So there is not
31242 ** a compelling need to use the wrappers.
31243 **
31244 ** But there is a good reason to not use the wrappers.  If we use the
31245 ** wrappers then we will get simulated malloc() failures within this
31246 ** driver.  And that causes all kinds of problems for our tests.  We
31247 ** could enhance SQLite to deal with simulated malloc failures within
31248 ** the OS driver, but the code to deal with those failure would not
31249 ** be exercised on Linux (which does not need to malloc() in the driver)
31250 ** and so we would have difficulty writing coverage tests for that
31251 ** code.  Better to leave the code out, we think.
31252 **
31253 ** The point of this discussion is as follows:  When creating a new
31254 ** OS layer for an embedded system, if you use this file as an example,
31255 ** avoid the use of malloc()/free().  Those routines work ok on windows
31256 ** desktops but not so well in embedded systems.
31257 */
31258
31259 #include <winbase.h>
31260
31261 #ifdef __CYGWIN__
31262 # include <sys/cygwin.h>
31263 #endif
31264
31265 /*
31266 ** Macros used to determine whether or not to use threads.
31267 */
31268 #if defined(THREADSAFE) && THREADSAFE
31269 # define SQLITE_W32_THREADS 1
31270 #endif
31271
31272 /*
31273 ** Include code that is common to all os_*.c files
31274 */
31275 /************** Include os_common.h in the middle of os_win.c ****************/
31276 /************** Begin file os_common.h ***************************************/
31277 /*
31278 ** 2004 May 22
31279 **
31280 ** The author disclaims copyright to this source code.  In place of
31281 ** a legal notice, here is a blessing:
31282 **
31283 **    May you do good and not evil.
31284 **    May you find forgiveness for yourself and forgive others.
31285 **    May you share freely, never taking more than you give.
31286 **
31287 ******************************************************************************
31288 **
31289 ** This file contains macros and a little bit of code that is common to
31290 ** all of the platform-specific files (os_*.c) and is #included into those
31291 ** files.
31292 **
31293 ** This file should be #included by the os_*.c files only.  It is not a
31294 ** general purpose header file.
31295 */
31296 #ifndef _OS_COMMON_H_
31297 #define _OS_COMMON_H_
31298
31299 /*
31300 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
31301 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
31302 ** switch.  The following code should catch this problem at compile-time.
31303 */
31304 #ifdef MEMORY_DEBUG
31305 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
31306 #endif
31307
31308 #ifdef SQLITE_DEBUG
31309 SQLITE_PRIVATE int sqlite3OSTrace = 0;
31310 #define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
31311 #else
31312 #define OSTRACE(X)
31313 #endif
31314
31315 /*
31316 ** Macros for performance tracing.  Normally turned off.  Only works
31317 ** on i486 hardware.
31318 */
31319 #ifdef SQLITE_PERFORMANCE_TRACE
31320
31321 /* 
31322 ** hwtime.h contains inline assembler code for implementing 
31323 ** high-performance timing routines.
31324 */
31325 /************** Include hwtime.h in the middle of os_common.h ****************/
31326 /************** Begin file hwtime.h ******************************************/
31327 /*
31328 ** 2008 May 27
31329 **
31330 ** The author disclaims copyright to this source code.  In place of
31331 ** a legal notice, here is a blessing:
31332 **
31333 **    May you do good and not evil.
31334 **    May you find forgiveness for yourself and forgive others.
31335 **    May you share freely, never taking more than you give.
31336 **
31337 ******************************************************************************
31338 **
31339 ** This file contains inline asm code for retrieving "high-performance"
31340 ** counters for x86 class CPUs.
31341 */
31342 #ifndef _HWTIME_H_
31343 #define _HWTIME_H_
31344
31345 /*
31346 ** The following routine only works on pentium-class (or newer) processors.
31347 ** It uses the RDTSC opcode to read the cycle count value out of the
31348 ** processor and returns that value.  This can be used for high-res
31349 ** profiling.
31350 */
31351 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
31352       (defined(i386) || defined(__i386__) || defined(_M_IX86))
31353
31354   #if defined(__GNUC__)
31355
31356   __inline__ sqlite_uint64 sqlite3Hwtime(void){
31357      unsigned int lo, hi;
31358      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
31359      return (sqlite_uint64)hi << 32 | lo;
31360   }
31361
31362   #elif defined(_MSC_VER)
31363
31364   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
31365      __asm {
31366         rdtsc
31367         ret       ; return value at EDX:EAX
31368      }
31369   }
31370
31371   #endif
31372
31373 #elif (defined(__GNUC__) && defined(__x86_64__))
31374
31375   __inline__ sqlite_uint64 sqlite3Hwtime(void){
31376       unsigned long val;
31377       __asm__ __volatile__ ("rdtsc" : "=A" (val));
31378       return val;
31379   }
31380  
31381 #elif (defined(__GNUC__) && defined(__ppc__))
31382
31383   __inline__ sqlite_uint64 sqlite3Hwtime(void){
31384       unsigned long long retval;
31385       unsigned long junk;
31386       __asm__ __volatile__ ("\n\
31387           1:      mftbu   %1\n\
31388                   mftb    %L0\n\
31389                   mftbu   %0\n\
31390                   cmpw    %0,%1\n\
31391                   bne     1b"
31392                   : "=r" (retval), "=r" (junk));
31393       return retval;
31394   }
31395
31396 #else
31397
31398   #error Need implementation of sqlite3Hwtime() for your platform.
31399
31400   /*
31401   ** To compile without implementing sqlite3Hwtime() for your platform,
31402   ** you can remove the above #error and use the following
31403   ** stub function.  You will lose timing support for many
31404   ** of the debugging and testing utilities, but it should at
31405   ** least compile and run.
31406   */
31407 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
31408
31409 #endif
31410
31411 #endif /* !defined(_HWTIME_H_) */
31412
31413 /************** End of hwtime.h **********************************************/
31414 /************** Continuing where we left off in os_common.h ******************/
31415
31416 static sqlite_uint64 g_start;
31417 static sqlite_uint64 g_elapsed;
31418 #define TIMER_START       g_start=sqlite3Hwtime()
31419 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
31420 #define TIMER_ELAPSED     g_elapsed
31421 #else
31422 #define TIMER_START
31423 #define TIMER_END
31424 #define TIMER_ELAPSED     ((sqlite_uint64)0)
31425 #endif
31426
31427 /*
31428 ** If we compile with the SQLITE_TEST macro set, then the following block
31429 ** of code will give us the ability to simulate a disk I/O error.  This
31430 ** is used for testing the I/O recovery logic.
31431 */
31432 #ifdef SQLITE_TEST
31433 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
31434 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
31435 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
31436 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
31437 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
31438 SQLITE_API int sqlite3_diskfull_pending = 0;
31439 SQLITE_API int sqlite3_diskfull = 0;
31440 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
31441 #define SimulateIOError(CODE)  \
31442   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
31443        || sqlite3_io_error_pending-- == 1 )  \
31444               { local_ioerr(); CODE; }
31445 static void local_ioerr(){
31446   IOTRACE(("IOERR\n"));
31447   sqlite3_io_error_hit++;
31448   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
31449 }
31450 #define SimulateDiskfullError(CODE) \
31451    if( sqlite3_diskfull_pending ){ \
31452      if( sqlite3_diskfull_pending == 1 ){ \
31453        local_ioerr(); \
31454        sqlite3_diskfull = 1; \
31455        sqlite3_io_error_hit = 1; \
31456        CODE; \
31457      }else{ \
31458        sqlite3_diskfull_pending--; \
31459      } \
31460    }
31461 #else
31462 #define SimulateIOErrorBenign(X)
31463 #define SimulateIOError(A)
31464 #define SimulateDiskfullError(A)
31465 #endif
31466
31467 /*
31468 ** When testing, keep a count of the number of open files.
31469 */
31470 #ifdef SQLITE_TEST
31471 SQLITE_API int sqlite3_open_file_count = 0;
31472 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
31473 #else
31474 #define OpenCounter(X)
31475 #endif
31476
31477 #endif /* !defined(_OS_COMMON_H_) */
31478
31479 /************** End of os_common.h *******************************************/
31480 /************** Continuing where we left off in os_win.c *********************/
31481
31482 /*
31483 ** Some microsoft compilers lack this definition.
31484 */
31485 #ifndef INVALID_FILE_ATTRIBUTES
31486 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1) 
31487 #endif
31488
31489 /*
31490 ** Determine if we are dealing with WindowsCE - which has a much
31491 ** reduced API.
31492 */
31493 #if SQLITE_OS_WINCE
31494 # define AreFileApisANSI() 1
31495 # define FormatMessageW(a,b,c,d,e,f,g) 0
31496 #endif
31497
31498 /* Forward references */
31499 typedef struct winShm winShm;           /* A connection to shared-memory */
31500 typedef struct winShmNode winShmNode;   /* A region of shared-memory */
31501
31502 /*
31503 ** WinCE lacks native support for file locking so we have to fake it
31504 ** with some code of our own.
31505 */
31506 #if SQLITE_OS_WINCE
31507 typedef struct winceLock {
31508   int nReaders;       /* Number of reader locks obtained */
31509   BOOL bPending;      /* Indicates a pending lock has been obtained */
31510   BOOL bReserved;     /* Indicates a reserved lock has been obtained */
31511   BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
31512 } winceLock;
31513 #endif
31514
31515 /*
31516 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
31517 ** portability layer.
31518 */
31519 typedef struct winFile winFile;
31520 struct winFile {
31521   const sqlite3_io_methods *pMethod; /*** Must be first ***/
31522   sqlite3_vfs *pVfs;      /* The VFS used to open this file */
31523   HANDLE h;               /* Handle for accessing the file */
31524   unsigned char locktype; /* Type of lock currently held on this file */
31525   short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
31526   DWORD lastErrno;        /* The Windows errno from the last I/O error */
31527   DWORD sectorSize;       /* Sector size of the device file is on */
31528   winShm *pShm;           /* Instance of shared memory on this file */
31529   const char *zPath;      /* Full pathname of this file */
31530   int szChunk;            /* Chunk size configured by FCNTL_CHUNK_SIZE */
31531 #if SQLITE_OS_WINCE
31532   WCHAR *zDeleteOnClose;  /* Name of file to delete when closing */
31533   HANDLE hMutex;          /* Mutex used to control access to shared lock */  
31534   HANDLE hShared;         /* Shared memory segment used for locking */
31535   winceLock local;        /* Locks obtained by this instance of winFile */
31536   winceLock *shared;      /* Global shared lock memory for the file  */
31537 #endif
31538 };
31539
31540
31541 /*
31542 ** Forward prototypes.
31543 */
31544 static int getSectorSize(
31545     sqlite3_vfs *pVfs,
31546     const char *zRelative     /* UTF-8 file name */
31547 );
31548
31549 /*
31550 ** The following variable is (normally) set once and never changes
31551 ** thereafter.  It records whether the operating system is Win95
31552 ** or WinNT.
31553 **
31554 ** 0:   Operating system unknown.
31555 ** 1:   Operating system is Win95.
31556 ** 2:   Operating system is WinNT.
31557 **
31558 ** In order to facilitate testing on a WinNT system, the test fixture
31559 ** can manually set this value to 1 to emulate Win98 behavior.
31560 */
31561 #ifdef SQLITE_TEST
31562 SQLITE_API int sqlite3_os_type = 0;
31563 #else
31564 static int sqlite3_os_type = 0;
31565 #endif
31566
31567 /*
31568 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
31569 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
31570 **
31571 ** Here is an interesting observation:  Win95, Win98, and WinME lack
31572 ** the LockFileEx() API.  But we can still statically link against that
31573 ** API as long as we don't call it when running Win95/98/ME.  A call to
31574 ** this routine is used to determine if the host is Win95/98/ME or
31575 ** WinNT/2K/XP so that we will know whether or not we can safely call
31576 ** the LockFileEx() API.
31577 */
31578 #if SQLITE_OS_WINCE
31579 # define isNT()  (1)
31580 #else
31581   static int isNT(void){
31582     if( sqlite3_os_type==0 ){
31583       OSVERSIONINFO sInfo;
31584       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
31585       GetVersionEx(&sInfo);
31586       sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
31587     }
31588     return sqlite3_os_type==2;
31589   }
31590 #endif /* SQLITE_OS_WINCE */
31591
31592 /*
31593 ** Convert a UTF-8 string to microsoft unicode (UTF-16?). 
31594 **
31595 ** Space to hold the returned string is obtained from malloc.
31596 */
31597 static WCHAR *utf8ToUnicode(const char *zFilename){
31598   int nChar;
31599   WCHAR *zWideFilename;
31600
31601   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
31602   zWideFilename = malloc( nChar*sizeof(zWideFilename[0]) );
31603   if( zWideFilename==0 ){
31604     return 0;
31605   }
31606   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar);
31607   if( nChar==0 ){
31608     free(zWideFilename);
31609     zWideFilename = 0;
31610   }
31611   return zWideFilename;
31612 }
31613
31614 /*
31615 ** Convert microsoft unicode to UTF-8.  Space to hold the returned string is
31616 ** obtained from malloc().
31617 */
31618 static char *unicodeToUtf8(const WCHAR *zWideFilename){
31619   int nByte;
31620   char *zFilename;
31621
31622   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
31623   zFilename = malloc( nByte );
31624   if( zFilename==0 ){
31625     return 0;
31626   }
31627   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
31628                               0, 0);
31629   if( nByte == 0 ){
31630     free(zFilename);
31631     zFilename = 0;
31632   }
31633   return zFilename;
31634 }
31635
31636 /*
31637 ** Convert an ansi string to microsoft unicode, based on the
31638 ** current codepage settings for file apis.
31639 ** 
31640 ** Space to hold the returned string is obtained
31641 ** from malloc.
31642 */
31643 static WCHAR *mbcsToUnicode(const char *zFilename){
31644   int nByte;
31645   WCHAR *zMbcsFilename;
31646   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
31647
31648   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*sizeof(WCHAR);
31649   zMbcsFilename = malloc( nByte*sizeof(zMbcsFilename[0]) );
31650   if( zMbcsFilename==0 ){
31651     return 0;
31652   }
31653   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte);
31654   if( nByte==0 ){
31655     free(zMbcsFilename);
31656     zMbcsFilename = 0;
31657   }
31658   return zMbcsFilename;
31659 }
31660
31661 /*
31662 ** Convert microsoft unicode to multibyte character string, based on the
31663 ** user's Ansi codepage.
31664 **
31665 ** Space to hold the returned string is obtained from
31666 ** malloc().
31667 */
31668 static char *unicodeToMbcs(const WCHAR *zWideFilename){
31669   int nByte;
31670   char *zFilename;
31671   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
31672
31673   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
31674   zFilename = malloc( nByte );
31675   if( zFilename==0 ){
31676     return 0;
31677   }
31678   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte,
31679                               0, 0);
31680   if( nByte == 0 ){
31681     free(zFilename);
31682     zFilename = 0;
31683   }
31684   return zFilename;
31685 }
31686
31687 /*
31688 ** Convert multibyte character string to UTF-8.  Space to hold the
31689 ** returned string is obtained from malloc().
31690 */
31691 SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
31692   char *zFilenameUtf8;
31693   WCHAR *zTmpWide;
31694
31695   zTmpWide = mbcsToUnicode(zFilename);
31696   if( zTmpWide==0 ){
31697     return 0;
31698   }
31699   zFilenameUtf8 = unicodeToUtf8(zTmpWide);
31700   free(zTmpWide);
31701   return zFilenameUtf8;
31702 }
31703
31704 /*
31705 ** Convert UTF-8 to multibyte character string.  Space to hold the 
31706 ** returned string is obtained from malloc().
31707 */
31708 SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zFilename){
31709   char *zFilenameMbcs;
31710   WCHAR *zTmpWide;
31711
31712   zTmpWide = utf8ToUnicode(zFilename);
31713   if( zTmpWide==0 ){
31714     return 0;
31715   }
31716   zFilenameMbcs = unicodeToMbcs(zTmpWide);
31717   free(zTmpWide);
31718   return zFilenameMbcs;
31719 }
31720
31721
31722 /*
31723 ** The return value of getLastErrorMsg
31724 ** is zero if the error message fits in the buffer, or non-zero
31725 ** otherwise (if the message was truncated).
31726 */
31727 static int getLastErrorMsg(int nBuf, char *zBuf){
31728   /* FormatMessage returns 0 on failure.  Otherwise it
31729   ** returns the number of TCHARs written to the output
31730   ** buffer, excluding the terminating null char.
31731   */
31732   DWORD error = GetLastError();
31733   DWORD dwLen = 0;
31734   char *zOut = 0;
31735
31736   if( isNT() ){
31737     WCHAR *zTempWide = NULL;
31738     dwLen = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
31739                            NULL,
31740                            error,
31741                            0,
31742                            (LPWSTR) &zTempWide,
31743                            0,
31744                            0);
31745     if( dwLen > 0 ){
31746       /* allocate a buffer and convert to UTF8 */
31747       zOut = unicodeToUtf8(zTempWide);
31748       /* free the system buffer allocated by FormatMessage */
31749       LocalFree(zTempWide);
31750     }
31751 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
31752 ** Since the ASCII version of these Windows API do not exist for WINCE,
31753 ** it's important to not reference them for WINCE builds.
31754 */
31755 #if SQLITE_OS_WINCE==0
31756   }else{
31757     char *zTemp = NULL;
31758     dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
31759                            NULL,
31760                            error,
31761                            0,
31762                            (LPSTR) &zTemp,
31763                            0,
31764                            0);
31765     if( dwLen > 0 ){
31766       /* allocate a buffer and convert to UTF8 */
31767       zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
31768       /* free the system buffer allocated by FormatMessage */
31769       LocalFree(zTemp);
31770     }
31771 #endif
31772   }
31773   if( 0 == dwLen ){
31774     sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error);
31775   }else{
31776     /* copy a maximum of nBuf chars to output buffer */
31777     sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
31778     /* free the UTF8 buffer */
31779     free(zOut);
31780   }
31781   return 0;
31782 }
31783
31784 /*
31785 **
31786 ** This function - winLogErrorAtLine() - is only ever called via the macro
31787 ** winLogError().
31788 **
31789 ** This routine is invoked after an error occurs in an OS function.
31790 ** It logs a message using sqlite3_log() containing the current value of
31791 ** error code and, if possible, the human-readable equivalent from 
31792 ** FormatMessage.
31793 **
31794 ** The first argument passed to the macro should be the error code that
31795 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN). 
31796 ** The two subsequent arguments should be the name of the OS function that
31797 ** failed and the the associated file-system path, if any.
31798 */
31799 #define winLogError(a,b,c)     winLogErrorAtLine(a,b,c,__LINE__)
31800 static int winLogErrorAtLine(
31801   int errcode,                    /* SQLite error code */
31802   const char *zFunc,              /* Name of OS function that failed */
31803   const char *zPath,              /* File path associated with error */
31804   int iLine                       /* Source line number where error occurred */
31805 ){
31806   char zMsg[500];                 /* Human readable error text */
31807   int i;                          /* Loop counter */
31808   DWORD iErrno = GetLastError();  /* Error code */
31809
31810   zMsg[0] = 0;
31811   getLastErrorMsg(sizeof(zMsg), zMsg);
31812   assert( errcode!=SQLITE_OK );
31813   if( zPath==0 ) zPath = "";
31814   for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
31815   zMsg[i] = 0;
31816   sqlite3_log(errcode,
31817       "os_win.c:%d: (%d) %s(%s) - %s",
31818       iLine, iErrno, zFunc, zPath, zMsg
31819   );
31820
31821   return errcode;
31822 }
31823
31824 #if SQLITE_OS_WINCE
31825 /*************************************************************************
31826 ** This section contains code for WinCE only.
31827 */
31828 /*
31829 ** WindowsCE does not have a localtime() function.  So create a
31830 ** substitute.
31831 */
31832 struct tm *__cdecl localtime(const time_t *t)
31833 {
31834   static struct tm y;
31835   FILETIME uTm, lTm;
31836   SYSTEMTIME pTm;
31837   sqlite3_int64 t64;
31838   t64 = *t;
31839   t64 = (t64 + 11644473600)*10000000;
31840   uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
31841   uTm.dwHighDateTime= (DWORD)(t64 >> 32);
31842   FileTimeToLocalFileTime(&uTm,&lTm);
31843   FileTimeToSystemTime(&lTm,&pTm);
31844   y.tm_year = pTm.wYear - 1900;
31845   y.tm_mon = pTm.wMonth - 1;
31846   y.tm_wday = pTm.wDayOfWeek;
31847   y.tm_mday = pTm.wDay;
31848   y.tm_hour = pTm.wHour;
31849   y.tm_min = pTm.wMinute;
31850   y.tm_sec = pTm.wSecond;
31851   return &y;
31852 }
31853
31854 /* This will never be called, but defined to make the code compile */
31855 #define GetTempPathA(a,b)
31856
31857 #define LockFile(a,b,c,d,e)       winceLockFile(&a, b, c, d, e)
31858 #define UnlockFile(a,b,c,d,e)     winceUnlockFile(&a, b, c, d, e)
31859 #define LockFileEx(a,b,c,d,e,f)   winceLockFileEx(&a, b, c, d, e, f)
31860
31861 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
31862
31863 /*
31864 ** Acquire a lock on the handle h
31865 */
31866 static void winceMutexAcquire(HANDLE h){
31867    DWORD dwErr;
31868    do {
31869      dwErr = WaitForSingleObject(h, INFINITE);
31870    } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
31871 }
31872 /*
31873 ** Release a lock acquired by winceMutexAcquire()
31874 */
31875 #define winceMutexRelease(h) ReleaseMutex(h)
31876
31877 /*
31878 ** Create the mutex and shared memory used for locking in the file
31879 ** descriptor pFile
31880 */
31881 static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
31882   WCHAR *zTok;
31883   WCHAR *zName = utf8ToUnicode(zFilename);
31884   BOOL bInit = TRUE;
31885
31886   /* Initialize the local lockdata */
31887   ZeroMemory(&pFile->local, sizeof(pFile->local));
31888
31889   /* Replace the backslashes from the filename and lowercase it
31890   ** to derive a mutex name. */
31891   zTok = CharLowerW(zName);
31892   for (;*zTok;zTok++){
31893     if (*zTok == '\\') *zTok = '_';
31894   }
31895
31896   /* Create/open the named mutex */
31897   pFile->hMutex = CreateMutexW(NULL, FALSE, zName);
31898   if (!pFile->hMutex){
31899     pFile->lastErrno = GetLastError();
31900     winLogError(SQLITE_ERROR, "winceCreateLock1", zFilename);
31901     free(zName);
31902     return FALSE;
31903   }
31904
31905   /* Acquire the mutex before continuing */
31906   winceMutexAcquire(pFile->hMutex);
31907   
31908   /* Since the names of named mutexes, semaphores, file mappings etc are 
31909   ** case-sensitive, take advantage of that by uppercasing the mutex name
31910   ** and using that as the shared filemapping name.
31911   */
31912   CharUpperW(zName);
31913   pFile->hShared = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
31914                                        PAGE_READWRITE, 0, sizeof(winceLock),
31915                                        zName);  
31916
31917   /* Set a flag that indicates we're the first to create the memory so it 
31918   ** must be zero-initialized */
31919   if (GetLastError() == ERROR_ALREADY_EXISTS){
31920     bInit = FALSE;
31921   }
31922
31923   free(zName);
31924
31925   /* If we succeeded in making the shared memory handle, map it. */
31926   if (pFile->hShared){
31927     pFile->shared = (winceLock*)MapViewOfFile(pFile->hShared, 
31928              FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
31929     /* If mapping failed, close the shared memory handle and erase it */
31930     if (!pFile->shared){
31931       pFile->lastErrno = GetLastError();
31932       winLogError(SQLITE_ERROR, "winceCreateLock2", zFilename);
31933       CloseHandle(pFile->hShared);
31934       pFile->hShared = NULL;
31935     }
31936   }
31937
31938   /* If shared memory could not be created, then close the mutex and fail */
31939   if (pFile->hShared == NULL){
31940     winceMutexRelease(pFile->hMutex);
31941     CloseHandle(pFile->hMutex);
31942     pFile->hMutex = NULL;
31943     return FALSE;
31944   }
31945   
31946   /* Initialize the shared memory if we're supposed to */
31947   if (bInit) {
31948     ZeroMemory(pFile->shared, sizeof(winceLock));
31949   }
31950
31951   winceMutexRelease(pFile->hMutex);
31952   return TRUE;
31953 }
31954
31955 /*
31956 ** Destroy the part of winFile that deals with wince locks
31957 */
31958 static void winceDestroyLock(winFile *pFile){
31959   if (pFile->hMutex){
31960     /* Acquire the mutex */
31961     winceMutexAcquire(pFile->hMutex);
31962
31963     /* The following blocks should probably assert in debug mode, but they
31964        are to cleanup in case any locks remained open */
31965     if (pFile->local.nReaders){
31966       pFile->shared->nReaders --;
31967     }
31968     if (pFile->local.bReserved){
31969       pFile->shared->bReserved = FALSE;
31970     }
31971     if (pFile->local.bPending){
31972       pFile->shared->bPending = FALSE;
31973     }
31974     if (pFile->local.bExclusive){
31975       pFile->shared->bExclusive = FALSE;
31976     }
31977
31978     /* De-reference and close our copy of the shared memory handle */
31979     UnmapViewOfFile(pFile->shared);
31980     CloseHandle(pFile->hShared);
31981
31982     /* Done with the mutex */
31983     winceMutexRelease(pFile->hMutex);    
31984     CloseHandle(pFile->hMutex);
31985     pFile->hMutex = NULL;
31986   }
31987 }
31988
31989 /* 
31990 ** An implementation of the LockFile() API of windows for wince
31991 */
31992 static BOOL winceLockFile(
31993   HANDLE *phFile,
31994   DWORD dwFileOffsetLow,
31995   DWORD dwFileOffsetHigh,
31996   DWORD nNumberOfBytesToLockLow,
31997   DWORD nNumberOfBytesToLockHigh
31998 ){
31999   winFile *pFile = HANDLE_TO_WINFILE(phFile);
32000   BOOL bReturn = FALSE;
32001
32002   UNUSED_PARAMETER(dwFileOffsetHigh);
32003   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
32004
32005   if (!pFile->hMutex) return TRUE;
32006   winceMutexAcquire(pFile->hMutex);
32007
32008   /* Wanting an exclusive lock? */
32009   if (dwFileOffsetLow == (DWORD)SHARED_FIRST
32010        && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
32011     if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
32012        pFile->shared->bExclusive = TRUE;
32013        pFile->local.bExclusive = TRUE;
32014        bReturn = TRUE;
32015     }
32016   }
32017
32018   /* Want a read-only lock? */
32019   else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
32020            nNumberOfBytesToLockLow == 1){
32021     if (pFile->shared->bExclusive == 0){
32022       pFile->local.nReaders ++;
32023       if (pFile->local.nReaders == 1){
32024         pFile->shared->nReaders ++;
32025       }
32026       bReturn = TRUE;
32027     }
32028   }
32029
32030   /* Want a pending lock? */
32031   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToLockLow == 1){
32032     /* If no pending lock has been acquired, then acquire it */
32033     if (pFile->shared->bPending == 0) {
32034       pFile->shared->bPending = TRUE;
32035       pFile->local.bPending = TRUE;
32036       bReturn = TRUE;
32037     }
32038   }
32039
32040   /* Want a reserved lock? */
32041   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
32042     if (pFile->shared->bReserved == 0) {
32043       pFile->shared->bReserved = TRUE;
32044       pFile->local.bReserved = TRUE;
32045       bReturn = TRUE;
32046     }
32047   }
32048
32049   winceMutexRelease(pFile->hMutex);
32050   return bReturn;
32051 }
32052
32053 /*
32054 ** An implementation of the UnlockFile API of windows for wince
32055 */
32056 static BOOL winceUnlockFile(
32057   HANDLE *phFile,
32058   DWORD dwFileOffsetLow,
32059   DWORD dwFileOffsetHigh,
32060   DWORD nNumberOfBytesToUnlockLow,
32061   DWORD nNumberOfBytesToUnlockHigh
32062 ){
32063   winFile *pFile = HANDLE_TO_WINFILE(phFile);
32064   BOOL bReturn = FALSE;
32065
32066   UNUSED_PARAMETER(dwFileOffsetHigh);
32067   UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
32068
32069   if (!pFile->hMutex) return TRUE;
32070   winceMutexAcquire(pFile->hMutex);
32071
32072   /* Releasing a reader lock or an exclusive lock */
32073   if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
32074     /* Did we have an exclusive lock? */
32075     if (pFile->local.bExclusive){
32076       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
32077       pFile->local.bExclusive = FALSE;
32078       pFile->shared->bExclusive = FALSE;
32079       bReturn = TRUE;
32080     }
32081
32082     /* Did we just have a reader lock? */
32083     else if (pFile->local.nReaders){
32084       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE || nNumberOfBytesToUnlockLow == 1);
32085       pFile->local.nReaders --;
32086       if (pFile->local.nReaders == 0)
32087       {
32088         pFile->shared->nReaders --;
32089       }
32090       bReturn = TRUE;
32091     }
32092   }
32093
32094   /* Releasing a pending lock */
32095   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
32096     if (pFile->local.bPending){
32097       pFile->local.bPending = FALSE;
32098       pFile->shared->bPending = FALSE;
32099       bReturn = TRUE;
32100     }
32101   }
32102   /* Releasing a reserved lock */
32103   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
32104     if (pFile->local.bReserved) {
32105       pFile->local.bReserved = FALSE;
32106       pFile->shared->bReserved = FALSE;
32107       bReturn = TRUE;
32108     }
32109   }
32110
32111   winceMutexRelease(pFile->hMutex);
32112   return bReturn;
32113 }
32114
32115 /*
32116 ** An implementation of the LockFileEx() API of windows for wince
32117 */
32118 static BOOL winceLockFileEx(
32119   HANDLE *phFile,
32120   DWORD dwFlags,
32121   DWORD dwReserved,
32122   DWORD nNumberOfBytesToLockLow,
32123   DWORD nNumberOfBytesToLockHigh,
32124   LPOVERLAPPED lpOverlapped
32125 ){
32126   UNUSED_PARAMETER(dwReserved);
32127   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
32128
32129   /* If the caller wants a shared read lock, forward this call
32130   ** to winceLockFile */
32131   if (lpOverlapped->Offset == (DWORD)SHARED_FIRST &&
32132       dwFlags == 1 &&
32133       nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
32134     return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
32135   }
32136   return FALSE;
32137 }
32138 /*
32139 ** End of the special code for wince
32140 *****************************************************************************/
32141 #endif /* SQLITE_OS_WINCE */
32142
32143 /*****************************************************************************
32144 ** The next group of routines implement the I/O methods specified
32145 ** by the sqlite3_io_methods object.
32146 ******************************************************************************/
32147
32148 /*
32149 ** Some microsoft compilers lack this definition.
32150 */
32151 #ifndef INVALID_SET_FILE_POINTER
32152 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
32153 #endif
32154
32155 /*
32156 ** Move the current position of the file handle passed as the first 
32157 ** argument to offset iOffset within the file. If successful, return 0. 
32158 ** Otherwise, set pFile->lastErrno and return non-zero.
32159 */
32160 static int seekWinFile(winFile *pFile, sqlite3_int64 iOffset){
32161   LONG upperBits;                 /* Most sig. 32 bits of new offset */
32162   LONG lowerBits;                 /* Least sig. 32 bits of new offset */
32163   DWORD dwRet;                    /* Value returned by SetFilePointer() */
32164
32165   upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
32166   lowerBits = (LONG)(iOffset & 0xffffffff);
32167
32168   /* API oddity: If successful, SetFilePointer() returns a dword 
32169   ** containing the lower 32-bits of the new file-offset. Or, if it fails,
32170   ** it returns INVALID_SET_FILE_POINTER. However according to MSDN, 
32171   ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine 
32172   ** whether an error has actually occured, it is also necessary to call 
32173   ** GetLastError().
32174   */
32175   dwRet = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
32176   if( (dwRet==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR) ){
32177     pFile->lastErrno = GetLastError();
32178     winLogError(SQLITE_IOERR_SEEK, "seekWinFile", pFile->zPath);
32179     return 1;
32180   }
32181
32182   return 0;
32183 }
32184
32185 /*
32186 ** Close a file.
32187 **
32188 ** It is reported that an attempt to close a handle might sometimes
32189 ** fail.  This is a very unreasonable result, but windows is notorious
32190 ** for being unreasonable so I do not doubt that it might happen.  If
32191 ** the close fails, we pause for 100 milliseconds and try again.  As
32192 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
32193 ** giving up and returning an error.
32194 */
32195 #define MX_CLOSE_ATTEMPT 3
32196 static int winClose(sqlite3_file *id){
32197   int rc, cnt = 0;
32198   winFile *pFile = (winFile*)id;
32199
32200   assert( id!=0 );
32201   assert( pFile->pShm==0 );
32202   OSTRACE(("CLOSE %d\n", pFile->h));
32203   do{
32204     rc = CloseHandle(pFile->h);
32205     /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
32206   }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (Sleep(100), 1) );
32207 #if SQLITE_OS_WINCE
32208 #define WINCE_DELETION_ATTEMPTS 3
32209   winceDestroyLock(pFile);
32210   if( pFile->zDeleteOnClose ){
32211     int cnt = 0;
32212     while(
32213            DeleteFileW(pFile->zDeleteOnClose)==0
32214         && GetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff 
32215         && cnt++ < WINCE_DELETION_ATTEMPTS
32216     ){
32217        Sleep(100);  /* Wait a little before trying again */
32218     }
32219     free(pFile->zDeleteOnClose);
32220   }
32221 #endif
32222   OSTRACE(("CLOSE %d %s\n", pFile->h, rc ? "ok" : "failed"));
32223   OpenCounter(-1);
32224   return rc ? SQLITE_OK
32225             : winLogError(SQLITE_IOERR_CLOSE, "winClose", pFile->zPath);
32226 }
32227
32228 /*
32229 ** Read data from a file into a buffer.  Return SQLITE_OK if all
32230 ** bytes were read successfully and SQLITE_IOERR if anything goes
32231 ** wrong.
32232 */
32233 static int winRead(
32234   sqlite3_file *id,          /* File to read from */
32235   void *pBuf,                /* Write content into this buffer */
32236   int amt,                   /* Number of bytes to read */
32237   sqlite3_int64 offset       /* Begin reading at this offset */
32238 ){
32239   winFile *pFile = (winFile*)id;  /* file handle */
32240   DWORD nRead;                    /* Number of bytes actually read from file */
32241
32242   assert( id!=0 );
32243   SimulateIOError(return SQLITE_IOERR_READ);
32244   OSTRACE(("READ %d lock=%d\n", pFile->h, pFile->locktype));
32245
32246   if( seekWinFile(pFile, offset) ){
32247     return SQLITE_FULL;
32248   }
32249   if( !ReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
32250     pFile->lastErrno = GetLastError();
32251     return winLogError(SQLITE_IOERR_READ, "winRead", pFile->zPath);
32252   }
32253   if( nRead<(DWORD)amt ){
32254     /* Unread parts of the buffer must be zero-filled */
32255     memset(&((char*)pBuf)[nRead], 0, amt-nRead);
32256     return SQLITE_IOERR_SHORT_READ;
32257   }
32258
32259   return SQLITE_OK;
32260 }
32261
32262 /*
32263 ** Write data from a buffer into a file.  Return SQLITE_OK on success
32264 ** or some other error code on failure.
32265 */
32266 static int winWrite(
32267   sqlite3_file *id,               /* File to write into */
32268   const void *pBuf,               /* The bytes to be written */
32269   int amt,                        /* Number of bytes to write */
32270   sqlite3_int64 offset            /* Offset into the file to begin writing at */
32271 ){
32272   int rc;                         /* True if error has occured, else false */
32273   winFile *pFile = (winFile*)id;  /* File handle */
32274
32275   assert( amt>0 );
32276   assert( pFile );
32277   SimulateIOError(return SQLITE_IOERR_WRITE);
32278   SimulateDiskfullError(return SQLITE_FULL);
32279
32280   OSTRACE(("WRITE %d lock=%d\n", pFile->h, pFile->locktype));
32281
32282   rc = seekWinFile(pFile, offset);
32283   if( rc==0 ){
32284     u8 *aRem = (u8 *)pBuf;        /* Data yet to be written */
32285     int nRem = amt;               /* Number of bytes yet to be written */
32286     DWORD nWrite;                 /* Bytes written by each WriteFile() call */
32287
32288     while( nRem>0 && WriteFile(pFile->h, aRem, nRem, &nWrite, 0) && nWrite>0 ){
32289       aRem += nWrite;
32290       nRem -= nWrite;
32291     }
32292     if( nRem>0 ){
32293       pFile->lastErrno = GetLastError();
32294       rc = 1;
32295     }
32296   }
32297
32298   if( rc ){
32299     if(   ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
32300        || ( pFile->lastErrno==ERROR_DISK_FULL )){
32301       return SQLITE_FULL;
32302     }
32303     return winLogError(SQLITE_IOERR_WRITE, "winWrite", pFile->zPath);
32304   }
32305   return SQLITE_OK;
32306 }
32307
32308 /*
32309 ** Truncate an open file to a specified size
32310 */
32311 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
32312   winFile *pFile = (winFile*)id;  /* File handle object */
32313   int rc = SQLITE_OK;             /* Return code for this function */
32314
32315   assert( pFile );
32316
32317   OSTRACE(("TRUNCATE %d %lld\n", pFile->h, nByte));
32318   SimulateIOError(return SQLITE_IOERR_TRUNCATE);
32319
32320   /* If the user has configured a chunk-size for this file, truncate the
32321   ** file so that it consists of an integer number of chunks (i.e. the
32322   ** actual file size after the operation may be larger than the requested
32323   ** size).
32324   */
32325   if( pFile->szChunk ){
32326     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
32327   }
32328
32329   /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
32330   if( seekWinFile(pFile, nByte) ){
32331     rc = winLogError(SQLITE_IOERR_TRUNCATE, "winTruncate1", pFile->zPath);
32332   }else if( 0==SetEndOfFile(pFile->h) ){
32333     pFile->lastErrno = GetLastError();
32334     rc = winLogError(SQLITE_IOERR_TRUNCATE, "winTruncate2", pFile->zPath);
32335   }
32336
32337   OSTRACE(("TRUNCATE %d %lld %s\n", pFile->h, nByte, rc ? "failed" : "ok"));
32338   return rc;
32339 }
32340
32341 #ifdef SQLITE_TEST
32342 /*
32343 ** Count the number of fullsyncs and normal syncs.  This is used to test
32344 ** that syncs and fullsyncs are occuring at the right times.
32345 */
32346 SQLITE_API int sqlite3_sync_count = 0;
32347 SQLITE_API int sqlite3_fullsync_count = 0;
32348 #endif
32349
32350 /*
32351 ** Make sure all writes to a particular file are committed to disk.
32352 */
32353 static int winSync(sqlite3_file *id, int flags){
32354 #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || defined(SQLITE_DEBUG)
32355   winFile *pFile = (winFile*)id;
32356   BOOL rc;
32357 #else
32358   UNUSED_PARAMETER(id);
32359 #endif
32360
32361   assert( pFile );
32362   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
32363   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
32364       || (flags&0x0F)==SQLITE_SYNC_FULL
32365   );
32366
32367   OSTRACE(("SYNC %d lock=%d\n", pFile->h, pFile->locktype));
32368
32369   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
32370   ** line is to test that doing so does not cause any problems.
32371   */
32372   SimulateDiskfullError( return SQLITE_FULL );
32373
32374 #ifndef SQLITE_TEST
32375   UNUSED_PARAMETER(flags);
32376 #else
32377   if( (flags&0x0F)==SQLITE_SYNC_FULL ){
32378     sqlite3_fullsync_count++;
32379   }
32380   sqlite3_sync_count++;
32381 #endif
32382
32383   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
32384   ** no-op
32385   */
32386 #ifdef SQLITE_NO_SYNC
32387   return SQLITE_OK;
32388 #else
32389   rc = FlushFileBuffers(pFile->h);
32390   SimulateIOError( rc=FALSE );
32391   if( rc ){
32392     return SQLITE_OK;
32393   }else{
32394     pFile->lastErrno = GetLastError();
32395     return winLogError(SQLITE_IOERR_FSYNC, "winSync", pFile->zPath);
32396   }
32397 #endif
32398 }
32399
32400 /*
32401 ** Determine the current size of a file in bytes
32402 */
32403 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
32404   DWORD upperBits;
32405   DWORD lowerBits;
32406   winFile *pFile = (winFile*)id;
32407   DWORD error;
32408
32409   assert( id!=0 );
32410   SimulateIOError(return SQLITE_IOERR_FSTAT);
32411   lowerBits = GetFileSize(pFile->h, &upperBits);
32412   if(   (lowerBits == INVALID_FILE_SIZE)
32413      && ((error = GetLastError()) != NO_ERROR) )
32414   {
32415     pFile->lastErrno = error;
32416     return winLogError(SQLITE_IOERR_FSTAT, "winFileSize", pFile->zPath);
32417   }
32418   *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
32419   return SQLITE_OK;
32420 }
32421
32422 /*
32423 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
32424 */
32425 #ifndef LOCKFILE_FAIL_IMMEDIATELY
32426 # define LOCKFILE_FAIL_IMMEDIATELY 1
32427 #endif
32428
32429 /*
32430 ** Acquire a reader lock.
32431 ** Different API routines are called depending on whether or not this
32432 ** is Win95 or WinNT.
32433 */
32434 static int getReadLock(winFile *pFile){
32435   int res;
32436   if( isNT() ){
32437     OVERLAPPED ovlp;
32438     ovlp.Offset = SHARED_FIRST;
32439     ovlp.OffsetHigh = 0;
32440     ovlp.hEvent = 0;
32441     res = LockFileEx(pFile->h, LOCKFILE_FAIL_IMMEDIATELY,
32442                      0, SHARED_SIZE, 0, &ovlp);
32443 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
32444 */
32445 #if SQLITE_OS_WINCE==0
32446   }else{
32447     int lk;
32448     sqlite3_randomness(sizeof(lk), &lk);
32449     pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
32450     res = LockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
32451 #endif
32452   }
32453   if( res == 0 ){
32454     pFile->lastErrno = GetLastError();
32455     /* No need to log a failure to lock */
32456   }
32457   return res;
32458 }
32459
32460 /*
32461 ** Undo a readlock
32462 */
32463 static int unlockReadLock(winFile *pFile){
32464   int res;
32465   if( isNT() ){
32466     res = UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
32467 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
32468 */
32469 #if SQLITE_OS_WINCE==0
32470   }else{
32471     res = UnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
32472 #endif
32473   }
32474   if( res==0 && GetLastError()!=ERROR_NOT_LOCKED ){
32475     pFile->lastErrno = GetLastError();
32476     winLogError(SQLITE_IOERR_UNLOCK, "unlockReadLock", pFile->zPath);
32477   }
32478   return res;
32479 }
32480
32481 /*
32482 ** Lock the file with the lock specified by parameter locktype - one
32483 ** of the following:
32484 **
32485 **     (1) SHARED_LOCK
32486 **     (2) RESERVED_LOCK
32487 **     (3) PENDING_LOCK
32488 **     (4) EXCLUSIVE_LOCK
32489 **
32490 ** Sometimes when requesting one lock state, additional lock states
32491 ** are inserted in between.  The locking might fail on one of the later
32492 ** transitions leaving the lock state different from what it started but
32493 ** still short of its goal.  The following chart shows the allowed
32494 ** transitions and the inserted intermediate states:
32495 **
32496 **    UNLOCKED -> SHARED
32497 **    SHARED -> RESERVED
32498 **    SHARED -> (PENDING) -> EXCLUSIVE
32499 **    RESERVED -> (PENDING) -> EXCLUSIVE
32500 **    PENDING -> EXCLUSIVE
32501 **
32502 ** This routine will only increase a lock.  The winUnlock() routine
32503 ** erases all locks at once and returns us immediately to locking level 0.
32504 ** It is not possible to lower the locking level one step at a time.  You
32505 ** must go straight to locking level 0.
32506 */
32507 static int winLock(sqlite3_file *id, int locktype){
32508   int rc = SQLITE_OK;    /* Return code from subroutines */
32509   int res = 1;           /* Result of a windows lock call */
32510   int newLocktype;       /* Set pFile->locktype to this value before exiting */
32511   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
32512   winFile *pFile = (winFile*)id;
32513   DWORD error = NO_ERROR;
32514
32515   assert( id!=0 );
32516   OSTRACE(("LOCK %d %d was %d(%d)\n",
32517            pFile->h, locktype, pFile->locktype, pFile->sharedLockByte));
32518
32519   /* If there is already a lock of this type or more restrictive on the
32520   ** OsFile, do nothing. Don't use the end_lock: exit path, as
32521   ** sqlite3OsEnterMutex() hasn't been called yet.
32522   */
32523   if( pFile->locktype>=locktype ){
32524     return SQLITE_OK;
32525   }
32526
32527   /* Make sure the locking sequence is correct
32528   */
32529   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
32530   assert( locktype!=PENDING_LOCK );
32531   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
32532
32533   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
32534   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
32535   ** the PENDING_LOCK byte is temporary.
32536   */
32537   newLocktype = pFile->locktype;
32538   if(   (pFile->locktype==NO_LOCK)
32539      || (   (locktype==EXCLUSIVE_LOCK)
32540          && (pFile->locktype==RESERVED_LOCK))
32541   ){
32542     int cnt = 3;
32543     while( cnt-->0 && (res = LockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
32544       /* Try 3 times to get the pending lock.  The pending lock might be
32545       ** held by another reader process who will release it momentarily.
32546       */
32547       OSTRACE(("could not get a PENDING lock. cnt=%d\n", cnt));
32548       Sleep(1);
32549     }
32550     gotPendingLock = res;
32551     if( !res ){
32552       error = GetLastError();
32553     }
32554   }
32555
32556   /* Acquire a shared lock
32557   */
32558   if( locktype==SHARED_LOCK && res ){
32559     assert( pFile->locktype==NO_LOCK );
32560     res = getReadLock(pFile);
32561     if( res ){
32562       newLocktype = SHARED_LOCK;
32563     }else{
32564       error = GetLastError();
32565     }
32566   }
32567
32568   /* Acquire a RESERVED lock
32569   */
32570   if( locktype==RESERVED_LOCK && res ){
32571     assert( pFile->locktype==SHARED_LOCK );
32572     res = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
32573     if( res ){
32574       newLocktype = RESERVED_LOCK;
32575     }else{
32576       error = GetLastError();
32577     }
32578   }
32579
32580   /* Acquire a PENDING lock
32581   */
32582   if( locktype==EXCLUSIVE_LOCK && res ){
32583     newLocktype = PENDING_LOCK;
32584     gotPendingLock = 0;
32585   }
32586
32587   /* Acquire an EXCLUSIVE lock
32588   */
32589   if( locktype==EXCLUSIVE_LOCK && res ){
32590     assert( pFile->locktype>=SHARED_LOCK );
32591     res = unlockReadLock(pFile);
32592     OSTRACE(("unreadlock = %d\n", res));
32593     res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
32594     if( res ){
32595       newLocktype = EXCLUSIVE_LOCK;
32596     }else{
32597       error = GetLastError();
32598       OSTRACE(("error-code = %d\n", error));
32599       getReadLock(pFile);
32600     }
32601   }
32602
32603   /* If we are holding a PENDING lock that ought to be released, then
32604   ** release it now.
32605   */
32606   if( gotPendingLock && locktype==SHARED_LOCK ){
32607     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
32608   }
32609
32610   /* Update the state of the lock has held in the file descriptor then
32611   ** return the appropriate result code.
32612   */
32613   if( res ){
32614     rc = SQLITE_OK;
32615   }else{
32616     OSTRACE(("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
32617            locktype, newLocktype));
32618     pFile->lastErrno = error;
32619     rc = SQLITE_BUSY;
32620   }
32621   pFile->locktype = (u8)newLocktype;
32622   return rc;
32623 }
32624
32625 /*
32626 ** This routine checks if there is a RESERVED lock held on the specified
32627 ** file by this or any other process. If such a lock is held, return
32628 ** non-zero, otherwise zero.
32629 */
32630 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
32631   int rc;
32632   winFile *pFile = (winFile*)id;
32633
32634   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
32635
32636   assert( id!=0 );
32637   if( pFile->locktype>=RESERVED_LOCK ){
32638     rc = 1;
32639     OSTRACE(("TEST WR-LOCK %d %d (local)\n", pFile->h, rc));
32640   }else{
32641     rc = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
32642     if( rc ){
32643       UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
32644     }
32645     rc = !rc;
32646     OSTRACE(("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc));
32647   }
32648   *pResOut = rc;
32649   return SQLITE_OK;
32650 }
32651
32652 /*
32653 ** Lower the locking level on file descriptor id to locktype.  locktype
32654 ** must be either NO_LOCK or SHARED_LOCK.
32655 **
32656 ** If the locking level of the file descriptor is already at or below
32657 ** the requested locking level, this routine is a no-op.
32658 **
32659 ** It is not possible for this routine to fail if the second argument
32660 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
32661 ** might return SQLITE_IOERR;
32662 */
32663 static int winUnlock(sqlite3_file *id, int locktype){
32664   int type;
32665   winFile *pFile = (winFile*)id;
32666   int rc = SQLITE_OK;
32667   assert( pFile!=0 );
32668   assert( locktype<=SHARED_LOCK );
32669   OSTRACE(("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
32670           pFile->locktype, pFile->sharedLockByte));
32671   type = pFile->locktype;
32672   if( type>=EXCLUSIVE_LOCK ){
32673     UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
32674     if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
32675       /* This should never happen.  We should always be able to
32676       ** reacquire the read lock */
32677       rc = winLogError(SQLITE_IOERR_UNLOCK, "winUnlock", pFile->zPath);
32678     }
32679   }
32680   if( type>=RESERVED_LOCK ){
32681     UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
32682   }
32683   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
32684     unlockReadLock(pFile);
32685   }
32686   if( type>=PENDING_LOCK ){
32687     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
32688   }
32689   pFile->locktype = (u8)locktype;
32690   return rc;
32691 }
32692
32693 /*
32694 ** Control and query of the open file handle.
32695 */
32696 static int winFileControl(sqlite3_file *id, int op, void *pArg){
32697   switch( op ){
32698     case SQLITE_FCNTL_LOCKSTATE: {
32699       *(int*)pArg = ((winFile*)id)->locktype;
32700       return SQLITE_OK;
32701     }
32702     case SQLITE_LAST_ERRNO: {
32703       *(int*)pArg = (int)((winFile*)id)->lastErrno;
32704       return SQLITE_OK;
32705     }
32706     case SQLITE_FCNTL_CHUNK_SIZE: {
32707       ((winFile*)id)->szChunk = *(int *)pArg;
32708       return SQLITE_OK;
32709     }
32710     case SQLITE_FCNTL_SIZE_HINT: {
32711       sqlite3_int64 sz = *(sqlite3_int64*)pArg;
32712       SimulateIOErrorBenign(1);
32713       winTruncate(id, sz);
32714       SimulateIOErrorBenign(0);
32715       return SQLITE_OK;
32716     }
32717     case SQLITE_FCNTL_SYNC_OMITTED: {
32718       return SQLITE_OK;
32719     }
32720   }
32721   return SQLITE_NOTFOUND;
32722 }
32723
32724 /*
32725 ** Return the sector size in bytes of the underlying block device for
32726 ** the specified file. This is almost always 512 bytes, but may be
32727 ** larger for some devices.
32728 **
32729 ** SQLite code assumes this function cannot fail. It also assumes that
32730 ** if two files are created in the same file-system directory (i.e.
32731 ** a database and its journal file) that the sector size will be the
32732 ** same for both.
32733 */
32734 static int winSectorSize(sqlite3_file *id){
32735   assert( id!=0 );
32736   return (int)(((winFile*)id)->sectorSize);
32737 }
32738
32739 /*
32740 ** Return a vector of device characteristics.
32741 */
32742 static int winDeviceCharacteristics(sqlite3_file *id){
32743   UNUSED_PARAMETER(id);
32744   return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN;
32745 }
32746
32747 #ifndef SQLITE_OMIT_WAL
32748
32749 /* 
32750 ** Windows will only let you create file view mappings
32751 ** on allocation size granularity boundaries.
32752 ** During sqlite3_os_init() we do a GetSystemInfo()
32753 ** to get the granularity size.
32754 */
32755 SYSTEM_INFO winSysInfo;
32756
32757 /*
32758 ** Helper functions to obtain and relinquish the global mutex. The
32759 ** global mutex is used to protect the winLockInfo objects used by 
32760 ** this file, all of which may be shared by multiple threads.
32761 **
32762 ** Function winShmMutexHeld() is used to assert() that the global mutex 
32763 ** is held when required. This function is only used as part of assert() 
32764 ** statements. e.g.
32765 **
32766 **   winShmEnterMutex()
32767 **     assert( winShmMutexHeld() );
32768 **   winShmLeaveMutex()
32769 */
32770 static void winShmEnterMutex(void){
32771   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
32772 }
32773 static void winShmLeaveMutex(void){
32774   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
32775 }
32776 #ifdef SQLITE_DEBUG
32777 static int winShmMutexHeld(void) {
32778   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
32779 }
32780 #endif
32781
32782 /*
32783 ** Object used to represent a single file opened and mmapped to provide
32784 ** shared memory.  When multiple threads all reference the same
32785 ** log-summary, each thread has its own winFile object, but they all
32786 ** point to a single instance of this object.  In other words, each
32787 ** log-summary is opened only once per process.
32788 **
32789 ** winShmMutexHeld() must be true when creating or destroying
32790 ** this object or while reading or writing the following fields:
32791 **
32792 **      nRef
32793 **      pNext 
32794 **
32795 ** The following fields are read-only after the object is created:
32796 ** 
32797 **      fid
32798 **      zFilename
32799 **
32800 ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
32801 ** winShmMutexHeld() is true when reading or writing any other field
32802 ** in this structure.
32803 **
32804 */
32805 struct winShmNode {
32806   sqlite3_mutex *mutex;      /* Mutex to access this object */
32807   char *zFilename;           /* Name of the file */
32808   winFile hFile;             /* File handle from winOpen */
32809
32810   int szRegion;              /* Size of shared-memory regions */
32811   int nRegion;               /* Size of array apRegion */
32812   struct ShmRegion {
32813     HANDLE hMap;             /* File handle from CreateFileMapping */
32814     void *pMap;
32815   } *aRegion;
32816   DWORD lastErrno;           /* The Windows errno from the last I/O error */
32817
32818   int nRef;                  /* Number of winShm objects pointing to this */
32819   winShm *pFirst;            /* All winShm objects pointing to this */
32820   winShmNode *pNext;         /* Next in list of all winShmNode objects */
32821 #ifdef SQLITE_DEBUG
32822   u8 nextShmId;              /* Next available winShm.id value */
32823 #endif
32824 };
32825
32826 /*
32827 ** A global array of all winShmNode objects.
32828 **
32829 ** The winShmMutexHeld() must be true while reading or writing this list.
32830 */
32831 static winShmNode *winShmNodeList = 0;
32832
32833 /*
32834 ** Structure used internally by this VFS to record the state of an
32835 ** open shared memory connection.
32836 **
32837 ** The following fields are initialized when this object is created and
32838 ** are read-only thereafter:
32839 **
32840 **    winShm.pShmNode
32841 **    winShm.id
32842 **
32843 ** All other fields are read/write.  The winShm.pShmNode->mutex must be held
32844 ** while accessing any read/write fields.
32845 */
32846 struct winShm {
32847   winShmNode *pShmNode;      /* The underlying winShmNode object */
32848   winShm *pNext;             /* Next winShm with the same winShmNode */
32849   u8 hasMutex;               /* True if holding the winShmNode mutex */
32850   u16 sharedMask;            /* Mask of shared locks held */
32851   u16 exclMask;              /* Mask of exclusive locks held */
32852 #ifdef SQLITE_DEBUG
32853   u8 id;                     /* Id of this connection with its winShmNode */
32854 #endif
32855 };
32856
32857 /*
32858 ** Constants used for locking
32859 */
32860 #define WIN_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
32861 #define WIN_SHM_DMS    (WIN_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
32862
32863 /*
32864 ** Apply advisory locks for all n bytes beginning at ofst.
32865 */
32866 #define _SHM_UNLCK  1
32867 #define _SHM_RDLCK  2
32868 #define _SHM_WRLCK  3
32869 static int winShmSystemLock(
32870   winShmNode *pFile,    /* Apply locks to this open shared-memory segment */
32871   int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
32872   int ofst,             /* Offset to first byte to be locked/unlocked */
32873   int nByte             /* Number of bytes to lock or unlock */
32874 ){
32875   OVERLAPPED ovlp;
32876   DWORD dwFlags;
32877   int rc = 0;           /* Result code form Lock/UnlockFileEx() */
32878
32879   /* Access to the winShmNode object is serialized by the caller */
32880   assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
32881
32882   /* Initialize the locking parameters */
32883   dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
32884   if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
32885
32886   memset(&ovlp, 0, sizeof(OVERLAPPED));
32887   ovlp.Offset = ofst;
32888
32889   /* Release/Acquire the system-level lock */
32890   if( lockType==_SHM_UNLCK ){
32891     rc = UnlockFileEx(pFile->hFile.h, 0, nByte, 0, &ovlp);
32892   }else{
32893     rc = LockFileEx(pFile->hFile.h, dwFlags, 0, nByte, 0, &ovlp);
32894   }
32895   
32896   if( rc!= 0 ){
32897     rc = SQLITE_OK;
32898   }else{
32899     pFile->lastErrno =  GetLastError();
32900     rc = SQLITE_BUSY;
32901   }
32902
32903   OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n", 
32904            pFile->hFile.h,
32905            rc==SQLITE_OK ? "ok" : "failed",
32906            lockType==_SHM_UNLCK ? "UnlockFileEx" : "LockFileEx",
32907            pFile->lastErrno));
32908
32909   return rc;
32910 }
32911
32912 /* Forward references to VFS methods */
32913 static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
32914 static int winDelete(sqlite3_vfs *,const char*,int);
32915
32916 /*
32917 ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
32918 **
32919 ** This is not a VFS shared-memory method; it is a utility function called
32920 ** by VFS shared-memory methods.
32921 */
32922 static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
32923   winShmNode **pp;
32924   winShmNode *p;
32925   BOOL bRc;
32926   assert( winShmMutexHeld() );
32927   pp = &winShmNodeList;
32928   while( (p = *pp)!=0 ){
32929     if( p->nRef==0 ){
32930       int i;
32931       if( p->mutex ) sqlite3_mutex_free(p->mutex);
32932       for(i=0; i<p->nRegion; i++){
32933         bRc = UnmapViewOfFile(p->aRegion[i].pMap);
32934         OSTRACE(("SHM-PURGE pid-%d unmap region=%d %s\n",
32935                  (int)GetCurrentProcessId(), i,
32936                  bRc ? "ok" : "failed"));
32937         bRc = CloseHandle(p->aRegion[i].hMap);
32938         OSTRACE(("SHM-PURGE pid-%d close region=%d %s\n",
32939                  (int)GetCurrentProcessId(), i,
32940                  bRc ? "ok" : "failed"));
32941       }
32942       if( p->hFile.h != INVALID_HANDLE_VALUE ){
32943         SimulateIOErrorBenign(1);
32944         winClose((sqlite3_file *)&p->hFile);
32945         SimulateIOErrorBenign(0);
32946       }
32947       if( deleteFlag ){
32948         SimulateIOErrorBenign(1);
32949         winDelete(pVfs, p->zFilename, 0);
32950         SimulateIOErrorBenign(0);
32951       }
32952       *pp = p->pNext;
32953       sqlite3_free(p->aRegion);
32954       sqlite3_free(p);
32955     }else{
32956       pp = &p->pNext;
32957     }
32958   }
32959 }
32960
32961 /*
32962 ** Open the shared-memory area associated with database file pDbFd.
32963 **
32964 ** When opening a new shared-memory file, if no other instances of that
32965 ** file are currently open, in this process or in other processes, then
32966 ** the file must be truncated to zero length or have its header cleared.
32967 */
32968 static int winOpenSharedMemory(winFile *pDbFd){
32969   struct winShm *p;                  /* The connection to be opened */
32970   struct winShmNode *pShmNode = 0;   /* The underlying mmapped file */
32971   int rc;                            /* Result code */
32972   struct winShmNode *pNew;           /* Newly allocated winShmNode */
32973   int nName;                         /* Size of zName in bytes */
32974
32975   assert( pDbFd->pShm==0 );    /* Not previously opened */
32976
32977   /* Allocate space for the new sqlite3_shm object.  Also speculatively
32978   ** allocate space for a new winShmNode and filename.
32979   */
32980   p = sqlite3_malloc( sizeof(*p) );
32981   if( p==0 ) return SQLITE_NOMEM;
32982   memset(p, 0, sizeof(*p));
32983   nName = sqlite3Strlen30(pDbFd->zPath);
32984   pNew = sqlite3_malloc( sizeof(*pShmNode) + nName + 15 );
32985   if( pNew==0 ){
32986     sqlite3_free(p);
32987     return SQLITE_NOMEM;
32988   }
32989   memset(pNew, 0, sizeof(*pNew));
32990   pNew->zFilename = (char*)&pNew[1];
32991   sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
32992   sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename); 
32993
32994   /* Look to see if there is an existing winShmNode that can be used.
32995   ** If no matching winShmNode currently exists, create a new one.
32996   */
32997   winShmEnterMutex();
32998   for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
32999     /* TBD need to come up with better match here.  Perhaps
33000     ** use FILE_ID_BOTH_DIR_INFO Structure.
33001     */
33002     if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
33003   }
33004   if( pShmNode ){
33005     sqlite3_free(pNew);
33006   }else{
33007     pShmNode = pNew;
33008     pNew = 0;
33009     ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
33010     pShmNode->pNext = winShmNodeList;
33011     winShmNodeList = pShmNode;
33012
33013     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
33014     if( pShmNode->mutex==0 ){
33015       rc = SQLITE_NOMEM;
33016       goto shm_open_err;
33017     }
33018
33019     rc = winOpen(pDbFd->pVfs,
33020                  pShmNode->zFilename,             /* Name of the file (UTF-8) */
33021                  (sqlite3_file*)&pShmNode->hFile,  /* File handle here */
33022                  SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, /* Mode flags */
33023                  0);
33024     if( SQLITE_OK!=rc ){
33025       rc = SQLITE_CANTOPEN_BKPT;
33026       goto shm_open_err;
33027     }
33028
33029     /* Check to see if another process is holding the dead-man switch.
33030     ** If not, truncate the file to zero length. 
33031     */
33032     if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
33033       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
33034       if( rc!=SQLITE_OK ){
33035         rc = winLogError(SQLITE_IOERR_SHMOPEN, "winOpenShm", pDbFd->zPath);
33036       }
33037     }
33038     if( rc==SQLITE_OK ){
33039       winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
33040       rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
33041     }
33042     if( rc ) goto shm_open_err;
33043   }
33044
33045   /* Make the new connection a child of the winShmNode */
33046   p->pShmNode = pShmNode;
33047 #ifdef SQLITE_DEBUG
33048   p->id = pShmNode->nextShmId++;
33049 #endif
33050   pShmNode->nRef++;
33051   pDbFd->pShm = p;
33052   winShmLeaveMutex();
33053
33054   /* The reference count on pShmNode has already been incremented under
33055   ** the cover of the winShmEnterMutex() mutex and the pointer from the
33056   ** new (struct winShm) object to the pShmNode has been set. All that is
33057   ** left to do is to link the new object into the linked list starting
33058   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex 
33059   ** mutex.
33060   */
33061   sqlite3_mutex_enter(pShmNode->mutex);
33062   p->pNext = pShmNode->pFirst;
33063   pShmNode->pFirst = p;
33064   sqlite3_mutex_leave(pShmNode->mutex);
33065   return SQLITE_OK;
33066
33067   /* Jump here on any error */
33068 shm_open_err:
33069   winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
33070   winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */
33071   sqlite3_free(p);
33072   sqlite3_free(pNew);
33073   winShmLeaveMutex();
33074   return rc;
33075 }
33076
33077 /*
33078 ** Close a connection to shared-memory.  Delete the underlying 
33079 ** storage if deleteFlag is true.
33080 */
33081 static int winShmUnmap(
33082   sqlite3_file *fd,          /* Database holding shared memory */
33083   int deleteFlag             /* Delete after closing if true */
33084 ){
33085   winFile *pDbFd;       /* Database holding shared-memory */
33086   winShm *p;            /* The connection to be closed */
33087   winShmNode *pShmNode; /* The underlying shared-memory file */
33088   winShm **pp;          /* For looping over sibling connections */
33089
33090   pDbFd = (winFile*)fd;
33091   p = pDbFd->pShm;
33092   if( p==0 ) return SQLITE_OK;
33093   pShmNode = p->pShmNode;
33094
33095   /* Remove connection p from the set of connections associated
33096   ** with pShmNode */
33097   sqlite3_mutex_enter(pShmNode->mutex);
33098   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
33099   *pp = p->pNext;
33100
33101   /* Free the connection p */
33102   sqlite3_free(p);
33103   pDbFd->pShm = 0;
33104   sqlite3_mutex_leave(pShmNode->mutex);
33105
33106   /* If pShmNode->nRef has reached 0, then close the underlying
33107   ** shared-memory file, too */
33108   winShmEnterMutex();
33109   assert( pShmNode->nRef>0 );
33110   pShmNode->nRef--;
33111   if( pShmNode->nRef==0 ){
33112     winShmPurge(pDbFd->pVfs, deleteFlag);
33113   }
33114   winShmLeaveMutex();
33115
33116   return SQLITE_OK;
33117 }
33118
33119 /*
33120 ** Change the lock state for a shared-memory segment.
33121 */
33122 static int winShmLock(
33123   sqlite3_file *fd,          /* Database file holding the shared memory */
33124   int ofst,                  /* First lock to acquire or release */
33125   int n,                     /* Number of locks to acquire or release */
33126   int flags                  /* What to do with the lock */
33127 ){
33128   winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */
33129   winShm *p = pDbFd->pShm;              /* The shared memory being locked */
33130   winShm *pX;                           /* For looping over all siblings */
33131   winShmNode *pShmNode = p->pShmNode;
33132   int rc = SQLITE_OK;                   /* Result code */
33133   u16 mask;                             /* Mask of locks to take or release */
33134
33135   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
33136   assert( n>=1 );
33137   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
33138        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
33139        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
33140        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
33141   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
33142
33143   mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
33144   assert( n>1 || mask==(1<<ofst) );
33145   sqlite3_mutex_enter(pShmNode->mutex);
33146   if( flags & SQLITE_SHM_UNLOCK ){
33147     u16 allMask = 0; /* Mask of locks held by siblings */
33148
33149     /* See if any siblings hold this same lock */
33150     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
33151       if( pX==p ) continue;
33152       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
33153       allMask |= pX->sharedMask;
33154     }
33155
33156     /* Unlock the system-level locks */
33157     if( (mask & allMask)==0 ){
33158       rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
33159     }else{
33160       rc = SQLITE_OK;
33161     }
33162
33163     /* Undo the local locks */
33164     if( rc==SQLITE_OK ){
33165       p->exclMask &= ~mask;
33166       p->sharedMask &= ~mask;
33167     } 
33168   }else if( flags & SQLITE_SHM_SHARED ){
33169     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
33170
33171     /* Find out which shared locks are already held by sibling connections.
33172     ** If any sibling already holds an exclusive lock, go ahead and return
33173     ** SQLITE_BUSY.
33174     */
33175     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
33176       if( (pX->exclMask & mask)!=0 ){
33177         rc = SQLITE_BUSY;
33178         break;
33179       }
33180       allShared |= pX->sharedMask;
33181     }
33182
33183     /* Get shared locks at the system level, if necessary */
33184     if( rc==SQLITE_OK ){
33185       if( (allShared & mask)==0 ){
33186         rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
33187       }else{
33188         rc = SQLITE_OK;
33189       }
33190     }
33191
33192     /* Get the local shared locks */
33193     if( rc==SQLITE_OK ){
33194       p->sharedMask |= mask;
33195     }
33196   }else{
33197     /* Make sure no sibling connections hold locks that will block this
33198     ** lock.  If any do, return SQLITE_BUSY right away.
33199     */
33200     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
33201       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
33202         rc = SQLITE_BUSY;
33203         break;
33204       }
33205     }
33206   
33207     /* Get the exclusive locks at the system level.  Then if successful
33208     ** also mark the local connection as being locked.
33209     */
33210     if( rc==SQLITE_OK ){
33211       rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
33212       if( rc==SQLITE_OK ){
33213         assert( (p->sharedMask & mask)==0 );
33214         p->exclMask |= mask;
33215       }
33216     }
33217   }
33218   sqlite3_mutex_leave(pShmNode->mutex);
33219   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
33220            p->id, (int)GetCurrentProcessId(), p->sharedMask, p->exclMask,
33221            rc ? "failed" : "ok"));
33222   return rc;
33223 }
33224
33225 /*
33226 ** Implement a memory barrier or memory fence on shared memory.  
33227 **
33228 ** All loads and stores begun before the barrier must complete before
33229 ** any load or store begun after the barrier.
33230 */
33231 static void winShmBarrier(
33232   sqlite3_file *fd          /* Database holding the shared memory */
33233 ){
33234   UNUSED_PARAMETER(fd);
33235   /* MemoryBarrier(); // does not work -- do not know why not */
33236   winShmEnterMutex();
33237   winShmLeaveMutex();
33238 }
33239
33240 /*
33241 ** This function is called to obtain a pointer to region iRegion of the 
33242 ** shared-memory associated with the database file fd. Shared-memory regions 
33243 ** are numbered starting from zero. Each shared-memory region is szRegion 
33244 ** bytes in size.
33245 **
33246 ** If an error occurs, an error code is returned and *pp is set to NULL.
33247 **
33248 ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
33249 ** region has not been allocated (by any client, including one running in a
33250 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If 
33251 ** isWrite is non-zero and the requested shared-memory region has not yet 
33252 ** been allocated, it is allocated by this function.
33253 **
33254 ** If the shared-memory region has already been allocated or is allocated by
33255 ** this call as described above, then it is mapped into this processes 
33256 ** address space (if it is not already), *pp is set to point to the mapped 
33257 ** memory and SQLITE_OK returned.
33258 */
33259 static int winShmMap(
33260   sqlite3_file *fd,               /* Handle open on database file */
33261   int iRegion,                    /* Region to retrieve */
33262   int szRegion,                   /* Size of regions */
33263   int isWrite,                    /* True to extend file if necessary */
33264   void volatile **pp              /* OUT: Mapped memory */
33265 ){
33266   winFile *pDbFd = (winFile*)fd;
33267   winShm *p = pDbFd->pShm;
33268   winShmNode *pShmNode;
33269   int rc = SQLITE_OK;
33270
33271   if( !p ){
33272     rc = winOpenSharedMemory(pDbFd);
33273     if( rc!=SQLITE_OK ) return rc;
33274     p = pDbFd->pShm;
33275   }
33276   pShmNode = p->pShmNode;
33277
33278   sqlite3_mutex_enter(pShmNode->mutex);
33279   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
33280
33281   if( pShmNode->nRegion<=iRegion ){
33282     struct ShmRegion *apNew;           /* New aRegion[] array */
33283     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
33284     sqlite3_int64 sz;                  /* Current size of wal-index file */
33285
33286     pShmNode->szRegion = szRegion;
33287
33288     /* The requested region is not mapped into this processes address space.
33289     ** Check to see if it has been allocated (i.e. if the wal-index file is
33290     ** large enough to contain the requested region).
33291     */
33292     rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
33293     if( rc!=SQLITE_OK ){
33294       rc = winLogError(SQLITE_IOERR_SHMSIZE, "winShmMap1", pDbFd->zPath);
33295       goto shmpage_out;
33296     }
33297
33298     if( sz<nByte ){
33299       /* The requested memory region does not exist. If isWrite is set to
33300       ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
33301       **
33302       ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
33303       ** the requested memory region.
33304       */
33305       if( !isWrite ) goto shmpage_out;
33306       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
33307       if( rc!=SQLITE_OK ){
33308         rc = winLogError(SQLITE_IOERR_SHMSIZE, "winShmMap2", pDbFd->zPath);
33309         goto shmpage_out;
33310       }
33311     }
33312
33313     /* Map the requested memory region into this processes address space. */
33314     apNew = (struct ShmRegion *)sqlite3_realloc(
33315         pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
33316     );
33317     if( !apNew ){
33318       rc = SQLITE_IOERR_NOMEM;
33319       goto shmpage_out;
33320     }
33321     pShmNode->aRegion = apNew;
33322
33323     while( pShmNode->nRegion<=iRegion ){
33324       HANDLE hMap;                /* file-mapping handle */
33325       void *pMap = 0;             /* Mapped memory region */
33326      
33327       hMap = CreateFileMapping(pShmNode->hFile.h, 
33328           NULL, PAGE_READWRITE, 0, nByte, NULL
33329       );
33330       OSTRACE(("SHM-MAP pid-%d create region=%d nbyte=%d %s\n",
33331                (int)GetCurrentProcessId(), pShmNode->nRegion, nByte,
33332                hMap ? "ok" : "failed"));
33333       if( hMap ){
33334         int iOffset = pShmNode->nRegion*szRegion;
33335         int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
33336         pMap = MapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
33337             0, iOffset - iOffsetShift, szRegion + iOffsetShift
33338         );
33339         OSTRACE(("SHM-MAP pid-%d map region=%d offset=%d size=%d %s\n",
33340                  (int)GetCurrentProcessId(), pShmNode->nRegion, iOffset, szRegion,
33341                  pMap ? "ok" : "failed"));
33342       }
33343       if( !pMap ){
33344         pShmNode->lastErrno = GetLastError();
33345         rc = winLogError(SQLITE_IOERR_SHMMAP, "winShmMap3", pDbFd->zPath);
33346         if( hMap ) CloseHandle(hMap);
33347         goto shmpage_out;
33348       }
33349
33350       pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
33351       pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
33352       pShmNode->nRegion++;
33353     }
33354   }
33355
33356 shmpage_out:
33357   if( pShmNode->nRegion>iRegion ){
33358     int iOffset = iRegion*szRegion;
33359     int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
33360     char *p = (char *)pShmNode->aRegion[iRegion].pMap;
33361     *pp = (void *)&p[iOffsetShift];
33362   }else{
33363     *pp = 0;
33364   }
33365   sqlite3_mutex_leave(pShmNode->mutex);
33366   return rc;
33367 }
33368
33369 #else
33370 # define winShmMap     0
33371 # define winShmLock    0
33372 # define winShmBarrier 0
33373 # define winShmUnmap   0
33374 #endif /* #ifndef SQLITE_OMIT_WAL */
33375
33376 /*
33377 ** Here ends the implementation of all sqlite3_file methods.
33378 **
33379 ********************** End sqlite3_file Methods *******************************
33380 ******************************************************************************/
33381
33382 /*
33383 ** This vector defines all the methods that can operate on an
33384 ** sqlite3_file for win32.
33385 */
33386 static const sqlite3_io_methods winIoMethod = {
33387   2,                              /* iVersion */
33388   winClose,                       /* xClose */
33389   winRead,                        /* xRead */
33390   winWrite,                       /* xWrite */
33391   winTruncate,                    /* xTruncate */
33392   winSync,                        /* xSync */
33393   winFileSize,                    /* xFileSize */
33394   winLock,                        /* xLock */
33395   winUnlock,                      /* xUnlock */
33396   winCheckReservedLock,           /* xCheckReservedLock */
33397   winFileControl,                 /* xFileControl */
33398   winSectorSize,                  /* xSectorSize */
33399   winDeviceCharacteristics,       /* xDeviceCharacteristics */
33400   winShmMap,                      /* xShmMap */
33401   winShmLock,                     /* xShmLock */
33402   winShmBarrier,                  /* xShmBarrier */
33403   winShmUnmap                     /* xShmUnmap */
33404 };
33405
33406 /****************************************************************************
33407 **************************** sqlite3_vfs methods ****************************
33408 **
33409 ** This division contains the implementation of methods on the
33410 ** sqlite3_vfs object.
33411 */
33412
33413 /*
33414 ** Convert a UTF-8 filename into whatever form the underlying
33415 ** operating system wants filenames in.  Space to hold the result
33416 ** is obtained from malloc and must be freed by the calling
33417 ** function.
33418 */
33419 static void *convertUtf8Filename(const char *zFilename){
33420   void *zConverted = 0;
33421   if( isNT() ){
33422     zConverted = utf8ToUnicode(zFilename);
33423 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
33424 */
33425 #if SQLITE_OS_WINCE==0
33426   }else{
33427     zConverted = sqlite3_win32_utf8_to_mbcs(zFilename);
33428 #endif
33429   }
33430   /* caller will handle out of memory */
33431   return zConverted;
33432 }
33433
33434 /*
33435 ** Create a temporary file name in zBuf.  zBuf must be big enough to
33436 ** hold at pVfs->mxPathname characters.
33437 */
33438 static int getTempname(int nBuf, char *zBuf){
33439   static char zChars[] =
33440     "abcdefghijklmnopqrstuvwxyz"
33441     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
33442     "0123456789";
33443   size_t i, j;
33444   char zTempPath[MAX_PATH+1];
33445
33446   /* It's odd to simulate an io-error here, but really this is just
33447   ** using the io-error infrastructure to test that SQLite handles this
33448   ** function failing. 
33449   */
33450   SimulateIOError( return SQLITE_IOERR );
33451
33452   if( sqlite3_temp_directory ){
33453     sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
33454   }else if( isNT() ){
33455     char *zMulti;
33456     WCHAR zWidePath[MAX_PATH];
33457     GetTempPathW(MAX_PATH-30, zWidePath);
33458     zMulti = unicodeToUtf8(zWidePath);
33459     if( zMulti ){
33460       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
33461       free(zMulti);
33462     }else{
33463       return SQLITE_NOMEM;
33464     }
33465 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
33466 ** Since the ASCII version of these Windows API do not exist for WINCE,
33467 ** it's important to not reference them for WINCE builds.
33468 */
33469 #if SQLITE_OS_WINCE==0
33470   }else{
33471     char *zUtf8;
33472     char zMbcsPath[MAX_PATH];
33473     GetTempPathA(MAX_PATH-30, zMbcsPath);
33474     zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
33475     if( zUtf8 ){
33476       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
33477       free(zUtf8);
33478     }else{
33479       return SQLITE_NOMEM;
33480     }
33481 #endif
33482   }
33483
33484   /* Check that the output buffer is large enough for the temporary file 
33485   ** name. If it is not, return SQLITE_ERROR.
33486   */
33487   if( (sqlite3Strlen30(zTempPath) + sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX) + 17) >= nBuf ){
33488     return SQLITE_ERROR;
33489   }
33490
33491   for(i=sqlite3Strlen30(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
33492   zTempPath[i] = 0;
33493
33494   sqlite3_snprintf(nBuf-17, zBuf,
33495                    "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
33496   j = sqlite3Strlen30(zBuf);
33497   sqlite3_randomness(15, &zBuf[j]);
33498   for(i=0; i<15; i++, j++){
33499     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
33500   }
33501   zBuf[j] = 0;
33502
33503   OSTRACE(("TEMP FILENAME: %s\n", zBuf));
33504   return SQLITE_OK; 
33505 }
33506
33507 /*
33508 ** Open a file.
33509 */
33510 static int winOpen(
33511   sqlite3_vfs *pVfs,        /* Not used */
33512   const char *zName,        /* Name of the file (UTF-8) */
33513   sqlite3_file *id,         /* Write the SQLite file handle here */
33514   int flags,                /* Open mode flags */
33515   int *pOutFlags            /* Status return flags */
33516 ){
33517   HANDLE h;
33518   DWORD dwDesiredAccess;
33519   DWORD dwShareMode;
33520   DWORD dwCreationDisposition;
33521   DWORD dwFlagsAndAttributes = 0;
33522 #if SQLITE_OS_WINCE
33523   int isTemp = 0;
33524 #endif
33525   winFile *pFile = (winFile*)id;
33526   void *zConverted;              /* Filename in OS encoding */
33527   const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
33528
33529   /* If argument zPath is a NULL pointer, this function is required to open
33530   ** a temporary file. Use this buffer to store the file name in.
33531   */
33532   char zTmpname[MAX_PATH+1];     /* Buffer used to create temp filename */
33533
33534   int rc = SQLITE_OK;            /* Function Return Code */
33535 #if !defined(NDEBUG) || SQLITE_OS_WINCE
33536   int eType = flags&0xFFFFFF00;  /* Type of file to open */
33537 #endif
33538
33539   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
33540   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
33541   int isCreate     = (flags & SQLITE_OPEN_CREATE);
33542 #ifndef NDEBUG
33543   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
33544 #endif
33545   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
33546
33547 #ifndef NDEBUG
33548   int isOpenJournal = (isCreate && (
33549         eType==SQLITE_OPEN_MASTER_JOURNAL 
33550      || eType==SQLITE_OPEN_MAIN_JOURNAL 
33551      || eType==SQLITE_OPEN_WAL
33552   ));
33553 #endif
33554
33555   /* Check the following statements are true: 
33556   **
33557   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
33558   **   (b) if CREATE is set, then READWRITE must also be set, and
33559   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
33560   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
33561   */
33562   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
33563   assert(isCreate==0 || isReadWrite);
33564   assert(isExclusive==0 || isCreate);
33565   assert(isDelete==0 || isCreate);
33566
33567   /* The main DB, main journal, WAL file and master journal are never 
33568   ** automatically deleted. Nor are they ever temporary files.  */
33569   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
33570   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
33571   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
33572   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
33573
33574   /* Assert that the upper layer has set one of the "file-type" flags. */
33575   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
33576        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
33577        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
33578        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
33579   );
33580
33581   assert( id!=0 );
33582   UNUSED_PARAMETER(pVfs);
33583
33584   pFile->h = INVALID_HANDLE_VALUE;
33585
33586   /* If the second argument to this function is NULL, generate a 
33587   ** temporary file name to use 
33588   */
33589   if( !zUtf8Name ){
33590     assert(isDelete && !isOpenJournal);
33591     rc = getTempname(MAX_PATH+1, zTmpname);
33592     if( rc!=SQLITE_OK ){
33593       return rc;
33594     }
33595     zUtf8Name = zTmpname;
33596   }
33597
33598   /* Convert the filename to the system encoding. */
33599   zConverted = convertUtf8Filename(zUtf8Name);
33600   if( zConverted==0 ){
33601     return SQLITE_NOMEM;
33602   }
33603
33604   if( isReadWrite ){
33605     dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
33606   }else{
33607     dwDesiredAccess = GENERIC_READ;
33608   }
33609
33610   /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is 
33611   ** created. SQLite doesn't use it to indicate "exclusive access" 
33612   ** as it is usually understood.
33613   */
33614   if( isExclusive ){
33615     /* Creates a new file, only if it does not already exist. */
33616     /* If the file exists, it fails. */
33617     dwCreationDisposition = CREATE_NEW;
33618   }else if( isCreate ){
33619     /* Open existing file, or create if it doesn't exist */
33620     dwCreationDisposition = OPEN_ALWAYS;
33621   }else{
33622     /* Opens a file, only if it exists. */
33623     dwCreationDisposition = OPEN_EXISTING;
33624   }
33625
33626   dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
33627
33628   if( isDelete ){
33629 #if SQLITE_OS_WINCE
33630     dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
33631     isTemp = 1;
33632 #else
33633     dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
33634                                | FILE_ATTRIBUTE_HIDDEN
33635                                | FILE_FLAG_DELETE_ON_CLOSE;
33636 #endif
33637   }else{
33638     dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
33639   }
33640   /* Reports from the internet are that performance is always
33641   ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
33642 #if SQLITE_OS_WINCE
33643   dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
33644 #endif
33645
33646   if( isNT() ){
33647     h = CreateFileW((WCHAR*)zConverted,
33648        dwDesiredAccess,
33649        dwShareMode,
33650        NULL,
33651        dwCreationDisposition,
33652        dwFlagsAndAttributes,
33653        NULL
33654     );
33655 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
33656 ** Since the ASCII version of these Windows API do not exist for WINCE,
33657 ** it's important to not reference them for WINCE builds.
33658 */
33659 #if SQLITE_OS_WINCE==0
33660   }else{
33661     h = CreateFileA((char*)zConverted,
33662        dwDesiredAccess,
33663        dwShareMode,
33664        NULL,
33665        dwCreationDisposition,
33666        dwFlagsAndAttributes,
33667        NULL
33668     );
33669 #endif
33670   }
33671
33672   OSTRACE(("OPEN %d %s 0x%lx %s\n", 
33673            h, zName, dwDesiredAccess, 
33674            h==INVALID_HANDLE_VALUE ? "failed" : "ok"));
33675
33676   if( h==INVALID_HANDLE_VALUE ){
33677     pFile->lastErrno = GetLastError();
33678     winLogError(SQLITE_CANTOPEN, "winOpen", zUtf8Name);
33679     free(zConverted);
33680     if( isReadWrite ){
33681       return winOpen(pVfs, zName, id, 
33682              ((flags|SQLITE_OPEN_READONLY)&~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)), pOutFlags);
33683     }else{
33684       return SQLITE_CANTOPEN_BKPT;
33685     }
33686   }
33687
33688   if( pOutFlags ){
33689     if( isReadWrite ){
33690       *pOutFlags = SQLITE_OPEN_READWRITE;
33691     }else{
33692       *pOutFlags = SQLITE_OPEN_READONLY;
33693     }
33694   }
33695
33696   memset(pFile, 0, sizeof(*pFile));
33697   pFile->pMethod = &winIoMethod;
33698   pFile->h = h;
33699   pFile->lastErrno = NO_ERROR;
33700   pFile->pVfs = pVfs;
33701   pFile->pShm = 0;
33702   pFile->zPath = zName;
33703   pFile->sectorSize = getSectorSize(pVfs, zUtf8Name);
33704
33705 #if SQLITE_OS_WINCE
33706   if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
33707        && !winceCreateLock(zName, pFile)
33708   ){
33709     CloseHandle(h);
33710     free(zConverted);
33711     return SQLITE_CANTOPEN_BKPT;
33712   }
33713   if( isTemp ){
33714     pFile->zDeleteOnClose = zConverted;
33715   }else
33716 #endif
33717   {
33718     free(zConverted);
33719   }
33720
33721   OpenCounter(+1);
33722   return rc;
33723 }
33724
33725 /*
33726 ** Delete the named file.
33727 **
33728 ** Note that windows does not allow a file to be deleted if some other
33729 ** process has it open.  Sometimes a virus scanner or indexing program
33730 ** will open a journal file shortly after it is created in order to do
33731 ** whatever it does.  While this other process is holding the
33732 ** file open, we will be unable to delete it.  To work around this
33733 ** problem, we delay 100 milliseconds and try to delete again.  Up
33734 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
33735 ** up and returning an error.
33736 */
33737 #define MX_DELETION_ATTEMPTS 5
33738 static int winDelete(
33739   sqlite3_vfs *pVfs,          /* Not used on win32 */
33740   const char *zFilename,      /* Name of file to delete */
33741   int syncDir                 /* Not used on win32 */
33742 ){
33743   int cnt = 0;
33744   DWORD rc;
33745   DWORD error = 0;
33746   void *zConverted;
33747   UNUSED_PARAMETER(pVfs);
33748   UNUSED_PARAMETER(syncDir);
33749
33750   SimulateIOError(return SQLITE_IOERR_DELETE);
33751   zConverted = convertUtf8Filename(zFilename);
33752   if( zConverted==0 ){
33753     return SQLITE_NOMEM;
33754   }
33755   if( isNT() ){
33756     do{
33757       DeleteFileW(zConverted);
33758     }while(   (   ((rc = GetFileAttributesW(zConverted)) != INVALID_FILE_ATTRIBUTES)
33759                || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
33760            && (++cnt < MX_DELETION_ATTEMPTS)
33761            && (Sleep(100), 1) );
33762 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
33763 ** Since the ASCII version of these Windows API do not exist for WINCE,
33764 ** it's important to not reference them for WINCE builds.
33765 */
33766 #if SQLITE_OS_WINCE==0
33767   }else{
33768     do{
33769       DeleteFileA(zConverted);
33770     }while(   (   ((rc = GetFileAttributesA(zConverted)) != INVALID_FILE_ATTRIBUTES)
33771                || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
33772            && (++cnt < MX_DELETION_ATTEMPTS)
33773            && (Sleep(100), 1) );
33774 #endif
33775   }
33776   free(zConverted);
33777   OSTRACE(("DELETE \"%s\" %s\n", zFilename,
33778        ( (rc==INVALID_FILE_ATTRIBUTES) && (error==ERROR_FILE_NOT_FOUND)) ?
33779          "ok" : "failed" ));
33780  
33781   return (   (rc == INVALID_FILE_ATTRIBUTES) 
33782           && (error == ERROR_FILE_NOT_FOUND)) ? SQLITE_OK :
33783                  winLogError(SQLITE_IOERR_DELETE, "winDelete", zFilename);
33784 }
33785
33786 /*
33787 ** Check the existance and status of a file.
33788 */
33789 static int winAccess(
33790   sqlite3_vfs *pVfs,         /* Not used on win32 */
33791   const char *zFilename,     /* Name of file to check */
33792   int flags,                 /* Type of test to make on this file */
33793   int *pResOut               /* OUT: Result */
33794 ){
33795   DWORD attr;
33796   int rc = 0;
33797   void *zConverted;
33798   UNUSED_PARAMETER(pVfs);
33799
33800   SimulateIOError( return SQLITE_IOERR_ACCESS; );
33801   zConverted = convertUtf8Filename(zFilename);
33802   if( zConverted==0 ){
33803     return SQLITE_NOMEM;
33804   }
33805   if( isNT() ){
33806     WIN32_FILE_ATTRIBUTE_DATA sAttrData;
33807     memset(&sAttrData, 0, sizeof(sAttrData));
33808     if( GetFileAttributesExW((WCHAR*)zConverted,
33809                              GetFileExInfoStandard, 
33810                              &sAttrData) ){
33811       /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
33812       ** as if it does not exist.
33813       */
33814       if(    flags==SQLITE_ACCESS_EXISTS
33815           && sAttrData.nFileSizeHigh==0 
33816           && sAttrData.nFileSizeLow==0 ){
33817         attr = INVALID_FILE_ATTRIBUTES;
33818       }else{
33819         attr = sAttrData.dwFileAttributes;
33820       }
33821     }else{
33822       if( GetLastError()!=ERROR_FILE_NOT_FOUND ){
33823         winLogError(SQLITE_IOERR_ACCESS, "winAccess", zFilename);
33824         free(zConverted);
33825         return SQLITE_IOERR_ACCESS;
33826       }else{
33827         attr = INVALID_FILE_ATTRIBUTES;
33828       }
33829     }
33830 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
33831 ** Since the ASCII version of these Windows API do not exist for WINCE,
33832 ** it's important to not reference them for WINCE builds.
33833 */
33834 #if SQLITE_OS_WINCE==0
33835   }else{
33836     attr = GetFileAttributesA((char*)zConverted);
33837 #endif
33838   }
33839   free(zConverted);
33840   switch( flags ){
33841     case SQLITE_ACCESS_READ:
33842     case SQLITE_ACCESS_EXISTS:
33843       rc = attr!=INVALID_FILE_ATTRIBUTES;
33844       break;
33845     case SQLITE_ACCESS_READWRITE:
33846       rc = (attr & FILE_ATTRIBUTE_READONLY)==0;
33847       break;
33848     default:
33849       assert(!"Invalid flags argument");
33850   }
33851   *pResOut = rc;
33852   return SQLITE_OK;
33853 }
33854
33855
33856 /*
33857 ** Turn a relative pathname into a full pathname.  Write the full
33858 ** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
33859 ** bytes in size.
33860 */
33861 static int winFullPathname(
33862   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
33863   const char *zRelative,        /* Possibly relative input path */
33864   int nFull,                    /* Size of output buffer in bytes */
33865   char *zFull                   /* Output buffer */
33866 ){
33867   
33868 #if defined(__CYGWIN__)
33869   SimulateIOError( return SQLITE_ERROR );
33870   UNUSED_PARAMETER(nFull);
33871   cygwin_conv_to_full_win32_path(zRelative, zFull);
33872   return SQLITE_OK;
33873 #endif
33874
33875 #if SQLITE_OS_WINCE
33876   SimulateIOError( return SQLITE_ERROR );
33877   UNUSED_PARAMETER(nFull);
33878   /* WinCE has no concept of a relative pathname, or so I am told. */
33879   sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zRelative);
33880   return SQLITE_OK;
33881 #endif
33882
33883 #if !SQLITE_OS_WINCE && !defined(__CYGWIN__)
33884   int nByte;
33885   void *zConverted;
33886   char *zOut;
33887
33888   /* If this path name begins with "/X:", where "X" is any alphabetic
33889   ** character, discard the initial "/" from the pathname.
33890   */
33891   if( zRelative[0]=='/' && sqlite3Isalpha(zRelative[1]) && zRelative[2]==':' ){
33892     zRelative++;
33893   }
33894
33895   /* It's odd to simulate an io-error here, but really this is just
33896   ** using the io-error infrastructure to test that SQLite handles this
33897   ** function failing. This function could fail if, for example, the
33898   ** current working directory has been unlinked.
33899   */
33900   SimulateIOError( return SQLITE_ERROR );
33901   UNUSED_PARAMETER(nFull);
33902   zConverted = convertUtf8Filename(zRelative);
33903   if( isNT() ){
33904     WCHAR *zTemp;
33905     nByte = GetFullPathNameW((WCHAR*)zConverted, 0, 0, 0) + 3;
33906     zTemp = malloc( nByte*sizeof(zTemp[0]) );
33907     if( zTemp==0 ){
33908       free(zConverted);
33909       return SQLITE_NOMEM;
33910     }
33911     GetFullPathNameW((WCHAR*)zConverted, nByte, zTemp, 0);
33912     free(zConverted);
33913     zOut = unicodeToUtf8(zTemp);
33914     free(zTemp);
33915 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
33916 ** Since the ASCII version of these Windows API do not exist for WINCE,
33917 ** it's important to not reference them for WINCE builds.
33918 */
33919 #if SQLITE_OS_WINCE==0
33920   }else{
33921     char *zTemp;
33922     nByte = GetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
33923     zTemp = malloc( nByte*sizeof(zTemp[0]) );
33924     if( zTemp==0 ){
33925       free(zConverted);
33926       return SQLITE_NOMEM;
33927     }
33928     GetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
33929     free(zConverted);
33930     zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
33931     free(zTemp);
33932 #endif
33933   }
33934   if( zOut ){
33935     sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zOut);
33936     free(zOut);
33937     return SQLITE_OK;
33938   }else{
33939     return SQLITE_NOMEM;
33940   }
33941 #endif
33942 }
33943
33944 /*
33945 ** Get the sector size of the device used to store
33946 ** file.
33947 */
33948 static int getSectorSize(
33949     sqlite3_vfs *pVfs,
33950     const char *zRelative     /* UTF-8 file name */
33951 ){
33952   DWORD bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
33953   /* GetDiskFreeSpace is not supported under WINCE */
33954 #if SQLITE_OS_WINCE
33955   UNUSED_PARAMETER(pVfs);
33956   UNUSED_PARAMETER(zRelative);
33957 #else
33958   char zFullpath[MAX_PATH+1];
33959   int rc;
33960   DWORD dwRet = 0;
33961   DWORD dwDummy;
33962
33963   /*
33964   ** We need to get the full path name of the file
33965   ** to get the drive letter to look up the sector
33966   ** size.
33967   */
33968   SimulateIOErrorBenign(1);
33969   rc = winFullPathname(pVfs, zRelative, MAX_PATH, zFullpath);
33970   SimulateIOErrorBenign(0);
33971   if( rc == SQLITE_OK )
33972   {
33973     void *zConverted = convertUtf8Filename(zFullpath);
33974     if( zConverted ){
33975       if( isNT() ){
33976         /* trim path to just drive reference */
33977         WCHAR *p = zConverted;
33978         for(;*p;p++){
33979           if( *p == '\\' ){
33980             *p = '\0';
33981             break;
33982           }
33983         }
33984         dwRet = GetDiskFreeSpaceW((WCHAR*)zConverted,
33985                                   &dwDummy,
33986                                   &bytesPerSector,
33987                                   &dwDummy,
33988                                   &dwDummy);
33989       }else{
33990         /* trim path to just drive reference */
33991         char *p = (char *)zConverted;
33992         for(;*p;p++){
33993           if( *p == '\\' ){
33994             *p = '\0';
33995             break;
33996           }
33997         }
33998         dwRet = GetDiskFreeSpaceA((char*)zConverted,
33999                                   &dwDummy,
34000                                   &bytesPerSector,
34001                                   &dwDummy,
34002                                   &dwDummy);
34003       }
34004       free(zConverted);
34005     }
34006     if( !dwRet ){
34007       bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
34008     }
34009   }
34010 #endif
34011   return (int) bytesPerSector; 
34012 }
34013
34014 #ifndef SQLITE_OMIT_LOAD_EXTENSION
34015 /*
34016 ** Interfaces for opening a shared library, finding entry points
34017 ** within the shared library, and closing the shared library.
34018 */
34019 /*
34020 ** Interfaces for opening a shared library, finding entry points
34021 ** within the shared library, and closing the shared library.
34022 */
34023 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
34024   HANDLE h;
34025   void *zConverted = convertUtf8Filename(zFilename);
34026   UNUSED_PARAMETER(pVfs);
34027   if( zConverted==0 ){
34028     return 0;
34029   }
34030   if( isNT() ){
34031     h = LoadLibraryW((WCHAR*)zConverted);
34032 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
34033 ** Since the ASCII version of these Windows API do not exist for WINCE,
34034 ** it's important to not reference them for WINCE builds.
34035 */
34036 #if SQLITE_OS_WINCE==0
34037   }else{
34038     h = LoadLibraryA((char*)zConverted);
34039 #endif
34040   }
34041   free(zConverted);
34042   return (void*)h;
34043 }
34044 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
34045   UNUSED_PARAMETER(pVfs);
34046   getLastErrorMsg(nBuf, zBufOut);
34047 }
34048 void (*winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
34049   UNUSED_PARAMETER(pVfs);
34050 #if SQLITE_OS_WINCE
34051   /* The GetProcAddressA() routine is only available on wince. */
34052   return (void(*)(void))GetProcAddressA((HANDLE)pHandle, zSymbol);
34053 #else
34054   /* All other windows platforms expect GetProcAddress() to take
34055   ** an Ansi string regardless of the _UNICODE setting */
34056   return (void(*)(void))GetProcAddress((HANDLE)pHandle, zSymbol);
34057 #endif
34058 }
34059 void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
34060   UNUSED_PARAMETER(pVfs);
34061   FreeLibrary((HANDLE)pHandle);
34062 }
34063 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
34064   #define winDlOpen  0
34065   #define winDlError 0
34066   #define winDlSym   0
34067   #define winDlClose 0
34068 #endif
34069
34070
34071 /*
34072 ** Write up to nBuf bytes of randomness into zBuf.
34073 */
34074 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
34075   int n = 0;
34076   UNUSED_PARAMETER(pVfs);
34077 #if defined(SQLITE_TEST)
34078   n = nBuf;
34079   memset(zBuf, 0, nBuf);
34080 #else
34081   if( sizeof(SYSTEMTIME)<=nBuf-n ){
34082     SYSTEMTIME x;
34083     GetSystemTime(&x);
34084     memcpy(&zBuf[n], &x, sizeof(x));
34085     n += sizeof(x);
34086   }
34087   if( sizeof(DWORD)<=nBuf-n ){
34088     DWORD pid = GetCurrentProcessId();
34089     memcpy(&zBuf[n], &pid, sizeof(pid));
34090     n += sizeof(pid);
34091   }
34092   if( sizeof(DWORD)<=nBuf-n ){
34093     DWORD cnt = GetTickCount();
34094     memcpy(&zBuf[n], &cnt, sizeof(cnt));
34095     n += sizeof(cnt);
34096   }
34097   if( sizeof(LARGE_INTEGER)<=nBuf-n ){
34098     LARGE_INTEGER i;
34099     QueryPerformanceCounter(&i);
34100     memcpy(&zBuf[n], &i, sizeof(i));
34101     n += sizeof(i);
34102   }
34103 #endif
34104   return n;
34105 }
34106
34107
34108 /*
34109 ** Sleep for a little while.  Return the amount of time slept.
34110 */
34111 static int winSleep(sqlite3_vfs *pVfs, int microsec){
34112   Sleep((microsec+999)/1000);
34113   UNUSED_PARAMETER(pVfs);
34114   return ((microsec+999)/1000)*1000;
34115 }
34116
34117 /*
34118 ** The following variable, if set to a non-zero value, is interpreted as
34119 ** the number of seconds since 1970 and is used to set the result of
34120 ** sqlite3OsCurrentTime() during testing.
34121 */
34122 #ifdef SQLITE_TEST
34123 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
34124 #endif
34125
34126 /*
34127 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
34128 ** the current time and date as a Julian Day number times 86_400_000.  In
34129 ** other words, write into *piNow the number of milliseconds since the Julian
34130 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
34131 ** proleptic Gregorian calendar.
34132 **
34133 ** On success, return 0.  Return 1 if the time and date cannot be found.
34134 */
34135 static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
34136   /* FILETIME structure is a 64-bit value representing the number of 
34137      100-nanosecond intervals since January 1, 1601 (= JD 2305813.5). 
34138   */
34139   FILETIME ft;
34140   static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
34141 #ifdef SQLITE_TEST
34142   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
34143 #endif
34144   /* 2^32 - to avoid use of LL and warnings in gcc */
34145   static const sqlite3_int64 max32BitValue = 
34146       (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + (sqlite3_int64)294967296;
34147
34148 #if SQLITE_OS_WINCE
34149   SYSTEMTIME time;
34150   GetSystemTime(&time);
34151   /* if SystemTimeToFileTime() fails, it returns zero. */
34152   if (!SystemTimeToFileTime(&time,&ft)){
34153     return 1;
34154   }
34155 #else
34156   GetSystemTimeAsFileTime( &ft );
34157 #endif
34158
34159   *piNow = winFiletimeEpoch +
34160             ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) + 
34161                (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
34162
34163 #ifdef SQLITE_TEST
34164   if( sqlite3_current_time ){
34165     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
34166   }
34167 #endif
34168   UNUSED_PARAMETER(pVfs);
34169   return 0;
34170 }
34171
34172 /*
34173 ** Find the current time (in Universal Coordinated Time).  Write the
34174 ** current time and date as a Julian Day number into *prNow and
34175 ** return 0.  Return 1 if the time and date cannot be found.
34176 */
34177 int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
34178   int rc;
34179   sqlite3_int64 i;
34180   rc = winCurrentTimeInt64(pVfs, &i);
34181   if( !rc ){
34182     *prNow = i/86400000.0;
34183   }
34184   return rc;
34185 }
34186
34187 /*
34188 ** The idea is that this function works like a combination of
34189 ** GetLastError() and FormatMessage() on windows (or errno and
34190 ** strerror_r() on unix). After an error is returned by an OS
34191 ** function, SQLite calls this function with zBuf pointing to
34192 ** a buffer of nBuf bytes. The OS layer should populate the
34193 ** buffer with a nul-terminated UTF-8 encoded error message
34194 ** describing the last IO error to have occurred within the calling
34195 ** thread.
34196 **
34197 ** If the error message is too large for the supplied buffer,
34198 ** it should be truncated. The return value of xGetLastError
34199 ** is zero if the error message fits in the buffer, or non-zero
34200 ** otherwise (if the message was truncated). If non-zero is returned,
34201 ** then it is not necessary to include the nul-terminator character
34202 ** in the output buffer.
34203 **
34204 ** Not supplying an error message will have no adverse effect
34205 ** on SQLite. It is fine to have an implementation that never
34206 ** returns an error message:
34207 **
34208 **   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
34209 **     assert(zBuf[0]=='\0');
34210 **     return 0;
34211 **   }
34212 **
34213 ** However if an error message is supplied, it will be incorporated
34214 ** by sqlite into the error message available to the user using
34215 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
34216 */
34217 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
34218   UNUSED_PARAMETER(pVfs);
34219   return getLastErrorMsg(nBuf, zBuf);
34220 }
34221
34222
34223
34224 /*
34225 ** Initialize and deinitialize the operating system interface.
34226 */
34227 SQLITE_API int sqlite3_os_init(void){
34228   static sqlite3_vfs winVfs = {
34229     3,                   /* iVersion */
34230     sizeof(winFile),     /* szOsFile */
34231     MAX_PATH,            /* mxPathname */
34232     0,                   /* pNext */
34233     "win32",             /* zName */
34234     0,                   /* pAppData */
34235     winOpen,             /* xOpen */
34236     winDelete,           /* xDelete */
34237     winAccess,           /* xAccess */
34238     winFullPathname,     /* xFullPathname */
34239     winDlOpen,           /* xDlOpen */
34240     winDlError,          /* xDlError */
34241     winDlSym,            /* xDlSym */
34242     winDlClose,          /* xDlClose */
34243     winRandomness,       /* xRandomness */
34244     winSleep,            /* xSleep */
34245     winCurrentTime,      /* xCurrentTime */
34246     winGetLastError,     /* xGetLastError */
34247     winCurrentTimeInt64, /* xCurrentTimeInt64 */
34248     0,                   /* xSetSystemCall */
34249     0,                   /* xGetSystemCall */
34250     0,                   /* xNextSystemCall */
34251   };
34252
34253 #ifndef SQLITE_OMIT_WAL
34254   /* get memory map allocation granularity */
34255   memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
34256   GetSystemInfo(&winSysInfo);
34257   assert(winSysInfo.dwAllocationGranularity > 0);
34258 #endif
34259
34260   sqlite3_vfs_register(&winVfs, 1);
34261   return SQLITE_OK; 
34262 }
34263 SQLITE_API int sqlite3_os_end(void){ 
34264   return SQLITE_OK;
34265 }
34266
34267 #endif /* SQLITE_OS_WIN */
34268
34269 /************** End of os_win.c **********************************************/
34270 /************** Begin file bitvec.c ******************************************/
34271 /*
34272 ** 2008 February 16
34273 **
34274 ** The author disclaims copyright to this source code.  In place of
34275 ** a legal notice, here is a blessing:
34276 **
34277 **    May you do good and not evil.
34278 **    May you find forgiveness for yourself and forgive others.
34279 **    May you share freely, never taking more than you give.
34280 **
34281 *************************************************************************
34282 ** This file implements an object that represents a fixed-length
34283 ** bitmap.  Bits are numbered starting with 1.
34284 **
34285 ** A bitmap is used to record which pages of a database file have been
34286 ** journalled during a transaction, or which pages have the "dont-write"
34287 ** property.  Usually only a few pages are meet either condition.
34288 ** So the bitmap is usually sparse and has low cardinality.
34289 ** But sometimes (for example when during a DROP of a large table) most
34290 ** or all of the pages in a database can get journalled.  In those cases, 
34291 ** the bitmap becomes dense with high cardinality.  The algorithm needs 
34292 ** to handle both cases well.
34293 **
34294 ** The size of the bitmap is fixed when the object is created.
34295 **
34296 ** All bits are clear when the bitmap is created.  Individual bits
34297 ** may be set or cleared one at a time.
34298 **
34299 ** Test operations are about 100 times more common that set operations.
34300 ** Clear operations are exceedingly rare.  There are usually between
34301 ** 5 and 500 set operations per Bitvec object, though the number of sets can
34302 ** sometimes grow into tens of thousands or larger.  The size of the
34303 ** Bitvec object is the number of pages in the database file at the
34304 ** start of a transaction, and is thus usually less than a few thousand,
34305 ** but can be as large as 2 billion for a really big database.
34306 */
34307
34308 /* Size of the Bitvec structure in bytes. */
34309 #define BITVEC_SZ        512
34310
34311 /* Round the union size down to the nearest pointer boundary, since that's how 
34312 ** it will be aligned within the Bitvec struct. */
34313 #define BITVEC_USIZE     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
34314
34315 /* Type of the array "element" for the bitmap representation. 
34316 ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE. 
34317 ** Setting this to the "natural word" size of your CPU may improve
34318 ** performance. */
34319 #define BITVEC_TELEM     u8
34320 /* Size, in bits, of the bitmap element. */
34321 #define BITVEC_SZELEM    8
34322 /* Number of elements in a bitmap array. */
34323 #define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
34324 /* Number of bits in the bitmap array. */
34325 #define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
34326
34327 /* Number of u32 values in hash table. */
34328 #define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
34329 /* Maximum number of entries in hash table before 
34330 ** sub-dividing and re-hashing. */
34331 #define BITVEC_MXHASH    (BITVEC_NINT/2)
34332 /* Hashing function for the aHash representation.
34333 ** Empirical testing showed that the *37 multiplier 
34334 ** (an arbitrary prime)in the hash function provided 
34335 ** no fewer collisions than the no-op *1. */
34336 #define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
34337
34338 #define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
34339
34340
34341 /*
34342 ** A bitmap is an instance of the following structure.
34343 **
34344 ** This bitmap records the existance of zero or more bits
34345 ** with values between 1 and iSize, inclusive.
34346 **
34347 ** There are three possible representations of the bitmap.
34348 ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
34349 ** bitmap.  The least significant bit is bit 1.
34350 **
34351 ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
34352 ** a hash table that will hold up to BITVEC_MXHASH distinct values.
34353 **
34354 ** Otherwise, the value i is redirected into one of BITVEC_NPTR
34355 ** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
34356 ** handles up to iDivisor separate values of i.  apSub[0] holds
34357 ** values between 1 and iDivisor.  apSub[1] holds values between
34358 ** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
34359 ** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
34360 ** to hold deal with values between 1 and iDivisor.
34361 */
34362 struct Bitvec {
34363   u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
34364   u32 nSet;       /* Number of bits that are set - only valid for aHash
34365                   ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
34366                   ** this would be 125. */
34367   u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
34368                   /* Should >=0 for apSub element. */
34369                   /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
34370                   /* For a BITVEC_SZ of 512, this would be 34,359,739. */
34371   union {
34372     BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
34373     u32 aHash[BITVEC_NINT];      /* Hash table representation */
34374     Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
34375   } u;
34376 };
34377
34378 /*
34379 ** Create a new bitmap object able to handle bits between 0 and iSize,
34380 ** inclusive.  Return a pointer to the new object.  Return NULL if 
34381 ** malloc fails.
34382 */
34383 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
34384   Bitvec *p;
34385   assert( sizeof(*p)==BITVEC_SZ );
34386   p = sqlite3MallocZero( sizeof(*p) );
34387   if( p ){
34388     p->iSize = iSize;
34389   }
34390   return p;
34391 }
34392
34393 /*
34394 ** Check to see if the i-th bit is set.  Return true or false.
34395 ** If p is NULL (if the bitmap has not been created) or if
34396 ** i is out of range, then return false.
34397 */
34398 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
34399   if( p==0 ) return 0;
34400   if( i>p->iSize || i==0 ) return 0;
34401   i--;
34402   while( p->iDivisor ){
34403     u32 bin = i/p->iDivisor;
34404     i = i%p->iDivisor;
34405     p = p->u.apSub[bin];
34406     if (!p) {
34407       return 0;
34408     }
34409   }
34410   if( p->iSize<=BITVEC_NBIT ){
34411     return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
34412   } else{
34413     u32 h = BITVEC_HASH(i++);
34414     while( p->u.aHash[h] ){
34415       if( p->u.aHash[h]==i ) return 1;
34416       h = (h+1) % BITVEC_NINT;
34417     }
34418     return 0;
34419   }
34420 }
34421
34422 /*
34423 ** Set the i-th bit.  Return 0 on success and an error code if
34424 ** anything goes wrong.
34425 **
34426 ** This routine might cause sub-bitmaps to be allocated.  Failing
34427 ** to get the memory needed to hold the sub-bitmap is the only
34428 ** that can go wrong with an insert, assuming p and i are valid.
34429 **
34430 ** The calling function must ensure that p is a valid Bitvec object
34431 ** and that the value for "i" is within range of the Bitvec object.
34432 ** Otherwise the behavior is undefined.
34433 */
34434 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
34435   u32 h;
34436   if( p==0 ) return SQLITE_OK;
34437   assert( i>0 );
34438   assert( i<=p->iSize );
34439   i--;
34440   while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
34441     u32 bin = i/p->iDivisor;
34442     i = i%p->iDivisor;
34443     if( p->u.apSub[bin]==0 ){
34444       p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
34445       if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
34446     }
34447     p = p->u.apSub[bin];
34448   }
34449   if( p->iSize<=BITVEC_NBIT ){
34450     p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
34451     return SQLITE_OK;
34452   }
34453   h = BITVEC_HASH(i++);
34454   /* if there wasn't a hash collision, and this doesn't */
34455   /* completely fill the hash, then just add it without */
34456   /* worring about sub-dividing and re-hashing. */
34457   if( !p->u.aHash[h] ){
34458     if (p->nSet<(BITVEC_NINT-1)) {
34459       goto bitvec_set_end;
34460     } else {
34461       goto bitvec_set_rehash;
34462     }
34463   }
34464   /* there was a collision, check to see if it's already */
34465   /* in hash, if not, try to find a spot for it */
34466   do {
34467     if( p->u.aHash[h]==i ) return SQLITE_OK;
34468     h++;
34469     if( h>=BITVEC_NINT ) h = 0;
34470   } while( p->u.aHash[h] );
34471   /* we didn't find it in the hash.  h points to the first */
34472   /* available free spot. check to see if this is going to */
34473   /* make our hash too "full".  */
34474 bitvec_set_rehash:
34475   if( p->nSet>=BITVEC_MXHASH ){
34476     unsigned int j;
34477     int rc;
34478     u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
34479     if( aiValues==0 ){
34480       return SQLITE_NOMEM;
34481     }else{
34482       memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
34483       memset(p->u.apSub, 0, sizeof(p->u.apSub));
34484       p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
34485       rc = sqlite3BitvecSet(p, i);
34486       for(j=0; j<BITVEC_NINT; j++){
34487         if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
34488       }
34489       sqlite3StackFree(0, aiValues);
34490       return rc;
34491     }
34492   }
34493 bitvec_set_end:
34494   p->nSet++;
34495   p->u.aHash[h] = i;
34496   return SQLITE_OK;
34497 }
34498
34499 /*
34500 ** Clear the i-th bit.
34501 **
34502 ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
34503 ** that BitvecClear can use to rebuilt its hash table.
34504 */
34505 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
34506   if( p==0 ) return;
34507   assert( i>0 );
34508   i--;
34509   while( p->iDivisor ){
34510     u32 bin = i/p->iDivisor;
34511     i = i%p->iDivisor;
34512     p = p->u.apSub[bin];
34513     if (!p) {
34514       return;
34515     }
34516   }
34517   if( p->iSize<=BITVEC_NBIT ){
34518     p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
34519   }else{
34520     unsigned int j;
34521     u32 *aiValues = pBuf;
34522     memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
34523     memset(p->u.aHash, 0, sizeof(p->u.aHash));
34524     p->nSet = 0;
34525     for(j=0; j<BITVEC_NINT; j++){
34526       if( aiValues[j] && aiValues[j]!=(i+1) ){
34527         u32 h = BITVEC_HASH(aiValues[j]-1);
34528         p->nSet++;
34529         while( p->u.aHash[h] ){
34530           h++;
34531           if( h>=BITVEC_NINT ) h = 0;
34532         }
34533         p->u.aHash[h] = aiValues[j];
34534       }
34535     }
34536   }
34537 }
34538
34539 /*
34540 ** Destroy a bitmap object.  Reclaim all memory used.
34541 */
34542 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
34543   if( p==0 ) return;
34544   if( p->iDivisor ){
34545     unsigned int i;
34546     for(i=0; i<BITVEC_NPTR; i++){
34547       sqlite3BitvecDestroy(p->u.apSub[i]);
34548     }
34549   }
34550   sqlite3_free(p);
34551 }
34552
34553 /*
34554 ** Return the value of the iSize parameter specified when Bitvec *p
34555 ** was created.
34556 */
34557 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
34558   return p->iSize;
34559 }
34560
34561 #ifndef SQLITE_OMIT_BUILTIN_TEST
34562 /*
34563 ** Let V[] be an array of unsigned characters sufficient to hold
34564 ** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
34565 ** Then the following macros can be used to set, clear, or test
34566 ** individual bits within V.
34567 */
34568 #define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
34569 #define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
34570 #define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
34571
34572 /*
34573 ** This routine runs an extensive test of the Bitvec code.
34574 **
34575 ** The input is an array of integers that acts as a program
34576 ** to test the Bitvec.  The integers are opcodes followed
34577 ** by 0, 1, or 3 operands, depending on the opcode.  Another
34578 ** opcode follows immediately after the last operand.
34579 **
34580 ** There are 6 opcodes numbered from 0 through 5.  0 is the
34581 ** "halt" opcode and causes the test to end.
34582 **
34583 **    0          Halt and return the number of errors
34584 **    1 N S X    Set N bits beginning with S and incrementing by X
34585 **    2 N S X    Clear N bits beginning with S and incrementing by X
34586 **    3 N        Set N randomly chosen bits
34587 **    4 N        Clear N randomly chosen bits
34588 **    5 N S X    Set N bits from S increment X in array only, not in bitvec
34589 **
34590 ** The opcodes 1 through 4 perform set and clear operations are performed
34591 ** on both a Bitvec object and on a linear array of bits obtained from malloc.
34592 ** Opcode 5 works on the linear array only, not on the Bitvec.
34593 ** Opcode 5 is used to deliberately induce a fault in order to
34594 ** confirm that error detection works.
34595 **
34596 ** At the conclusion of the test the linear array is compared
34597 ** against the Bitvec object.  If there are any differences,
34598 ** an error is returned.  If they are the same, zero is returned.
34599 **
34600 ** If a memory allocation error occurs, return -1.
34601 */
34602 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
34603   Bitvec *pBitvec = 0;
34604   unsigned char *pV = 0;
34605   int rc = -1;
34606   int i, nx, pc, op;
34607   void *pTmpSpace;
34608
34609   /* Allocate the Bitvec to be tested and a linear array of
34610   ** bits to act as the reference */
34611   pBitvec = sqlite3BitvecCreate( sz );
34612   pV = sqlite3_malloc( (sz+7)/8 + 1 );
34613   pTmpSpace = sqlite3_malloc(BITVEC_SZ);
34614   if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
34615   memset(pV, 0, (sz+7)/8 + 1);
34616
34617   /* NULL pBitvec tests */
34618   sqlite3BitvecSet(0, 1);
34619   sqlite3BitvecClear(0, 1, pTmpSpace);
34620
34621   /* Run the program */
34622   pc = 0;
34623   while( (op = aOp[pc])!=0 ){
34624     switch( op ){
34625       case 1:
34626       case 2:
34627       case 5: {
34628         nx = 4;
34629         i = aOp[pc+2] - 1;
34630         aOp[pc+2] += aOp[pc+3];
34631         break;
34632       }
34633       case 3:
34634       case 4: 
34635       default: {
34636         nx = 2;
34637         sqlite3_randomness(sizeof(i), &i);
34638         break;
34639       }
34640     }
34641     if( (--aOp[pc+1]) > 0 ) nx = 0;
34642     pc += nx;
34643     i = (i & 0x7fffffff)%sz;
34644     if( (op & 1)!=0 ){
34645       SETBIT(pV, (i+1));
34646       if( op!=5 ){
34647         if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
34648       }
34649     }else{
34650       CLEARBIT(pV, (i+1));
34651       sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
34652     }
34653   }
34654
34655   /* Test to make sure the linear array exactly matches the
34656   ** Bitvec object.  Start with the assumption that they do
34657   ** match (rc==0).  Change rc to non-zero if a discrepancy
34658   ** is found.
34659   */
34660   rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
34661           + sqlite3BitvecTest(pBitvec, 0)
34662           + (sqlite3BitvecSize(pBitvec) - sz);
34663   for(i=1; i<=sz; i++){
34664     if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
34665       rc = i;
34666       break;
34667     }
34668   }
34669
34670   /* Free allocated structure */
34671 bitvec_end:
34672   sqlite3_free(pTmpSpace);
34673   sqlite3_free(pV);
34674   sqlite3BitvecDestroy(pBitvec);
34675   return rc;
34676 }
34677 #endif /* SQLITE_OMIT_BUILTIN_TEST */
34678
34679 /************** End of bitvec.c **********************************************/
34680 /************** Begin file pcache.c ******************************************/
34681 /*
34682 ** 2008 August 05
34683 **
34684 ** The author disclaims copyright to this source code.  In place of
34685 ** a legal notice, here is a blessing:
34686 **
34687 **    May you do good and not evil.
34688 **    May you find forgiveness for yourself and forgive others.
34689 **    May you share freely, never taking more than you give.
34690 **
34691 *************************************************************************
34692 ** This file implements that page cache.
34693 */
34694
34695 /*
34696 ** A complete page cache is an instance of this structure.
34697 */
34698 struct PCache {
34699   PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
34700   PgHdr *pSynced;                     /* Last synced page in dirty page list */
34701   int nRef;                           /* Number of referenced pages */
34702   int nMax;                           /* Configured cache size */
34703   int szPage;                         /* Size of every page in this cache */
34704   int szExtra;                        /* Size of extra space for each page */
34705   int bPurgeable;                     /* True if pages are on backing store */
34706   int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
34707   void *pStress;                      /* Argument to xStress */
34708   sqlite3_pcache *pCache;             /* Pluggable cache module */
34709   PgHdr *pPage1;                      /* Reference to page 1 */
34710 };
34711
34712 /*
34713 ** Some of the assert() macros in this code are too expensive to run
34714 ** even during normal debugging.  Use them only rarely on long-running
34715 ** tests.  Enable the expensive asserts using the
34716 ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
34717 */
34718 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
34719 # define expensive_assert(X)  assert(X)
34720 #else
34721 # define expensive_assert(X)
34722 #endif
34723
34724 /********************************** Linked List Management ********************/
34725
34726 #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
34727 /*
34728 ** Check that the pCache->pSynced variable is set correctly. If it
34729 ** is not, either fail an assert or return zero. Otherwise, return
34730 ** non-zero. This is only used in debugging builds, as follows:
34731 **
34732 **   expensive_assert( pcacheCheckSynced(pCache) );
34733 */
34734 static int pcacheCheckSynced(PCache *pCache){
34735   PgHdr *p;
34736   for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
34737     assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
34738   }
34739   return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
34740 }
34741 #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
34742
34743 /*
34744 ** Remove page pPage from the list of dirty pages.
34745 */
34746 static void pcacheRemoveFromDirtyList(PgHdr *pPage){
34747   PCache *p = pPage->pCache;
34748
34749   assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
34750   assert( pPage->pDirtyPrev || pPage==p->pDirty );
34751
34752   /* Update the PCache1.pSynced variable if necessary. */
34753   if( p->pSynced==pPage ){
34754     PgHdr *pSynced = pPage->pDirtyPrev;
34755     while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
34756       pSynced = pSynced->pDirtyPrev;
34757     }
34758     p->pSynced = pSynced;
34759   }
34760
34761   if( pPage->pDirtyNext ){
34762     pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
34763   }else{
34764     assert( pPage==p->pDirtyTail );
34765     p->pDirtyTail = pPage->pDirtyPrev;
34766   }
34767   if( pPage->pDirtyPrev ){
34768     pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
34769   }else{
34770     assert( pPage==p->pDirty );
34771     p->pDirty = pPage->pDirtyNext;
34772   }
34773   pPage->pDirtyNext = 0;
34774   pPage->pDirtyPrev = 0;
34775
34776   expensive_assert( pcacheCheckSynced(p) );
34777 }
34778
34779 /*
34780 ** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
34781 ** pPage).
34782 */
34783 static void pcacheAddToDirtyList(PgHdr *pPage){
34784   PCache *p = pPage->pCache;
34785
34786   assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
34787
34788   pPage->pDirtyNext = p->pDirty;
34789   if( pPage->pDirtyNext ){
34790     assert( pPage->pDirtyNext->pDirtyPrev==0 );
34791     pPage->pDirtyNext->pDirtyPrev = pPage;
34792   }
34793   p->pDirty = pPage;
34794   if( !p->pDirtyTail ){
34795     p->pDirtyTail = pPage;
34796   }
34797   if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
34798     p->pSynced = pPage;
34799   }
34800   expensive_assert( pcacheCheckSynced(p) );
34801 }
34802
34803 /*
34804 ** Wrapper around the pluggable caches xUnpin method. If the cache is
34805 ** being used for an in-memory database, this function is a no-op.
34806 */
34807 static void pcacheUnpin(PgHdr *p){
34808   PCache *pCache = p->pCache;
34809   if( pCache->bPurgeable ){
34810     if( p->pgno==1 ){
34811       pCache->pPage1 = 0;
34812     }
34813     sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 0);
34814   }
34815 }
34816
34817 /*************************************************** General Interfaces ******
34818 **
34819 ** Initialize and shutdown the page cache subsystem. Neither of these 
34820 ** functions are threadsafe.
34821 */
34822 SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
34823   if( sqlite3GlobalConfig.pcache.xInit==0 ){
34824     /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
34825     ** built-in default page cache is used instead of the application defined
34826     ** page cache. */
34827     sqlite3PCacheSetDefault();
34828   }
34829   return sqlite3GlobalConfig.pcache.xInit(sqlite3GlobalConfig.pcache.pArg);
34830 }
34831 SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
34832   if( sqlite3GlobalConfig.pcache.xShutdown ){
34833     /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
34834     sqlite3GlobalConfig.pcache.xShutdown(sqlite3GlobalConfig.pcache.pArg);
34835   }
34836 }
34837
34838 /*
34839 ** Return the size in bytes of a PCache object.
34840 */
34841 SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
34842
34843 /*
34844 ** Create a new PCache object. Storage space to hold the object
34845 ** has already been allocated and is passed in as the p pointer. 
34846 ** The caller discovers how much space needs to be allocated by 
34847 ** calling sqlite3PcacheSize().
34848 */
34849 SQLITE_PRIVATE void sqlite3PcacheOpen(
34850   int szPage,                  /* Size of every page */
34851   int szExtra,                 /* Extra space associated with each page */
34852   int bPurgeable,              /* True if pages are on backing store */
34853   int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
34854   void *pStress,               /* Argument to xStress */
34855   PCache *p                    /* Preallocated space for the PCache */
34856 ){
34857   memset(p, 0, sizeof(PCache));
34858   p->szPage = szPage;
34859   p->szExtra = szExtra;
34860   p->bPurgeable = bPurgeable;
34861   p->xStress = xStress;
34862   p->pStress = pStress;
34863   p->nMax = 100;
34864 }
34865
34866 /*
34867 ** Change the page size for PCache object. The caller must ensure that there
34868 ** are no outstanding page references when this function is called.
34869 */
34870 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
34871   assert( pCache->nRef==0 && pCache->pDirty==0 );
34872   if( pCache->pCache ){
34873     sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
34874     pCache->pCache = 0;
34875     pCache->pPage1 = 0;
34876   }
34877   pCache->szPage = szPage;
34878 }
34879
34880 /*
34881 ** Try to obtain a page from the cache.
34882 */
34883 SQLITE_PRIVATE int sqlite3PcacheFetch(
34884   PCache *pCache,       /* Obtain the page from this cache */
34885   Pgno pgno,            /* Page number to obtain */
34886   int createFlag,       /* If true, create page if it does not exist already */
34887   PgHdr **ppPage        /* Write the page here */
34888 ){
34889   PgHdr *pPage = 0;
34890   int eCreate;
34891
34892   assert( pCache!=0 );
34893   assert( createFlag==1 || createFlag==0 );
34894   assert( pgno>0 );
34895
34896   /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
34897   ** allocate it now.
34898   */
34899   if( !pCache->pCache && createFlag ){
34900     sqlite3_pcache *p;
34901     int nByte;
34902     nByte = pCache->szPage + pCache->szExtra + sizeof(PgHdr);
34903     p = sqlite3GlobalConfig.pcache.xCreate(nByte, pCache->bPurgeable);
34904     if( !p ){
34905       return SQLITE_NOMEM;
34906     }
34907     sqlite3GlobalConfig.pcache.xCachesize(p, pCache->nMax);
34908     pCache->pCache = p;
34909   }
34910
34911   eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));
34912   if( pCache->pCache ){
34913     pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, eCreate);
34914   }
34915
34916   if( !pPage && eCreate==1 ){
34917     PgHdr *pPg;
34918
34919     /* Find a dirty page to write-out and recycle. First try to find a 
34920     ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
34921     ** cleared), but if that is not possible settle for any other 
34922     ** unreferenced dirty page.
34923     */
34924     expensive_assert( pcacheCheckSynced(pCache) );
34925     for(pPg=pCache->pSynced; 
34926         pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC)); 
34927         pPg=pPg->pDirtyPrev
34928     );
34929     pCache->pSynced = pPg;
34930     if( !pPg ){
34931       for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
34932     }
34933     if( pPg ){
34934       int rc;
34935 #ifdef SQLITE_LOG_CACHE_SPILL
34936       sqlite3_log(SQLITE_FULL, 
34937                   "spill page %d making room for %d - cache used: %d/%d",
34938                   pPg->pgno, pgno,
34939                   sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
34940                   pCache->nMax);
34941 #endif
34942       rc = pCache->xStress(pCache->pStress, pPg);
34943       if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
34944         return rc;
34945       }
34946     }
34947
34948     pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, 2);
34949   }
34950
34951   if( pPage ){
34952     if( !pPage->pData ){
34953       memset(pPage, 0, sizeof(PgHdr));
34954       pPage->pData = (void *)&pPage[1];
34955       pPage->pExtra = (void*)&((char *)pPage->pData)[pCache->szPage];
34956       memset(pPage->pExtra, 0, pCache->szExtra);
34957       pPage->pCache = pCache;
34958       pPage->pgno = pgno;
34959     }
34960     assert( pPage->pCache==pCache );
34961     assert( pPage->pgno==pgno );
34962     assert( pPage->pData==(void *)&pPage[1] );
34963     assert( pPage->pExtra==(void *)&((char *)&pPage[1])[pCache->szPage] );
34964
34965     if( 0==pPage->nRef ){
34966       pCache->nRef++;
34967     }
34968     pPage->nRef++;
34969     if( pgno==1 ){
34970       pCache->pPage1 = pPage;
34971     }
34972   }
34973   *ppPage = pPage;
34974   return (pPage==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
34975 }
34976
34977 /*
34978 ** Decrement the reference count on a page. If the page is clean and the
34979 ** reference count drops to 0, then it is made elible for recycling.
34980 */
34981 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
34982   assert( p->nRef>0 );
34983   p->nRef--;
34984   if( p->nRef==0 ){
34985     PCache *pCache = p->pCache;
34986     pCache->nRef--;
34987     if( (p->flags&PGHDR_DIRTY)==0 ){
34988       pcacheUnpin(p);
34989     }else{
34990       /* Move the page to the head of the dirty list. */
34991       pcacheRemoveFromDirtyList(p);
34992       pcacheAddToDirtyList(p);
34993     }
34994   }
34995 }
34996
34997 /*
34998 ** Increase the reference count of a supplied page by 1.
34999 */
35000 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
35001   assert(p->nRef>0);
35002   p->nRef++;
35003 }
35004
35005 /*
35006 ** Drop a page from the cache. There must be exactly one reference to the
35007 ** page. This function deletes that reference, so after it returns the
35008 ** page pointed to by p is invalid.
35009 */
35010 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
35011   PCache *pCache;
35012   assert( p->nRef==1 );
35013   if( p->flags&PGHDR_DIRTY ){
35014     pcacheRemoveFromDirtyList(p);
35015   }
35016   pCache = p->pCache;
35017   pCache->nRef--;
35018   if( p->pgno==1 ){
35019     pCache->pPage1 = 0;
35020   }
35021   sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 1);
35022 }
35023
35024 /*
35025 ** Make sure the page is marked as dirty. If it isn't dirty already,
35026 ** make it so.
35027 */
35028 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
35029   p->flags &= ~PGHDR_DONT_WRITE;
35030   assert( p->nRef>0 );
35031   if( 0==(p->flags & PGHDR_DIRTY) ){
35032     p->flags |= PGHDR_DIRTY;
35033     pcacheAddToDirtyList( p);
35034   }
35035 }
35036
35037 /*
35038 ** Make sure the page is marked as clean. If it isn't clean already,
35039 ** make it so.
35040 */
35041 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
35042   if( (p->flags & PGHDR_DIRTY) ){
35043     pcacheRemoveFromDirtyList(p);
35044     p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
35045     if( p->nRef==0 ){
35046       pcacheUnpin(p);
35047     }
35048   }
35049 }
35050
35051 /*
35052 ** Make every page in the cache clean.
35053 */
35054 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
35055   PgHdr *p;
35056   while( (p = pCache->pDirty)!=0 ){
35057     sqlite3PcacheMakeClean(p);
35058   }
35059 }
35060
35061 /*
35062 ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
35063 */
35064 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
35065   PgHdr *p;
35066   for(p=pCache->pDirty; p; p=p->pDirtyNext){
35067     p->flags &= ~PGHDR_NEED_SYNC;
35068   }
35069   pCache->pSynced = pCache->pDirtyTail;
35070 }
35071
35072 /*
35073 ** Change the page number of page p to newPgno. 
35074 */
35075 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
35076   PCache *pCache = p->pCache;
35077   assert( p->nRef>0 );
35078   assert( newPgno>0 );
35079   sqlite3GlobalConfig.pcache.xRekey(pCache->pCache, p, p->pgno, newPgno);
35080   p->pgno = newPgno;
35081   if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
35082     pcacheRemoveFromDirtyList(p);
35083     pcacheAddToDirtyList(p);
35084   }
35085 }
35086
35087 /*
35088 ** Drop every cache entry whose page number is greater than "pgno". The
35089 ** caller must ensure that there are no outstanding references to any pages
35090 ** other than page 1 with a page number greater than pgno.
35091 **
35092 ** If there is a reference to page 1 and the pgno parameter passed to this
35093 ** function is 0, then the data area associated with page 1 is zeroed, but
35094 ** the page object is not dropped.
35095 */
35096 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
35097   if( pCache->pCache ){
35098     PgHdr *p;
35099     PgHdr *pNext;
35100     for(p=pCache->pDirty; p; p=pNext){
35101       pNext = p->pDirtyNext;
35102       /* This routine never gets call with a positive pgno except right
35103       ** after sqlite3PcacheCleanAll().  So if there are dirty pages,
35104       ** it must be that pgno==0.
35105       */
35106       assert( p->pgno>0 );
35107       if( ALWAYS(p->pgno>pgno) ){
35108         assert( p->flags&PGHDR_DIRTY );
35109         sqlite3PcacheMakeClean(p);
35110       }
35111     }
35112     if( pgno==0 && pCache->pPage1 ){
35113       memset(pCache->pPage1->pData, 0, pCache->szPage);
35114       pgno = 1;
35115     }
35116     sqlite3GlobalConfig.pcache.xTruncate(pCache->pCache, pgno+1);
35117   }
35118 }
35119
35120 /*
35121 ** Close a cache.
35122 */
35123 SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
35124   if( pCache->pCache ){
35125     sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
35126   }
35127 }
35128
35129 /* 
35130 ** Discard the contents of the cache.
35131 */
35132 SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
35133   sqlite3PcacheTruncate(pCache, 0);
35134 }
35135
35136 /*
35137 ** Merge two lists of pages connected by pDirty and in pgno order.
35138 ** Do not both fixing the pDirtyPrev pointers.
35139 */
35140 static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
35141   PgHdr result, *pTail;
35142   pTail = &result;
35143   while( pA && pB ){
35144     if( pA->pgno<pB->pgno ){
35145       pTail->pDirty = pA;
35146       pTail = pA;
35147       pA = pA->pDirty;
35148     }else{
35149       pTail->pDirty = pB;
35150       pTail = pB;
35151       pB = pB->pDirty;
35152     }
35153   }
35154   if( pA ){
35155     pTail->pDirty = pA;
35156   }else if( pB ){
35157     pTail->pDirty = pB;
35158   }else{
35159     pTail->pDirty = 0;
35160   }
35161   return result.pDirty;
35162 }
35163
35164 /*
35165 ** Sort the list of pages in accending order by pgno.  Pages are
35166 ** connected by pDirty pointers.  The pDirtyPrev pointers are
35167 ** corrupted by this sort.
35168 **
35169 ** Since there cannot be more than 2^31 distinct pages in a database,
35170 ** there cannot be more than 31 buckets required by the merge sorter.
35171 ** One extra bucket is added to catch overflow in case something
35172 ** ever changes to make the previous sentence incorrect.
35173 */
35174 #define N_SORT_BUCKET  32
35175 static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
35176   PgHdr *a[N_SORT_BUCKET], *p;
35177   int i;
35178   memset(a, 0, sizeof(a));
35179   while( pIn ){
35180     p = pIn;
35181     pIn = p->pDirty;
35182     p->pDirty = 0;
35183     for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
35184       if( a[i]==0 ){
35185         a[i] = p;
35186         break;
35187       }else{
35188         p = pcacheMergeDirtyList(a[i], p);
35189         a[i] = 0;
35190       }
35191     }
35192     if( NEVER(i==N_SORT_BUCKET-1) ){
35193       /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
35194       ** the input list.  But that is impossible.
35195       */
35196       a[i] = pcacheMergeDirtyList(a[i], p);
35197     }
35198   }
35199   p = a[0];
35200   for(i=1; i<N_SORT_BUCKET; i++){
35201     p = pcacheMergeDirtyList(p, a[i]);
35202   }
35203   return p;
35204 }
35205
35206 /*
35207 ** Return a list of all dirty pages in the cache, sorted by page number.
35208 */
35209 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
35210   PgHdr *p;
35211   for(p=pCache->pDirty; p; p=p->pDirtyNext){
35212     p->pDirty = p->pDirtyNext;
35213   }
35214   return pcacheSortDirtyList(pCache->pDirty);
35215 }
35216
35217 /* 
35218 ** Return the total number of referenced pages held by the cache.
35219 */
35220 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
35221   return pCache->nRef;
35222 }
35223
35224 /*
35225 ** Return the number of references to the page supplied as an argument.
35226 */
35227 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
35228   return p->nRef;
35229 }
35230
35231 /* 
35232 ** Return the total number of pages in the cache.
35233 */
35234 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
35235   int nPage = 0;
35236   if( pCache->pCache ){
35237     nPage = sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache);
35238   }
35239   return nPage;
35240 }
35241
35242 #ifdef SQLITE_TEST
35243 /*
35244 ** Get the suggested cache-size value.
35245 */
35246 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
35247   return pCache->nMax;
35248 }
35249 #endif
35250
35251 /*
35252 ** Set the suggested cache-size value.
35253 */
35254 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
35255   pCache->nMax = mxPage;
35256   if( pCache->pCache ){
35257     sqlite3GlobalConfig.pcache.xCachesize(pCache->pCache, mxPage);
35258   }
35259 }
35260
35261 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
35262 /*
35263 ** For all dirty pages currently in the cache, invoke the specified
35264 ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
35265 ** defined.
35266 */
35267 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
35268   PgHdr *pDirty;
35269   for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
35270     xIter(pDirty);
35271   }
35272 }
35273 #endif
35274
35275 /************** End of pcache.c **********************************************/
35276 /************** Begin file pcache1.c *****************************************/
35277 /*
35278 ** 2008 November 05
35279 **
35280 ** The author disclaims copyright to this source code.  In place of
35281 ** a legal notice, here is a blessing:
35282 **
35283 **    May you do good and not evil.
35284 **    May you find forgiveness for yourself and forgive others.
35285 **    May you share freely, never taking more than you give.
35286 **
35287 *************************************************************************
35288 **
35289 ** This file implements the default page cache implementation (the
35290 ** sqlite3_pcache interface). It also contains part of the implementation
35291 ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
35292 ** If the default page cache implementation is overriden, then neither of
35293 ** these two features are available.
35294 */
35295
35296
35297 typedef struct PCache1 PCache1;
35298 typedef struct PgHdr1 PgHdr1;
35299 typedef struct PgFreeslot PgFreeslot;
35300 typedef struct PGroup PGroup;
35301
35302 /* Each page cache (or PCache) belongs to a PGroup.  A PGroup is a set 
35303 ** of one or more PCaches that are able to recycle each others unpinned
35304 ** pages when they are under memory pressure.  A PGroup is an instance of
35305 ** the following object.
35306 **
35307 ** This page cache implementation works in one of two modes:
35308 **
35309 **   (1)  Every PCache is the sole member of its own PGroup.  There is
35310 **        one PGroup per PCache.
35311 **
35312 **   (2)  There is a single global PGroup that all PCaches are a member
35313 **        of.
35314 **
35315 ** Mode 1 uses more memory (since PCache instances are not able to rob
35316 ** unused pages from other PCaches) but it also operates without a mutex,
35317 ** and is therefore often faster.  Mode 2 requires a mutex in order to be
35318 ** threadsafe, but is able recycle pages more efficient.
35319 **
35320 ** For mode (1), PGroup.mutex is NULL.  For mode (2) there is only a single
35321 ** PGroup which is the pcache1.grp global variable and its mutex is
35322 ** SQLITE_MUTEX_STATIC_LRU.
35323 */
35324 struct PGroup {
35325   sqlite3_mutex *mutex;          /* MUTEX_STATIC_LRU or NULL */
35326   int nMaxPage;                  /* Sum of nMax for purgeable caches */
35327   int nMinPage;                  /* Sum of nMin for purgeable caches */
35328   int mxPinned;                  /* nMaxpage + 10 - nMinPage */
35329   int nCurrentPage;              /* Number of purgeable pages allocated */
35330   PgHdr1 *pLruHead, *pLruTail;   /* LRU list of unpinned pages */
35331 };
35332
35333 /* Each page cache is an instance of the following object.  Every
35334 ** open database file (including each in-memory database and each
35335 ** temporary or transient database) has a single page cache which
35336 ** is an instance of this object.
35337 **
35338 ** Pointers to structures of this type are cast and returned as 
35339 ** opaque sqlite3_pcache* handles.
35340 */
35341 struct PCache1 {
35342   /* Cache configuration parameters. Page size (szPage) and the purgeable
35343   ** flag (bPurgeable) are set when the cache is created. nMax may be 
35344   ** modified at any time by a call to the pcache1CacheSize() method.
35345   ** The PGroup mutex must be held when accessing nMax.
35346   */
35347   PGroup *pGroup;                     /* PGroup this cache belongs to */
35348   int szPage;                         /* Size of allocated pages in bytes */
35349   int bPurgeable;                     /* True if cache is purgeable */
35350   unsigned int nMin;                  /* Minimum number of pages reserved */
35351   unsigned int nMax;                  /* Configured "cache_size" value */
35352   unsigned int n90pct;                /* nMax*9/10 */
35353
35354   /* Hash table of all pages. The following variables may only be accessed
35355   ** when the accessor is holding the PGroup mutex.
35356   */
35357   unsigned int nRecyclable;           /* Number of pages in the LRU list */
35358   unsigned int nPage;                 /* Total number of pages in apHash */
35359   unsigned int nHash;                 /* Number of slots in apHash[] */
35360   PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
35361
35362   unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
35363 };
35364
35365 /*
35366 ** Each cache entry is represented by an instance of the following 
35367 ** structure. A buffer of PgHdr1.pCache->szPage bytes is allocated 
35368 ** directly before this structure in memory (see the PGHDR1_TO_PAGE() 
35369 ** macro below).
35370 */
35371 struct PgHdr1 {
35372   unsigned int iKey;             /* Key value (page number) */
35373   PgHdr1 *pNext;                 /* Next in hash table chain */
35374   PCache1 *pCache;               /* Cache that currently owns this page */
35375   PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
35376   PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
35377 };
35378
35379 /*
35380 ** Free slots in the allocator used to divide up the buffer provided using
35381 ** the SQLITE_CONFIG_PAGECACHE mechanism.
35382 */
35383 struct PgFreeslot {
35384   PgFreeslot *pNext;  /* Next free slot */
35385 };
35386
35387 /*
35388 ** Global data used by this cache.
35389 */
35390 static SQLITE_WSD struct PCacheGlobal {
35391   PGroup grp;                    /* The global PGroup for mode (2) */
35392
35393   /* Variables related to SQLITE_CONFIG_PAGECACHE settings.  The
35394   ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
35395   ** fixed at sqlite3_initialize() time and do not require mutex protection.
35396   ** The nFreeSlot and pFree values do require mutex protection.
35397   */
35398   int isInit;                    /* True if initialized */
35399   int szSlot;                    /* Size of each free slot */
35400   int nSlot;                     /* The number of pcache slots */
35401   int nReserve;                  /* Try to keep nFreeSlot above this */
35402   void *pStart, *pEnd;           /* Bounds of pagecache malloc range */
35403   /* Above requires no mutex.  Use mutex below for variable that follow. */
35404   sqlite3_mutex *mutex;          /* Mutex for accessing the following: */
35405   int nFreeSlot;                 /* Number of unused pcache slots */
35406   PgFreeslot *pFree;             /* Free page blocks */
35407   /* The following value requires a mutex to change.  We skip the mutex on
35408   ** reading because (1) most platforms read a 32-bit integer atomically and
35409   ** (2) even if an incorrect value is read, no great harm is done since this
35410   ** is really just an optimization. */
35411   int bUnderPressure;            /* True if low on PAGECACHE memory */
35412 } pcache1_g;
35413
35414 /*
35415 ** All code in this file should access the global structure above via the
35416 ** alias "pcache1". This ensures that the WSD emulation is used when
35417 ** compiling for systems that do not support real WSD.
35418 */
35419 #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
35420
35421 /*
35422 ** When a PgHdr1 structure is allocated, the associated PCache1.szPage
35423 ** bytes of data are located directly before it in memory (i.e. the total
35424 ** size of the allocation is sizeof(PgHdr1)+PCache1.szPage byte). The
35425 ** PGHDR1_TO_PAGE() macro takes a pointer to a PgHdr1 structure as
35426 ** an argument and returns a pointer to the associated block of szPage
35427 ** bytes. The PAGE_TO_PGHDR1() macro does the opposite: its argument is
35428 ** a pointer to a block of szPage bytes of data and the return value is
35429 ** a pointer to the associated PgHdr1 structure.
35430 **
35431 **   assert( PGHDR1_TO_PAGE(PAGE_TO_PGHDR1(pCache, X))==X );
35432 */
35433 #define PGHDR1_TO_PAGE(p)    (void*)(((char*)p) - p->pCache->szPage)
35434 #define PAGE_TO_PGHDR1(c, p) (PgHdr1*)(((char*)p) + c->szPage)
35435
35436 /*
35437 ** Macros to enter and leave the PCache LRU mutex.
35438 */
35439 #define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
35440 #define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
35441
35442 /******************************************************************************/
35443 /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
35444
35445 /*
35446 ** This function is called during initialization if a static buffer is 
35447 ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
35448 ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
35449 ** enough to contain 'n' buffers of 'sz' bytes each.
35450 **
35451 ** This routine is called from sqlite3_initialize() and so it is guaranteed
35452 ** to be serialized already.  There is no need for further mutexing.
35453 */
35454 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
35455   if( pcache1.isInit ){
35456     PgFreeslot *p;
35457     sz = ROUNDDOWN8(sz);
35458     pcache1.szSlot = sz;
35459     pcache1.nSlot = pcache1.nFreeSlot = n;
35460     pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
35461     pcache1.pStart = pBuf;
35462     pcache1.pFree = 0;
35463     pcache1.bUnderPressure = 0;
35464     while( n-- ){
35465       p = (PgFreeslot*)pBuf;
35466       p->pNext = pcache1.pFree;
35467       pcache1.pFree = p;
35468       pBuf = (void*)&((char*)pBuf)[sz];
35469     }
35470     pcache1.pEnd = pBuf;
35471   }
35472 }
35473
35474 /*
35475 ** Malloc function used within this file to allocate space from the buffer
35476 ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no 
35477 ** such buffer exists or there is no space left in it, this function falls 
35478 ** back to sqlite3Malloc().
35479 **
35480 ** Multiple threads can run this routine at the same time.  Global variables
35481 ** in pcache1 need to be protected via mutex.
35482 */
35483 static void *pcache1Alloc(int nByte){
35484   void *p = 0;
35485   assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
35486   sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
35487   if( nByte<=pcache1.szSlot ){
35488     sqlite3_mutex_enter(pcache1.mutex);
35489     p = (PgHdr1 *)pcache1.pFree;
35490     if( p ){
35491       pcache1.pFree = pcache1.pFree->pNext;
35492       pcache1.nFreeSlot--;
35493       pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
35494       assert( pcache1.nFreeSlot>=0 );
35495       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
35496     }
35497     sqlite3_mutex_leave(pcache1.mutex);
35498   }
35499   if( p==0 ){
35500     /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool.  Get
35501     ** it from sqlite3Malloc instead.
35502     */
35503     p = sqlite3Malloc(nByte);
35504     if( p ){
35505       int sz = sqlite3MallocSize(p);
35506       sqlite3_mutex_enter(pcache1.mutex);
35507       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
35508       sqlite3_mutex_leave(pcache1.mutex);
35509     }
35510     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
35511   }
35512   return p;
35513 }
35514
35515 /*
35516 ** Free an allocated buffer obtained from pcache1Alloc().
35517 */
35518 static void pcache1Free(void *p){
35519   if( p==0 ) return;
35520   if( p>=pcache1.pStart && p<pcache1.pEnd ){
35521     PgFreeslot *pSlot;
35522     sqlite3_mutex_enter(pcache1.mutex);
35523     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
35524     pSlot = (PgFreeslot*)p;
35525     pSlot->pNext = pcache1.pFree;
35526     pcache1.pFree = pSlot;
35527     pcache1.nFreeSlot++;
35528     pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
35529     assert( pcache1.nFreeSlot<=pcache1.nSlot );
35530     sqlite3_mutex_leave(pcache1.mutex);
35531   }else{
35532     int iSize;
35533     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
35534     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
35535     iSize = sqlite3MallocSize(p);
35536     sqlite3_mutex_enter(pcache1.mutex);
35537     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -iSize);
35538     sqlite3_mutex_leave(pcache1.mutex);
35539     sqlite3_free(p);
35540   }
35541 }
35542
35543 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
35544 /*
35545 ** Return the size of a pcache allocation
35546 */
35547 static int pcache1MemSize(void *p){
35548   if( p>=pcache1.pStart && p<pcache1.pEnd ){
35549     return pcache1.szSlot;
35550   }else{
35551     int iSize;
35552     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
35553     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
35554     iSize = sqlite3MallocSize(p);
35555     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
35556     return iSize;
35557   }
35558 }
35559 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
35560
35561 /*
35562 ** Allocate a new page object initially associated with cache pCache.
35563 */
35564 static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
35565   int nByte = sizeof(PgHdr1) + pCache->szPage;
35566   void *pPg = pcache1Alloc(nByte);
35567   PgHdr1 *p;
35568   if( pPg ){
35569     p = PAGE_TO_PGHDR1(pCache, pPg);
35570     if( pCache->bPurgeable ){
35571       pCache->pGroup->nCurrentPage++;
35572     }
35573   }else{
35574     p = 0;
35575   }
35576   return p;
35577 }
35578
35579 /*
35580 ** Free a page object allocated by pcache1AllocPage().
35581 **
35582 ** The pointer is allowed to be NULL, which is prudent.  But it turns out
35583 ** that the current implementation happens to never call this routine
35584 ** with a NULL pointer, so we mark the NULL test with ALWAYS().
35585 */
35586 static void pcache1FreePage(PgHdr1 *p){
35587   if( ALWAYS(p) ){
35588     PCache1 *pCache = p->pCache;
35589     if( pCache->bPurgeable ){
35590       pCache->pGroup->nCurrentPage--;
35591     }
35592     pcache1Free(PGHDR1_TO_PAGE(p));
35593   }
35594 }
35595
35596 /*
35597 ** Malloc function used by SQLite to obtain space from the buffer configured
35598 ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
35599 ** exists, this function falls back to sqlite3Malloc().
35600 */
35601 SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
35602   return pcache1Alloc(sz);
35603 }
35604
35605 /*
35606 ** Free an allocated buffer obtained from sqlite3PageMalloc().
35607 */
35608 SQLITE_PRIVATE void sqlite3PageFree(void *p){
35609   pcache1Free(p);
35610 }
35611
35612
35613 /*
35614 ** Return true if it desirable to avoid allocating a new page cache
35615 ** entry.
35616 **
35617 ** If memory was allocated specifically to the page cache using
35618 ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
35619 ** it is desirable to avoid allocating a new page cache entry because
35620 ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
35621 ** for all page cache needs and we should not need to spill the
35622 ** allocation onto the heap.
35623 **
35624 ** Or, the heap is used for all page cache memory put the heap is
35625 ** under memory pressure, then again it is desirable to avoid
35626 ** allocating a new page cache entry in order to avoid stressing
35627 ** the heap even further.
35628 */
35629 static int pcache1UnderMemoryPressure(PCache1 *pCache){
35630   if( pcache1.nSlot && pCache->szPage<=pcache1.szSlot ){
35631     return pcache1.bUnderPressure;
35632   }else{
35633     return sqlite3HeapNearlyFull();
35634   }
35635 }
35636
35637 /******************************************************************************/
35638 /******** General Implementation Functions ************************************/
35639
35640 /*
35641 ** This function is used to resize the hash table used by the cache passed
35642 ** as the first argument.
35643 **
35644 ** The PCache mutex must be held when this function is called.
35645 */
35646 static int pcache1ResizeHash(PCache1 *p){
35647   PgHdr1 **apNew;
35648   unsigned int nNew;
35649   unsigned int i;
35650
35651   assert( sqlite3_mutex_held(p->pGroup->mutex) );
35652
35653   nNew = p->nHash*2;
35654   if( nNew<256 ){
35655     nNew = 256;
35656   }
35657
35658   pcache1LeaveMutex(p->pGroup);
35659   if( p->nHash ){ sqlite3BeginBenignMalloc(); }
35660   apNew = (PgHdr1 **)sqlite3_malloc(sizeof(PgHdr1 *)*nNew);
35661   if( p->nHash ){ sqlite3EndBenignMalloc(); }
35662   pcache1EnterMutex(p->pGroup);
35663   if( apNew ){
35664     memset(apNew, 0, sizeof(PgHdr1 *)*nNew);
35665     for(i=0; i<p->nHash; i++){
35666       PgHdr1 *pPage;
35667       PgHdr1 *pNext = p->apHash[i];
35668       while( (pPage = pNext)!=0 ){
35669         unsigned int h = pPage->iKey % nNew;
35670         pNext = pPage->pNext;
35671         pPage->pNext = apNew[h];
35672         apNew[h] = pPage;
35673       }
35674     }
35675     sqlite3_free(p->apHash);
35676     p->apHash = apNew;
35677     p->nHash = nNew;
35678   }
35679
35680   return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
35681 }
35682
35683 /*
35684 ** This function is used internally to remove the page pPage from the 
35685 ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
35686 ** LRU list, then this function is a no-op.
35687 **
35688 ** The PGroup mutex must be held when this function is called.
35689 **
35690 ** If pPage is NULL then this routine is a no-op.
35691 */
35692 static void pcache1PinPage(PgHdr1 *pPage){
35693   PCache1 *pCache;
35694   PGroup *pGroup;
35695
35696   if( pPage==0 ) return;
35697   pCache = pPage->pCache;
35698   pGroup = pCache->pGroup;
35699   assert( sqlite3_mutex_held(pGroup->mutex) );
35700   if( pPage->pLruNext || pPage==pGroup->pLruTail ){
35701     if( pPage->pLruPrev ){
35702       pPage->pLruPrev->pLruNext = pPage->pLruNext;
35703     }
35704     if( pPage->pLruNext ){
35705       pPage->pLruNext->pLruPrev = pPage->pLruPrev;
35706     }
35707     if( pGroup->pLruHead==pPage ){
35708       pGroup->pLruHead = pPage->pLruNext;
35709     }
35710     if( pGroup->pLruTail==pPage ){
35711       pGroup->pLruTail = pPage->pLruPrev;
35712     }
35713     pPage->pLruNext = 0;
35714     pPage->pLruPrev = 0;
35715     pPage->pCache->nRecyclable--;
35716   }
35717 }
35718
35719
35720 /*
35721 ** Remove the page supplied as an argument from the hash table 
35722 ** (PCache1.apHash structure) that it is currently stored in.
35723 **
35724 ** The PGroup mutex must be held when this function is called.
35725 */
35726 static void pcache1RemoveFromHash(PgHdr1 *pPage){
35727   unsigned int h;
35728   PCache1 *pCache = pPage->pCache;
35729   PgHdr1 **pp;
35730
35731   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
35732   h = pPage->iKey % pCache->nHash;
35733   for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
35734   *pp = (*pp)->pNext;
35735
35736   pCache->nPage--;
35737 }
35738
35739 /*
35740 ** If there are currently more than nMaxPage pages allocated, try
35741 ** to recycle pages to reduce the number allocated to nMaxPage.
35742 */
35743 static void pcache1EnforceMaxPage(PGroup *pGroup){
35744   assert( sqlite3_mutex_held(pGroup->mutex) );
35745   while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){
35746     PgHdr1 *p = pGroup->pLruTail;
35747     assert( p->pCache->pGroup==pGroup );
35748     pcache1PinPage(p);
35749     pcache1RemoveFromHash(p);
35750     pcache1FreePage(p);
35751   }
35752 }
35753
35754 /*
35755 ** Discard all pages from cache pCache with a page number (key value) 
35756 ** greater than or equal to iLimit. Any pinned pages that meet this 
35757 ** criteria are unpinned before they are discarded.
35758 **
35759 ** The PCache mutex must be held when this function is called.
35760 */
35761 static void pcache1TruncateUnsafe(
35762   PCache1 *pCache,             /* The cache to truncate */
35763   unsigned int iLimit          /* Drop pages with this pgno or larger */
35764 ){
35765   TESTONLY( unsigned int nPage = 0; )  /* To assert pCache->nPage is correct */
35766   unsigned int h;
35767   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
35768   for(h=0; h<pCache->nHash; h++){
35769     PgHdr1 **pp = &pCache->apHash[h]; 
35770     PgHdr1 *pPage;
35771     while( (pPage = *pp)!=0 ){
35772       if( pPage->iKey>=iLimit ){
35773         pCache->nPage--;
35774         *pp = pPage->pNext;
35775         pcache1PinPage(pPage);
35776         pcache1FreePage(pPage);
35777       }else{
35778         pp = &pPage->pNext;
35779         TESTONLY( nPage++; )
35780       }
35781     }
35782   }
35783   assert( pCache->nPage==nPage );
35784 }
35785
35786 /******************************************************************************/
35787 /******** sqlite3_pcache Methods **********************************************/
35788
35789 /*
35790 ** Implementation of the sqlite3_pcache.xInit method.
35791 */
35792 static int pcache1Init(void *NotUsed){
35793   UNUSED_PARAMETER(NotUsed);
35794   assert( pcache1.isInit==0 );
35795   memset(&pcache1, 0, sizeof(pcache1));
35796   if( sqlite3GlobalConfig.bCoreMutex ){
35797     pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
35798     pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
35799   }
35800   pcache1.grp.mxPinned = 10;
35801   pcache1.isInit = 1;
35802   return SQLITE_OK;
35803 }
35804
35805 /*
35806 ** Implementation of the sqlite3_pcache.xShutdown method.
35807 ** Note that the static mutex allocated in xInit does 
35808 ** not need to be freed.
35809 */
35810 static void pcache1Shutdown(void *NotUsed){
35811   UNUSED_PARAMETER(NotUsed);
35812   assert( pcache1.isInit!=0 );
35813   memset(&pcache1, 0, sizeof(pcache1));
35814 }
35815
35816 /*
35817 ** Implementation of the sqlite3_pcache.xCreate method.
35818 **
35819 ** Allocate a new cache.
35820 */
35821 static sqlite3_pcache *pcache1Create(int szPage, int bPurgeable){
35822   PCache1 *pCache;      /* The newly created page cache */
35823   PGroup *pGroup;       /* The group the new page cache will belong to */
35824   int sz;               /* Bytes of memory required to allocate the new cache */
35825
35826   /*
35827   ** The seperateCache variable is true if each PCache has its own private
35828   ** PGroup.  In other words, separateCache is true for mode (1) where no
35829   ** mutexing is required.
35830   **
35831   **   *  Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
35832   **
35833   **   *  Always use a unified cache in single-threaded applications
35834   **
35835   **   *  Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off)
35836   **      use separate caches (mode-1)
35837   */
35838 #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
35839   const int separateCache = 0;
35840 #else
35841   int separateCache = sqlite3GlobalConfig.bCoreMutex>0;
35842 #endif
35843
35844   sz = sizeof(PCache1) + sizeof(PGroup)*separateCache;
35845   pCache = (PCache1 *)sqlite3_malloc(sz);
35846   if( pCache ){
35847     memset(pCache, 0, sz);
35848     if( separateCache ){
35849       pGroup = (PGroup*)&pCache[1];
35850       pGroup->mxPinned = 10;
35851     }else{
35852       pGroup = &pcache1.grp;
35853     }
35854     pCache->pGroup = pGroup;
35855     pCache->szPage = szPage;
35856     pCache->bPurgeable = (bPurgeable ? 1 : 0);
35857     if( bPurgeable ){
35858       pCache->nMin = 10;
35859       pcache1EnterMutex(pGroup);
35860       pGroup->nMinPage += pCache->nMin;
35861       pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
35862       pcache1LeaveMutex(pGroup);
35863     }
35864   }
35865   return (sqlite3_pcache *)pCache;
35866 }
35867
35868 /*
35869 ** Implementation of the sqlite3_pcache.xCachesize method. 
35870 **
35871 ** Configure the cache_size limit for a cache.
35872 */
35873 static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
35874   PCache1 *pCache = (PCache1 *)p;
35875   if( pCache->bPurgeable ){
35876     PGroup *pGroup = pCache->pGroup;
35877     pcache1EnterMutex(pGroup);
35878     pGroup->nMaxPage += (nMax - pCache->nMax);
35879     pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
35880     pCache->nMax = nMax;
35881     pCache->n90pct = pCache->nMax*9/10;
35882     pcache1EnforceMaxPage(pGroup);
35883     pcache1LeaveMutex(pGroup);
35884   }
35885 }
35886
35887 /*
35888 ** Implementation of the sqlite3_pcache.xPagecount method. 
35889 */
35890 static int pcache1Pagecount(sqlite3_pcache *p){
35891   int n;
35892   PCache1 *pCache = (PCache1*)p;
35893   pcache1EnterMutex(pCache->pGroup);
35894   n = pCache->nPage;
35895   pcache1LeaveMutex(pCache->pGroup);
35896   return n;
35897 }
35898
35899 /*
35900 ** Implementation of the sqlite3_pcache.xFetch method. 
35901 **
35902 ** Fetch a page by key value.
35903 **
35904 ** Whether or not a new page may be allocated by this function depends on
35905 ** the value of the createFlag argument.  0 means do not allocate a new
35906 ** page.  1 means allocate a new page if space is easily available.  2 
35907 ** means to try really hard to allocate a new page.
35908 **
35909 ** For a non-purgeable cache (a cache used as the storage for an in-memory
35910 ** database) there is really no difference between createFlag 1 and 2.  So
35911 ** the calling function (pcache.c) will never have a createFlag of 1 on
35912 ** a non-purgable cache.
35913 **
35914 ** There are three different approaches to obtaining space for a page,
35915 ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
35916 **
35917 **   1. Regardless of the value of createFlag, the cache is searched for a 
35918 **      copy of the requested page. If one is found, it is returned.
35919 **
35920 **   2. If createFlag==0 and the page is not already in the cache, NULL is
35921 **      returned.
35922 **
35923 **   3. If createFlag is 1, and the page is not already in the cache, then
35924 **      return NULL (do not allocate a new page) if any of the following
35925 **      conditions are true:
35926 **
35927 **       (a) the number of pages pinned by the cache is greater than
35928 **           PCache1.nMax, or
35929 **
35930 **       (b) the number of pages pinned by the cache is greater than
35931 **           the sum of nMax for all purgeable caches, less the sum of 
35932 **           nMin for all other purgeable caches, or
35933 **
35934 **   4. If none of the first three conditions apply and the cache is marked
35935 **      as purgeable, and if one of the following is true:
35936 **
35937 **       (a) The number of pages allocated for the cache is already 
35938 **           PCache1.nMax, or
35939 **
35940 **       (b) The number of pages allocated for all purgeable caches is
35941 **           already equal to or greater than the sum of nMax for all
35942 **           purgeable caches,
35943 **
35944 **       (c) The system is under memory pressure and wants to avoid
35945 **           unnecessary pages cache entry allocations
35946 **
35947 **      then attempt to recycle a page from the LRU list. If it is the right
35948 **      size, return the recycled buffer. Otherwise, free the buffer and
35949 **      proceed to step 5. 
35950 **
35951 **   5. Otherwise, allocate and return a new page buffer.
35952 */
35953 static void *pcache1Fetch(sqlite3_pcache *p, unsigned int iKey, int createFlag){
35954   int nPinned;
35955   PCache1 *pCache = (PCache1 *)p;
35956   PGroup *pGroup;
35957   PgHdr1 *pPage = 0;
35958
35959   assert( pCache->bPurgeable || createFlag!=1 );
35960   assert( pCache->bPurgeable || pCache->nMin==0 );
35961   assert( pCache->bPurgeable==0 || pCache->nMin==10 );
35962   assert( pCache->nMin==0 || pCache->bPurgeable );
35963   pcache1EnterMutex(pGroup = pCache->pGroup);
35964
35965   /* Step 1: Search the hash table for an existing entry. */
35966   if( pCache->nHash>0 ){
35967     unsigned int h = iKey % pCache->nHash;
35968     for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
35969   }
35970
35971   /* Step 2: Abort if no existing page is found and createFlag is 0 */
35972   if( pPage || createFlag==0 ){
35973     pcache1PinPage(pPage);
35974     goto fetch_out;
35975   }
35976
35977   /* The pGroup local variable will normally be initialized by the
35978   ** pcache1EnterMutex() macro above.  But if SQLITE_MUTEX_OMIT is defined,
35979   ** then pcache1EnterMutex() is a no-op, so we have to initialize the
35980   ** local variable here.  Delaying the initialization of pGroup is an
35981   ** optimization:  The common case is to exit the module before reaching
35982   ** this point.
35983   */
35984 #ifdef SQLITE_MUTEX_OMIT
35985   pGroup = pCache->pGroup;
35986 #endif
35987
35988
35989   /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
35990   nPinned = pCache->nPage - pCache->nRecyclable;
35991   assert( nPinned>=0 );
35992   assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
35993   assert( pCache->n90pct == pCache->nMax*9/10 );
35994   if( createFlag==1 && (
35995         nPinned>=pGroup->mxPinned
35996      || nPinned>=(int)pCache->n90pct
35997      || pcache1UnderMemoryPressure(pCache)
35998   )){
35999     goto fetch_out;
36000   }
36001
36002   if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
36003     goto fetch_out;
36004   }
36005
36006   /* Step 4. Try to recycle a page. */
36007   if( pCache->bPurgeable && pGroup->pLruTail && (
36008          (pCache->nPage+1>=pCache->nMax)
36009       || pGroup->nCurrentPage>=pGroup->nMaxPage
36010       || pcache1UnderMemoryPressure(pCache)
36011   )){
36012     PCache1 *pOtherCache;
36013     pPage = pGroup->pLruTail;
36014     pcache1RemoveFromHash(pPage);
36015     pcache1PinPage(pPage);
36016     if( (pOtherCache = pPage->pCache)->szPage!=pCache->szPage ){
36017       pcache1FreePage(pPage);
36018       pPage = 0;
36019     }else{
36020       pGroup->nCurrentPage -= 
36021                (pOtherCache->bPurgeable - pCache->bPurgeable);
36022     }
36023   }
36024
36025   /* Step 5. If a usable page buffer has still not been found, 
36026   ** attempt to allocate a new one. 
36027   */
36028   if( !pPage ){
36029     if( createFlag==1 ) sqlite3BeginBenignMalloc();
36030     pcache1LeaveMutex(pGroup);
36031     pPage = pcache1AllocPage(pCache);
36032     pcache1EnterMutex(pGroup);
36033     if( createFlag==1 ) sqlite3EndBenignMalloc();
36034   }
36035
36036   if( pPage ){
36037     unsigned int h = iKey % pCache->nHash;
36038     pCache->nPage++;
36039     pPage->iKey = iKey;
36040     pPage->pNext = pCache->apHash[h];
36041     pPage->pCache = pCache;
36042     pPage->pLruPrev = 0;
36043     pPage->pLruNext = 0;
36044     *(void **)(PGHDR1_TO_PAGE(pPage)) = 0;
36045     pCache->apHash[h] = pPage;
36046   }
36047
36048 fetch_out:
36049   if( pPage && iKey>pCache->iMaxKey ){
36050     pCache->iMaxKey = iKey;
36051   }
36052   pcache1LeaveMutex(pGroup);
36053   return (pPage ? PGHDR1_TO_PAGE(pPage) : 0);
36054 }
36055
36056
36057 /*
36058 ** Implementation of the sqlite3_pcache.xUnpin method.
36059 **
36060 ** Mark a page as unpinned (eligible for asynchronous recycling).
36061 */
36062 static void pcache1Unpin(sqlite3_pcache *p, void *pPg, int reuseUnlikely){
36063   PCache1 *pCache = (PCache1 *)p;
36064   PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
36065   PGroup *pGroup = pCache->pGroup;
36066  
36067   assert( pPage->pCache==pCache );
36068   pcache1EnterMutex(pGroup);
36069
36070   /* It is an error to call this function if the page is already 
36071   ** part of the PGroup LRU list.
36072   */
36073   assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
36074   assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage );
36075
36076   if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
36077     pcache1RemoveFromHash(pPage);
36078     pcache1FreePage(pPage);
36079   }else{
36080     /* Add the page to the PGroup LRU list. */
36081     if( pGroup->pLruHead ){
36082       pGroup->pLruHead->pLruPrev = pPage;
36083       pPage->pLruNext = pGroup->pLruHead;
36084       pGroup->pLruHead = pPage;
36085     }else{
36086       pGroup->pLruTail = pPage;
36087       pGroup->pLruHead = pPage;
36088     }
36089     pCache->nRecyclable++;
36090   }
36091
36092   pcache1LeaveMutex(pCache->pGroup);
36093 }
36094
36095 /*
36096 ** Implementation of the sqlite3_pcache.xRekey method. 
36097 */
36098 static void pcache1Rekey(
36099   sqlite3_pcache *p,
36100   void *pPg,
36101   unsigned int iOld,
36102   unsigned int iNew
36103 ){
36104   PCache1 *pCache = (PCache1 *)p;
36105   PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
36106   PgHdr1 **pp;
36107   unsigned int h; 
36108   assert( pPage->iKey==iOld );
36109   assert( pPage->pCache==pCache );
36110
36111   pcache1EnterMutex(pCache->pGroup);
36112
36113   h = iOld%pCache->nHash;
36114   pp = &pCache->apHash[h];
36115   while( (*pp)!=pPage ){
36116     pp = &(*pp)->pNext;
36117   }
36118   *pp = pPage->pNext;
36119
36120   h = iNew%pCache->nHash;
36121   pPage->iKey = iNew;
36122   pPage->pNext = pCache->apHash[h];
36123   pCache->apHash[h] = pPage;
36124   if( iNew>pCache->iMaxKey ){
36125     pCache->iMaxKey = iNew;
36126   }
36127
36128   pcache1LeaveMutex(pCache->pGroup);
36129 }
36130
36131 /*
36132 ** Implementation of the sqlite3_pcache.xTruncate method. 
36133 **
36134 ** Discard all unpinned pages in the cache with a page number equal to
36135 ** or greater than parameter iLimit. Any pinned pages with a page number
36136 ** equal to or greater than iLimit are implicitly unpinned.
36137 */
36138 static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
36139   PCache1 *pCache = (PCache1 *)p;
36140   pcache1EnterMutex(pCache->pGroup);
36141   if( iLimit<=pCache->iMaxKey ){
36142     pcache1TruncateUnsafe(pCache, iLimit);
36143     pCache->iMaxKey = iLimit-1;
36144   }
36145   pcache1LeaveMutex(pCache->pGroup);
36146 }
36147
36148 /*
36149 ** Implementation of the sqlite3_pcache.xDestroy method. 
36150 **
36151 ** Destroy a cache allocated using pcache1Create().
36152 */
36153 static void pcache1Destroy(sqlite3_pcache *p){
36154   PCache1 *pCache = (PCache1 *)p;
36155   PGroup *pGroup = pCache->pGroup;
36156   assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
36157   pcache1EnterMutex(pGroup);
36158   pcache1TruncateUnsafe(pCache, 0);
36159   pGroup->nMaxPage -= pCache->nMax;
36160   pGroup->nMinPage -= pCache->nMin;
36161   pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
36162   pcache1EnforceMaxPage(pGroup);
36163   pcache1LeaveMutex(pGroup);
36164   sqlite3_free(pCache->apHash);
36165   sqlite3_free(pCache);
36166 }
36167
36168 /*
36169 ** This function is called during initialization (sqlite3_initialize()) to
36170 ** install the default pluggable cache module, assuming the user has not
36171 ** already provided an alternative.
36172 */
36173 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
36174   static const sqlite3_pcache_methods defaultMethods = {
36175     0,                       /* pArg */
36176     pcache1Init,             /* xInit */
36177     pcache1Shutdown,         /* xShutdown */
36178     pcache1Create,           /* xCreate */
36179     pcache1Cachesize,        /* xCachesize */
36180     pcache1Pagecount,        /* xPagecount */
36181     pcache1Fetch,            /* xFetch */
36182     pcache1Unpin,            /* xUnpin */
36183     pcache1Rekey,            /* xRekey */
36184     pcache1Truncate,         /* xTruncate */
36185     pcache1Destroy           /* xDestroy */
36186   };
36187   sqlite3_config(SQLITE_CONFIG_PCACHE, &defaultMethods);
36188 }
36189
36190 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
36191 /*
36192 ** This function is called to free superfluous dynamically allocated memory
36193 ** held by the pager system. Memory in use by any SQLite pager allocated
36194 ** by the current thread may be sqlite3_free()ed.
36195 **
36196 ** nReq is the number of bytes of memory required. Once this much has
36197 ** been released, the function returns. The return value is the total number 
36198 ** of bytes of memory released.
36199 */
36200 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
36201   int nFree = 0;
36202   assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
36203   assert( sqlite3_mutex_notheld(pcache1.mutex) );
36204   if( pcache1.pStart==0 ){
36205     PgHdr1 *p;
36206     pcache1EnterMutex(&pcache1.grp);
36207     while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){
36208       nFree += pcache1MemSize(PGHDR1_TO_PAGE(p));
36209       pcache1PinPage(p);
36210       pcache1RemoveFromHash(p);
36211       pcache1FreePage(p);
36212     }
36213     pcache1LeaveMutex(&pcache1.grp);
36214   }
36215   return nFree;
36216 }
36217 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
36218
36219 #ifdef SQLITE_TEST
36220 /*
36221 ** This function is used by test procedures to inspect the internal state
36222 ** of the global cache.
36223 */
36224 SQLITE_PRIVATE void sqlite3PcacheStats(
36225   int *pnCurrent,      /* OUT: Total number of pages cached */
36226   int *pnMax,          /* OUT: Global maximum cache size */
36227   int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
36228   int *pnRecyclable    /* OUT: Total number of pages available for recycling */
36229 ){
36230   PgHdr1 *p;
36231   int nRecyclable = 0;
36232   for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){
36233     nRecyclable++;
36234   }
36235   *pnCurrent = pcache1.grp.nCurrentPage;
36236   *pnMax = pcache1.grp.nMaxPage;
36237   *pnMin = pcache1.grp.nMinPage;
36238   *pnRecyclable = nRecyclable;
36239 }
36240 #endif
36241
36242 /************** End of pcache1.c *********************************************/
36243 /************** Begin file rowset.c ******************************************/
36244 /*
36245 ** 2008 December 3
36246 **
36247 ** The author disclaims copyright to this source code.  In place of
36248 ** a legal notice, here is a blessing:
36249 **
36250 **    May you do good and not evil.
36251 **    May you find forgiveness for yourself and forgive others.
36252 **    May you share freely, never taking more than you give.
36253 **
36254 *************************************************************************
36255 **
36256 ** This module implements an object we call a "RowSet".
36257 **
36258 ** The RowSet object is a collection of rowids.  Rowids
36259 ** are inserted into the RowSet in an arbitrary order.  Inserts
36260 ** can be intermixed with tests to see if a given rowid has been
36261 ** previously inserted into the RowSet.
36262 **
36263 ** After all inserts are finished, it is possible to extract the
36264 ** elements of the RowSet in sorted order.  Once this extraction
36265 ** process has started, no new elements may be inserted.
36266 **
36267 ** Hence, the primitive operations for a RowSet are:
36268 **
36269 **    CREATE
36270 **    INSERT
36271 **    TEST
36272 **    SMALLEST
36273 **    DESTROY
36274 **
36275 ** The CREATE and DESTROY primitives are the constructor and destructor,
36276 ** obviously.  The INSERT primitive adds a new element to the RowSet.
36277 ** TEST checks to see if an element is already in the RowSet.  SMALLEST
36278 ** extracts the least value from the RowSet.
36279 **
36280 ** The INSERT primitive might allocate additional memory.  Memory is
36281 ** allocated in chunks so most INSERTs do no allocation.  There is an 
36282 ** upper bound on the size of allocated memory.  No memory is freed
36283 ** until DESTROY.
36284 **
36285 ** The TEST primitive includes a "batch" number.  The TEST primitive
36286 ** will only see elements that were inserted before the last change
36287 ** in the batch number.  In other words, if an INSERT occurs between
36288 ** two TESTs where the TESTs have the same batch nubmer, then the
36289 ** value added by the INSERT will not be visible to the second TEST.
36290 ** The initial batch number is zero, so if the very first TEST contains
36291 ** a non-zero batch number, it will see all prior INSERTs.
36292 **
36293 ** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
36294 ** that is attempted.
36295 **
36296 ** The cost of an INSERT is roughly constant.  (Sometime new memory
36297 ** has to be allocated on an INSERT.)  The cost of a TEST with a new
36298 ** batch number is O(NlogN) where N is the number of elements in the RowSet.
36299 ** The cost of a TEST using the same batch number is O(logN).  The cost
36300 ** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
36301 ** primitives are constant time.  The cost of DESTROY is O(N).
36302 **
36303 ** There is an added cost of O(N) when switching between TEST and
36304 ** SMALLEST primitives.
36305 */
36306
36307
36308 /*
36309 ** Target size for allocation chunks.
36310 */
36311 #define ROWSET_ALLOCATION_SIZE 1024
36312
36313 /*
36314 ** The number of rowset entries per allocation chunk.
36315 */
36316 #define ROWSET_ENTRY_PER_CHUNK  \
36317                        ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
36318
36319 /*
36320 ** Each entry in a RowSet is an instance of the following object.
36321 */
36322 struct RowSetEntry {            
36323   i64 v;                        /* ROWID value for this entry */
36324   struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
36325   struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
36326 };
36327
36328 /*
36329 ** RowSetEntry objects are allocated in large chunks (instances of the
36330 ** following structure) to reduce memory allocation overhead.  The
36331 ** chunks are kept on a linked list so that they can be deallocated
36332 ** when the RowSet is destroyed.
36333 */
36334 struct RowSetChunk {
36335   struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
36336   struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
36337 };
36338
36339 /*
36340 ** A RowSet in an instance of the following structure.
36341 **
36342 ** A typedef of this structure if found in sqliteInt.h.
36343 */
36344 struct RowSet {
36345   struct RowSetChunk *pChunk;    /* List of all chunk allocations */
36346   sqlite3 *db;                   /* The database connection */
36347   struct RowSetEntry *pEntry;    /* List of entries using pRight */
36348   struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
36349   struct RowSetEntry *pFresh;    /* Source of new entry objects */
36350   struct RowSetEntry *pTree;     /* Binary tree of entries */
36351   u16 nFresh;                    /* Number of objects on pFresh */
36352   u8 isSorted;                   /* True if pEntry is sorted */
36353   u8 iBatch;                     /* Current insert batch */
36354 };
36355
36356 /*
36357 ** Turn bulk memory into a RowSet object.  N bytes of memory
36358 ** are available at pSpace.  The db pointer is used as a memory context
36359 ** for any subsequent allocations that need to occur.
36360 ** Return a pointer to the new RowSet object.
36361 **
36362 ** It must be the case that N is sufficient to make a Rowset.  If not
36363 ** an assertion fault occurs.
36364 ** 
36365 ** If N is larger than the minimum, use the surplus as an initial
36366 ** allocation of entries available to be filled.
36367 */
36368 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
36369   RowSet *p;
36370   assert( N >= ROUND8(sizeof(*p)) );
36371   p = pSpace;
36372   p->pChunk = 0;
36373   p->db = db;
36374   p->pEntry = 0;
36375   p->pLast = 0;
36376   p->pTree = 0;
36377   p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
36378   p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
36379   p->isSorted = 1;
36380   p->iBatch = 0;
36381   return p;
36382 }
36383
36384 /*
36385 ** Deallocate all chunks from a RowSet.  This frees all memory that
36386 ** the RowSet has allocated over its lifetime.  This routine is
36387 ** the destructor for the RowSet.
36388 */
36389 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
36390   struct RowSetChunk *pChunk, *pNextChunk;
36391   for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
36392     pNextChunk = pChunk->pNextChunk;
36393     sqlite3DbFree(p->db, pChunk);
36394   }
36395   p->pChunk = 0;
36396   p->nFresh = 0;
36397   p->pEntry = 0;
36398   p->pLast = 0;
36399   p->pTree = 0;
36400   p->isSorted = 1;
36401 }
36402
36403 /*
36404 ** Insert a new value into a RowSet.
36405 **
36406 ** The mallocFailed flag of the database connection is set if a
36407 ** memory allocation fails.
36408 */
36409 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
36410   struct RowSetEntry *pEntry;  /* The new entry */
36411   struct RowSetEntry *pLast;   /* The last prior entry */
36412   assert( p!=0 );
36413   if( p->nFresh==0 ){
36414     struct RowSetChunk *pNew;
36415     pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
36416     if( pNew==0 ){
36417       return;
36418     }
36419     pNew->pNextChunk = p->pChunk;
36420     p->pChunk = pNew;
36421     p->pFresh = pNew->aEntry;
36422     p->nFresh = ROWSET_ENTRY_PER_CHUNK;
36423   }
36424   pEntry = p->pFresh++;
36425   p->nFresh--;
36426   pEntry->v = rowid;
36427   pEntry->pRight = 0;
36428   pLast = p->pLast;
36429   if( pLast ){
36430     if( p->isSorted && rowid<=pLast->v ){
36431       p->isSorted = 0;
36432     }
36433     pLast->pRight = pEntry;
36434   }else{
36435     assert( p->pEntry==0 ); /* Fires if INSERT after SMALLEST */
36436     p->pEntry = pEntry;
36437   }
36438   p->pLast = pEntry;
36439 }
36440
36441 /*
36442 ** Merge two lists of RowSetEntry objects.  Remove duplicates.
36443 **
36444 ** The input lists are connected via pRight pointers and are 
36445 ** assumed to each already be in sorted order.
36446 */
36447 static struct RowSetEntry *rowSetMerge(
36448   struct RowSetEntry *pA,    /* First sorted list to be merged */
36449   struct RowSetEntry *pB     /* Second sorted list to be merged */
36450 ){
36451   struct RowSetEntry head;
36452   struct RowSetEntry *pTail;
36453
36454   pTail = &head;
36455   while( pA && pB ){
36456     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
36457     assert( pB->pRight==0 || pB->v<=pB->pRight->v );
36458     if( pA->v<pB->v ){
36459       pTail->pRight = pA;
36460       pA = pA->pRight;
36461       pTail = pTail->pRight;
36462     }else if( pB->v<pA->v ){
36463       pTail->pRight = pB;
36464       pB = pB->pRight;
36465       pTail = pTail->pRight;
36466     }else{
36467       pA = pA->pRight;
36468     }
36469   }
36470   if( pA ){
36471     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
36472     pTail->pRight = pA;
36473   }else{
36474     assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
36475     pTail->pRight = pB;
36476   }
36477   return head.pRight;
36478 }
36479
36480 /*
36481 ** Sort all elements on the pEntry list of the RowSet into ascending order.
36482 */ 
36483 static void rowSetSort(RowSet *p){
36484   unsigned int i;
36485   struct RowSetEntry *pEntry;
36486   struct RowSetEntry *aBucket[40];
36487
36488   assert( p->isSorted==0 );
36489   memset(aBucket, 0, sizeof(aBucket));
36490   while( p->pEntry ){
36491     pEntry = p->pEntry;
36492     p->pEntry = pEntry->pRight;
36493     pEntry->pRight = 0;
36494     for(i=0; aBucket[i]; i++){
36495       pEntry = rowSetMerge(aBucket[i], pEntry);
36496       aBucket[i] = 0;
36497     }
36498     aBucket[i] = pEntry;
36499   }
36500   pEntry = 0;
36501   for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
36502     pEntry = rowSetMerge(pEntry, aBucket[i]);
36503   }
36504   p->pEntry = pEntry;
36505   p->pLast = 0;
36506   p->isSorted = 1;
36507 }
36508
36509
36510 /*
36511 ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
36512 ** Convert this tree into a linked list connected by the pRight pointers
36513 ** and return pointers to the first and last elements of the new list.
36514 */
36515 static void rowSetTreeToList(
36516   struct RowSetEntry *pIn,         /* Root of the input tree */
36517   struct RowSetEntry **ppFirst,    /* Write head of the output list here */
36518   struct RowSetEntry **ppLast      /* Write tail of the output list here */
36519 ){
36520   assert( pIn!=0 );
36521   if( pIn->pLeft ){
36522     struct RowSetEntry *p;
36523     rowSetTreeToList(pIn->pLeft, ppFirst, &p);
36524     p->pRight = pIn;
36525   }else{
36526     *ppFirst = pIn;
36527   }
36528   if( pIn->pRight ){
36529     rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
36530   }else{
36531     *ppLast = pIn;
36532   }
36533   assert( (*ppLast)->pRight==0 );
36534 }
36535
36536
36537 /*
36538 ** Convert a sorted list of elements (connected by pRight) into a binary
36539 ** tree with depth of iDepth.  A depth of 1 means the tree contains a single
36540 ** node taken from the head of *ppList.  A depth of 2 means a tree with
36541 ** three nodes.  And so forth.
36542 **
36543 ** Use as many entries from the input list as required and update the
36544 ** *ppList to point to the unused elements of the list.  If the input
36545 ** list contains too few elements, then construct an incomplete tree
36546 ** and leave *ppList set to NULL.
36547 **
36548 ** Return a pointer to the root of the constructed binary tree.
36549 */
36550 static struct RowSetEntry *rowSetNDeepTree(
36551   struct RowSetEntry **ppList,
36552   int iDepth
36553 ){
36554   struct RowSetEntry *p;         /* Root of the new tree */
36555   struct RowSetEntry *pLeft;     /* Left subtree */
36556   if( *ppList==0 ){
36557     return 0;
36558   }
36559   if( iDepth==1 ){
36560     p = *ppList;
36561     *ppList = p->pRight;
36562     p->pLeft = p->pRight = 0;
36563     return p;
36564   }
36565   pLeft = rowSetNDeepTree(ppList, iDepth-1);
36566   p = *ppList;
36567   if( p==0 ){
36568     return pLeft;
36569   }
36570   p->pLeft = pLeft;
36571   *ppList = p->pRight;
36572   p->pRight = rowSetNDeepTree(ppList, iDepth-1);
36573   return p;
36574 }
36575
36576 /*
36577 ** Convert a sorted list of elements into a binary tree. Make the tree
36578 ** as deep as it needs to be in order to contain the entire list.
36579 */
36580 static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
36581   int iDepth;           /* Depth of the tree so far */
36582   struct RowSetEntry *p;       /* Current tree root */
36583   struct RowSetEntry *pLeft;   /* Left subtree */
36584
36585   assert( pList!=0 );
36586   p = pList;
36587   pList = p->pRight;
36588   p->pLeft = p->pRight = 0;
36589   for(iDepth=1; pList; iDepth++){
36590     pLeft = p;
36591     p = pList;
36592     pList = p->pRight;
36593     p->pLeft = pLeft;
36594     p->pRight = rowSetNDeepTree(&pList, iDepth);
36595   }
36596   return p;
36597 }
36598
36599 /*
36600 ** Convert the list in p->pEntry into a sorted list if it is not
36601 ** sorted already.  If there is a binary tree on p->pTree, then
36602 ** convert it into a list too and merge it into the p->pEntry list.
36603 */
36604 static void rowSetToList(RowSet *p){
36605   if( !p->isSorted ){
36606     rowSetSort(p);
36607   }
36608   if( p->pTree ){
36609     struct RowSetEntry *pHead, *pTail;
36610     rowSetTreeToList(p->pTree, &pHead, &pTail);
36611     p->pTree = 0;
36612     p->pEntry = rowSetMerge(p->pEntry, pHead);
36613   }
36614 }
36615
36616 /*
36617 ** Extract the smallest element from the RowSet.
36618 ** Write the element into *pRowid.  Return 1 on success.  Return
36619 ** 0 if the RowSet is already empty.
36620 **
36621 ** After this routine has been called, the sqlite3RowSetInsert()
36622 ** routine may not be called again.  
36623 */
36624 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
36625   rowSetToList(p);
36626   if( p->pEntry ){
36627     *pRowid = p->pEntry->v;
36628     p->pEntry = p->pEntry->pRight;
36629     if( p->pEntry==0 ){
36630       sqlite3RowSetClear(p);
36631     }
36632     return 1;
36633   }else{
36634     return 0;
36635   }
36636 }
36637
36638 /*
36639 ** Check to see if element iRowid was inserted into the the rowset as
36640 ** part of any insert batch prior to iBatch.  Return 1 or 0.
36641 */
36642 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
36643   struct RowSetEntry *p;
36644   if( iBatch!=pRowSet->iBatch ){
36645     if( pRowSet->pEntry ){
36646       rowSetToList(pRowSet);
36647       pRowSet->pTree = rowSetListToTree(pRowSet->pEntry);
36648       pRowSet->pEntry = 0;
36649       pRowSet->pLast = 0;
36650     }
36651     pRowSet->iBatch = iBatch;
36652   }
36653   p = pRowSet->pTree;
36654   while( p ){
36655     if( p->v<iRowid ){
36656       p = p->pRight;
36657     }else if( p->v>iRowid ){
36658       p = p->pLeft;
36659     }else{
36660       return 1;
36661     }
36662   }
36663   return 0;
36664 }
36665
36666 /************** End of rowset.c **********************************************/
36667 /************** Begin file pager.c *******************************************/
36668 /*
36669 ** 2001 September 15
36670 **
36671 ** The author disclaims copyright to this source code.  In place of
36672 ** a legal notice, here is a blessing:
36673 **
36674 **    May you do good and not evil.
36675 **    May you find forgiveness for yourself and forgive others.
36676 **    May you share freely, never taking more than you give.
36677 **
36678 *************************************************************************
36679 ** This is the implementation of the page cache subsystem or "pager".
36680 ** 
36681 ** The pager is used to access a database disk file.  It implements
36682 ** atomic commit and rollback through the use of a journal file that
36683 ** is separate from the database file.  The pager also implements file
36684 ** locking to prevent two processes from writing the same database
36685 ** file simultaneously, or one process from reading the database while
36686 ** another is writing.
36687 */
36688 #ifndef SQLITE_OMIT_DISKIO
36689 /************** Include wal.h in the middle of pager.c ***********************/
36690 /************** Begin file wal.h *********************************************/
36691 /*
36692 ** 2010 February 1
36693 **
36694 ** The author disclaims copyright to this source code.  In place of
36695 ** a legal notice, here is a blessing:
36696 **
36697 **    May you do good and not evil.
36698 **    May you find forgiveness for yourself and forgive others.
36699 **    May you share freely, never taking more than you give.
36700 **
36701 *************************************************************************
36702 ** This header file defines the interface to the write-ahead logging 
36703 ** system. Refer to the comments below and the header comment attached to 
36704 ** the implementation of each function in log.c for further details.
36705 */
36706
36707 #ifndef _WAL_H_
36708 #define _WAL_H_
36709
36710
36711 #ifdef SQLITE_OMIT_WAL
36712 # define sqlite3WalOpen(x,y,z)                   0
36713 # define sqlite3WalLimit(x,y)
36714 # define sqlite3WalClose(w,x,y,z)                0
36715 # define sqlite3WalBeginReadTransaction(y,z)     0
36716 # define sqlite3WalEndReadTransaction(z)
36717 # define sqlite3WalRead(v,w,x,y,z)               0
36718 # define sqlite3WalDbsize(y)                     0
36719 # define sqlite3WalBeginWriteTransaction(y)      0
36720 # define sqlite3WalEndWriteTransaction(x)        0
36721 # define sqlite3WalUndo(x,y,z)                   0
36722 # define sqlite3WalSavepoint(y,z)
36723 # define sqlite3WalSavepointUndo(y,z)            0
36724 # define sqlite3WalFrames(u,v,w,x,y,z)           0
36725 # define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
36726 # define sqlite3WalCallback(z)                   0
36727 # define sqlite3WalExclusiveMode(y,z)            0
36728 # define sqlite3WalHeapMemory(z)                 0
36729 #else
36730
36731 #define WAL_SAVEPOINT_NDATA 4
36732
36733 /* Connection to a write-ahead log (WAL) file. 
36734 ** There is one object of this type for each pager. 
36735 */
36736 typedef struct Wal Wal;
36737
36738 /* Open and close a connection to a write-ahead log. */
36739 SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
36740 SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
36741
36742 /* Set the limiting size of a WAL file. */
36743 SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
36744
36745 /* Used by readers to open (lock) and close (unlock) a snapshot.  A 
36746 ** snapshot is like a read-transaction.  It is the state of the database
36747 ** at an instant in time.  sqlite3WalOpenSnapshot gets a read lock and
36748 ** preserves the current state even if the other threads or processes
36749 ** write to or checkpoint the WAL.  sqlite3WalCloseSnapshot() closes the
36750 ** transaction and releases the lock.
36751 */
36752 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
36753 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
36754
36755 /* Read a page from the write-ahead log, if it is present. */
36756 SQLITE_PRIVATE int sqlite3WalRead(Wal *pWal, Pgno pgno, int *pInWal, int nOut, u8 *pOut);
36757
36758 /* If the WAL is not empty, return the size of the database. */
36759 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
36760
36761 /* Obtain or release the WRITER lock. */
36762 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
36763 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
36764
36765 /* Undo any frames written (but not committed) to the log */
36766 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
36767
36768 /* Return an integer that records the current (uncommitted) write
36769 ** position in the WAL */
36770 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
36771
36772 /* Move the write position of the WAL back to iFrame.  Called in
36773 ** response to a ROLLBACK TO command. */
36774 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
36775
36776 /* Write a frame or frames to the log. */
36777 SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
36778
36779 /* Copy pages from the log to the database file */ 
36780 SQLITE_PRIVATE int sqlite3WalCheckpoint(
36781   Wal *pWal,                      /* Write-ahead log connection */
36782   int eMode,                      /* One of PASSIVE, FULL and RESTART */
36783   int (*xBusy)(void*),            /* Function to call when busy */
36784   void *pBusyArg,                 /* Context argument for xBusyHandler */
36785   int sync_flags,                 /* Flags to sync db file with (or 0) */
36786   int nBuf,                       /* Size of buffer nBuf */
36787   u8 *zBuf,                       /* Temporary buffer to use */
36788   int *pnLog,                     /* OUT: Number of frames in WAL */
36789   int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
36790 );
36791
36792 /* Return the value to pass to a sqlite3_wal_hook callback, the
36793 ** number of frames in the WAL at the point of the last commit since
36794 ** sqlite3WalCallback() was called.  If no commits have occurred since
36795 ** the last call, then return 0.
36796 */
36797 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
36798
36799 /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
36800 ** by the pager layer on the database file.
36801 */
36802 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
36803
36804 /* Return true if the argument is non-NULL and the WAL module is using
36805 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
36806 ** WAL module is using shared-memory, return false. 
36807 */
36808 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
36809
36810 #endif /* ifndef SQLITE_OMIT_WAL */
36811 #endif /* _WAL_H_ */
36812
36813 /************** End of wal.h *************************************************/
36814 /************** Continuing where we left off in pager.c **********************/
36815
36816
36817 /******************* NOTES ON THE DESIGN OF THE PAGER ************************
36818 **
36819 ** This comment block describes invariants that hold when using a rollback
36820 ** journal.  These invariants do not apply for journal_mode=WAL,
36821 ** journal_mode=MEMORY, or journal_mode=OFF.
36822 **
36823 ** Within this comment block, a page is deemed to have been synced
36824 ** automatically as soon as it is written when PRAGMA synchronous=OFF.
36825 ** Otherwise, the page is not synced until the xSync method of the VFS
36826 ** is called successfully on the file containing the page.
36827 **
36828 ** Definition:  A page of the database file is said to be "overwriteable" if
36829 ** one or more of the following are true about the page:
36830 ** 
36831 **     (a)  The original content of the page as it was at the beginning of
36832 **          the transaction has been written into the rollback journal and
36833 **          synced.
36834 ** 
36835 **     (b)  The page was a freelist leaf page at the start of the transaction.
36836 ** 
36837 **     (c)  The page number is greater than the largest page that existed in
36838 **          the database file at the start of the transaction.
36839 ** 
36840 ** (1) A page of the database file is never overwritten unless one of the
36841 **     following are true:
36842 ** 
36843 **     (a) The page and all other pages on the same sector are overwriteable.
36844 ** 
36845 **     (b) The atomic page write optimization is enabled, and the entire
36846 **         transaction other than the update of the transaction sequence
36847 **         number consists of a single page change.
36848 ** 
36849 ** (2) The content of a page written into the rollback journal exactly matches
36850 **     both the content in the database when the rollback journal was written
36851 **     and the content in the database at the beginning of the current
36852 **     transaction.
36853 ** 
36854 ** (3) Writes to the database file are an integer multiple of the page size
36855 **     in length and are aligned on a page boundary.
36856 ** 
36857 ** (4) Reads from the database file are either aligned on a page boundary and
36858 **     an integer multiple of the page size in length or are taken from the
36859 **     first 100 bytes of the database file.
36860 ** 
36861 ** (5) All writes to the database file are synced prior to the rollback journal
36862 **     being deleted, truncated, or zeroed.
36863 ** 
36864 ** (6) If a master journal file is used, then all writes to the database file
36865 **     are synced prior to the master journal being deleted.
36866 ** 
36867 ** Definition: Two databases (or the same database at two points it time)
36868 ** are said to be "logically equivalent" if they give the same answer to
36869 ** all queries.  Note in particular the the content of freelist leaf
36870 ** pages can be changed arbitarily without effecting the logical equivalence
36871 ** of the database.
36872 ** 
36873 ** (7) At any time, if any subset, including the empty set and the total set,
36874 **     of the unsynced changes to a rollback journal are removed and the 
36875 **     journal is rolled back, the resulting database file will be logical
36876 **     equivalent to the database file at the beginning of the transaction.
36877 ** 
36878 ** (8) When a transaction is rolled back, the xTruncate method of the VFS
36879 **     is called to restore the database file to the same size it was at
36880 **     the beginning of the transaction.  (In some VFSes, the xTruncate
36881 **     method is a no-op, but that does not change the fact the SQLite will
36882 **     invoke it.)
36883 ** 
36884 ** (9) Whenever the database file is modified, at least one bit in the range
36885 **     of bytes from 24 through 39 inclusive will be changed prior to releasing
36886 **     the EXCLUSIVE lock, thus signaling other connections on the same
36887 **     database to flush their caches.
36888 **
36889 ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
36890 **      than one billion transactions.
36891 **
36892 ** (11) A database file is well-formed at the beginning and at the conclusion
36893 **      of every transaction.
36894 **
36895 ** (12) An EXCLUSIVE lock is held on the database file when writing to
36896 **      the database file.
36897 **
36898 ** (13) A SHARED lock is held on the database file while reading any
36899 **      content out of the database file.
36900 **
36901 ******************************************************************************/
36902
36903 /*
36904 ** Macros for troubleshooting.  Normally turned off
36905 */
36906 #if 0
36907 int sqlite3PagerTrace=1;  /* True to enable tracing */
36908 #define sqlite3DebugPrintf printf
36909 #define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
36910 #else
36911 #define PAGERTRACE(X)
36912 #endif
36913
36914 /*
36915 ** The following two macros are used within the PAGERTRACE() macros above
36916 ** to print out file-descriptors. 
36917 **
36918 ** PAGERID() takes a pointer to a Pager struct as its argument. The
36919 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
36920 ** struct as its argument.
36921 */
36922 #define PAGERID(p) ((int)(p->fd))
36923 #define FILEHANDLEID(fd) ((int)fd)
36924
36925 /*
36926 ** The Pager.eState variable stores the current 'state' of a pager. A
36927 ** pager may be in any one of the seven states shown in the following
36928 ** state diagram.
36929 **
36930 **                            OPEN <------+------+
36931 **                              |         |      |
36932 **                              V         |      |
36933 **               +---------> READER-------+      |
36934 **               |              |                |
36935 **               |              V                |
36936 **               |<-------WRITER_LOCKED------> ERROR
36937 **               |              |                ^  
36938 **               |              V                |
36939 **               |<------WRITER_CACHEMOD-------->|
36940 **               |              |                |
36941 **               |              V                |
36942 **               |<-------WRITER_DBMOD---------->|
36943 **               |              |                |
36944 **               |              V                |
36945 **               +<------WRITER_FINISHED-------->+
36946 **
36947 **
36948 ** List of state transitions and the C [function] that performs each:
36949 ** 
36950 **   OPEN              -> READER              [sqlite3PagerSharedLock]
36951 **   READER            -> OPEN                [pager_unlock]
36952 **
36953 **   READER            -> WRITER_LOCKED       [sqlite3PagerBegin]
36954 **   WRITER_LOCKED     -> WRITER_CACHEMOD     [pager_open_journal]
36955 **   WRITER_CACHEMOD   -> WRITER_DBMOD        [syncJournal]
36956 **   WRITER_DBMOD      -> WRITER_FINISHED     [sqlite3PagerCommitPhaseOne]
36957 **   WRITER_***        -> READER              [pager_end_transaction]
36958 **
36959 **   WRITER_***        -> ERROR               [pager_error]
36960 **   ERROR             -> OPEN                [pager_unlock]
36961 ** 
36962 **
36963 **  OPEN:
36964 **
36965 **    The pager starts up in this state. Nothing is guaranteed in this
36966 **    state - the file may or may not be locked and the database size is
36967 **    unknown. The database may not be read or written.
36968 **
36969 **    * No read or write transaction is active.
36970 **    * Any lock, or no lock at all, may be held on the database file.
36971 **    * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
36972 **
36973 **  READER:
36974 **
36975 **    In this state all the requirements for reading the database in 
36976 **    rollback (non-WAL) mode are met. Unless the pager is (or recently
36977 **    was) in exclusive-locking mode, a user-level read transaction is 
36978 **    open. The database size is known in this state.
36979 **
36980 **    A connection running with locking_mode=normal enters this state when
36981 **    it opens a read-transaction on the database and returns to state
36982 **    OPEN after the read-transaction is completed. However a connection
36983 **    running in locking_mode=exclusive (including temp databases) remains in
36984 **    this state even after the read-transaction is closed. The only way
36985 **    a locking_mode=exclusive connection can transition from READER to OPEN
36986 **    is via the ERROR state (see below).
36987 ** 
36988 **    * A read transaction may be active (but a write-transaction cannot).
36989 **    * A SHARED or greater lock is held on the database file.
36990 **    * The dbSize variable may be trusted (even if a user-level read 
36991 **      transaction is not active). The dbOrigSize and dbFileSize variables
36992 **      may not be trusted at this point.
36993 **    * If the database is a WAL database, then the WAL connection is open.
36994 **    * Even if a read-transaction is not open, it is guaranteed that 
36995 **      there is no hot-journal in the file-system.
36996 **
36997 **  WRITER_LOCKED:
36998 **
36999 **    The pager moves to this state from READER when a write-transaction
37000 **    is first opened on the database. In WRITER_LOCKED state, all locks 
37001 **    required to start a write-transaction are held, but no actual 
37002 **    modifications to the cache or database have taken place.
37003 **
37004 **    In rollback mode, a RESERVED or (if the transaction was opened with 
37005 **    BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
37006 **    moving to this state, but the journal file is not written to or opened 
37007 **    to in this state. If the transaction is committed or rolled back while 
37008 **    in WRITER_LOCKED state, all that is required is to unlock the database 
37009 **    file.
37010 **
37011 **    IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
37012 **    If the connection is running with locking_mode=exclusive, an attempt
37013 **    is made to obtain an EXCLUSIVE lock on the database file.
37014 **
37015 **    * A write transaction is active.
37016 **    * If the connection is open in rollback-mode, a RESERVED or greater 
37017 **      lock is held on the database file.
37018 **    * If the connection is open in WAL-mode, a WAL write transaction
37019 **      is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
37020 **      called).
37021 **    * The dbSize, dbOrigSize and dbFileSize variables are all valid.
37022 **    * The contents of the pager cache have not been modified.
37023 **    * The journal file may or may not be open.
37024 **    * Nothing (not even the first header) has been written to the journal.
37025 **
37026 **  WRITER_CACHEMOD:
37027 **
37028 **    A pager moves from WRITER_LOCKED state to this state when a page is
37029 **    first modified by the upper layer. In rollback mode the journal file
37030 **    is opened (if it is not already open) and a header written to the
37031 **    start of it. The database file on disk has not been modified.
37032 **
37033 **    * A write transaction is active.
37034 **    * A RESERVED or greater lock is held on the database file.
37035 **    * The journal file is open and the first header has been written 
37036 **      to it, but the header has not been synced to disk.
37037 **    * The contents of the page cache have been modified.
37038 **
37039 **  WRITER_DBMOD:
37040 **
37041 **    The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
37042 **    when it modifies the contents of the database file. WAL connections
37043 **    never enter this state (since they do not modify the database file,
37044 **    just the log file).
37045 **
37046 **    * A write transaction is active.
37047 **    * An EXCLUSIVE or greater lock is held on the database file.
37048 **    * The journal file is open and the first header has been written 
37049 **      and synced to disk.
37050 **    * The contents of the page cache have been modified (and possibly
37051 **      written to disk).
37052 **
37053 **  WRITER_FINISHED:
37054 **
37055 **    It is not possible for a WAL connection to enter this state.
37056 **
37057 **    A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
37058 **    state after the entire transaction has been successfully written into the
37059 **    database file. In this state the transaction may be committed simply
37060 **    by finalizing the journal file. Once in WRITER_FINISHED state, it is 
37061 **    not possible to modify the database further. At this point, the upper 
37062 **    layer must either commit or rollback the transaction.
37063 **
37064 **    * A write transaction is active.
37065 **    * An EXCLUSIVE or greater lock is held on the database file.
37066 **    * All writing and syncing of journal and database data has finished.
37067 **      If no error occured, all that remains is to finalize the journal to
37068 **      commit the transaction. If an error did occur, the caller will need
37069 **      to rollback the transaction. 
37070 **
37071 **  ERROR:
37072 **
37073 **    The ERROR state is entered when an IO or disk-full error (including
37074 **    SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it 
37075 **    difficult to be sure that the in-memory pager state (cache contents, 
37076 **    db size etc.) are consistent with the contents of the file-system.
37077 **
37078 **    Temporary pager files may enter the ERROR state, but in-memory pagers
37079 **    cannot.
37080 **
37081 **    For example, if an IO error occurs while performing a rollback, 
37082 **    the contents of the page-cache may be left in an inconsistent state.
37083 **    At this point it would be dangerous to change back to READER state
37084 **    (as usually happens after a rollback). Any subsequent readers might
37085 **    report database corruption (due to the inconsistent cache), and if
37086 **    they upgrade to writers, they may inadvertently corrupt the database
37087 **    file. To avoid this hazard, the pager switches into the ERROR state
37088 **    instead of READER following such an error.
37089 **
37090 **    Once it has entered the ERROR state, any attempt to use the pager
37091 **    to read or write data returns an error. Eventually, once all 
37092 **    outstanding transactions have been abandoned, the pager is able to
37093 **    transition back to OPEN state, discarding the contents of the 
37094 **    page-cache and any other in-memory state at the same time. Everything
37095 **    is reloaded from disk (and, if necessary, hot-journal rollback peformed)
37096 **    when a read-transaction is next opened on the pager (transitioning
37097 **    the pager into READER state). At that point the system has recovered 
37098 **    from the error.
37099 **
37100 **    Specifically, the pager jumps into the ERROR state if:
37101 **
37102 **      1. An error occurs while attempting a rollback. This happens in
37103 **         function sqlite3PagerRollback().
37104 **
37105 **      2. An error occurs while attempting to finalize a journal file
37106 **         following a commit in function sqlite3PagerCommitPhaseTwo().
37107 **
37108 **      3. An error occurs while attempting to write to the journal or
37109 **         database file in function pagerStress() in order to free up
37110 **         memory.
37111 **
37112 **    In other cases, the error is returned to the b-tree layer. The b-tree
37113 **    layer then attempts a rollback operation. If the error condition 
37114 **    persists, the pager enters the ERROR state via condition (1) above.
37115 **
37116 **    Condition (3) is necessary because it can be triggered by a read-only
37117 **    statement executed within a transaction. In this case, if the error
37118 **    code were simply returned to the user, the b-tree layer would not
37119 **    automatically attempt a rollback, as it assumes that an error in a
37120 **    read-only statement cannot leave the pager in an internally inconsistent 
37121 **    state.
37122 **
37123 **    * The Pager.errCode variable is set to something other than SQLITE_OK.
37124 **    * There are one or more outstanding references to pages (after the
37125 **      last reference is dropped the pager should move back to OPEN state).
37126 **    * The pager is not an in-memory pager.
37127 **    
37128 **
37129 ** Notes:
37130 **
37131 **   * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
37132 **     connection is open in WAL mode. A WAL connection is always in one
37133 **     of the first four states.
37134 **
37135 **   * Normally, a connection open in exclusive mode is never in PAGER_OPEN
37136 **     state. There are two exceptions: immediately after exclusive-mode has
37137 **     been turned on (and before any read or write transactions are 
37138 **     executed), and when the pager is leaving the "error state".
37139 **
37140 **   * See also: assert_pager_state().
37141 */
37142 #define PAGER_OPEN                  0
37143 #define PAGER_READER                1
37144 #define PAGER_WRITER_LOCKED         2
37145 #define PAGER_WRITER_CACHEMOD       3
37146 #define PAGER_WRITER_DBMOD          4
37147 #define PAGER_WRITER_FINISHED       5
37148 #define PAGER_ERROR                 6
37149
37150 /*
37151 ** The Pager.eLock variable is almost always set to one of the 
37152 ** following locking-states, according to the lock currently held on
37153 ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
37154 ** This variable is kept up to date as locks are taken and released by
37155 ** the pagerLockDb() and pagerUnlockDb() wrappers.
37156 **
37157 ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
37158 ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
37159 ** the operation was successful. In these circumstances pagerLockDb() and
37160 ** pagerUnlockDb() take a conservative approach - eLock is always updated
37161 ** when unlocking the file, and only updated when locking the file if the
37162 ** VFS call is successful. This way, the Pager.eLock variable may be set
37163 ** to a less exclusive (lower) value than the lock that is actually held
37164 ** at the system level, but it is never set to a more exclusive value.
37165 **
37166 ** This is usually safe. If an xUnlock fails or appears to fail, there may 
37167 ** be a few redundant xLock() calls or a lock may be held for longer than
37168 ** required, but nothing really goes wrong.
37169 **
37170 ** The exception is when the database file is unlocked as the pager moves
37171 ** from ERROR to OPEN state. At this point there may be a hot-journal file 
37172 ** in the file-system that needs to be rolled back (as part of a OPEN->SHARED
37173 ** transition, by the same pager or any other). If the call to xUnlock()
37174 ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
37175 ** can confuse the call to xCheckReservedLock() call made later as part
37176 ** of hot-journal detection.
37177 **
37178 ** xCheckReservedLock() is defined as returning true "if there is a RESERVED 
37179 ** lock held by this process or any others". So xCheckReservedLock may 
37180 ** return true because the caller itself is holding an EXCLUSIVE lock (but
37181 ** doesn't know it because of a previous error in xUnlock). If this happens
37182 ** a hot-journal may be mistaken for a journal being created by an active
37183 ** transaction in another process, causing SQLite to read from the database
37184 ** without rolling it back.
37185 **
37186 ** To work around this, if a call to xUnlock() fails when unlocking the
37187 ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
37188 ** is only changed back to a real locking state after a successful call
37189 ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
37190 ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK 
37191 ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
37192 ** lock on the database file before attempting to roll it back. See function
37193 ** PagerSharedLock() for more detail.
37194 **
37195 ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in 
37196 ** PAGER_OPEN state.
37197 */
37198 #define UNKNOWN_LOCK                (EXCLUSIVE_LOCK+1)
37199
37200 /*
37201 ** A macro used for invoking the codec if there is one
37202 */
37203 #ifdef SQLITE_HAS_CODEC
37204 # define CODEC1(P,D,N,X,E) \
37205     if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
37206 # define CODEC2(P,D,N,X,E,O) \
37207     if( P->xCodec==0 ){ O=(char*)D; }else \
37208     if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
37209 #else
37210 # define CODEC1(P,D,N,X,E)   /* NO-OP */
37211 # define CODEC2(P,D,N,X,E,O) O=(char*)D
37212 #endif
37213
37214 /*
37215 ** The maximum allowed sector size. 64KiB. If the xSectorsize() method 
37216 ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
37217 ** This could conceivably cause corruption following a power failure on
37218 ** such a system. This is currently an undocumented limit.
37219 */
37220 #define MAX_SECTOR_SIZE 0x10000
37221
37222 /*
37223 ** An instance of the following structure is allocated for each active
37224 ** savepoint and statement transaction in the system. All such structures
37225 ** are stored in the Pager.aSavepoint[] array, which is allocated and
37226 ** resized using sqlite3Realloc().
37227 **
37228 ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
37229 ** set to 0. If a journal-header is written into the main journal while
37230 ** the savepoint is active, then iHdrOffset is set to the byte offset 
37231 ** immediately following the last journal record written into the main
37232 ** journal before the journal-header. This is required during savepoint
37233 ** rollback (see pagerPlaybackSavepoint()).
37234 */
37235 typedef struct PagerSavepoint PagerSavepoint;
37236 struct PagerSavepoint {
37237   i64 iOffset;                 /* Starting offset in main journal */
37238   i64 iHdrOffset;              /* See above */
37239   Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
37240   Pgno nOrig;                  /* Original number of pages in file */
37241   Pgno iSubRec;                /* Index of first record in sub-journal */
37242 #ifndef SQLITE_OMIT_WAL
37243   u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */
37244 #endif
37245 };
37246
37247 /*
37248 ** A open page cache is an instance of struct Pager. A description of
37249 ** some of the more important member variables follows:
37250 **
37251 ** eState
37252 **
37253 **   The current 'state' of the pager object. See the comment and state
37254 **   diagram above for a description of the pager state.
37255 **
37256 ** eLock
37257 **
37258 **   For a real on-disk database, the current lock held on the database file -
37259 **   NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
37260 **
37261 **   For a temporary or in-memory database (neither of which require any
37262 **   locks), this variable is always set to EXCLUSIVE_LOCK. Since such
37263 **   databases always have Pager.exclusiveMode==1, this tricks the pager
37264 **   logic into thinking that it already has all the locks it will ever
37265 **   need (and no reason to release them).
37266 **
37267 **   In some (obscure) circumstances, this variable may also be set to
37268 **   UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
37269 **   details.
37270 **
37271 ** changeCountDone
37272 **
37273 **   This boolean variable is used to make sure that the change-counter 
37274 **   (the 4-byte header field at byte offset 24 of the database file) is 
37275 **   not updated more often than necessary. 
37276 **
37277 **   It is set to true when the change-counter field is updated, which 
37278 **   can only happen if an exclusive lock is held on the database file.
37279 **   It is cleared (set to false) whenever an exclusive lock is 
37280 **   relinquished on the database file. Each time a transaction is committed,
37281 **   The changeCountDone flag is inspected. If it is true, the work of
37282 **   updating the change-counter is omitted for the current transaction.
37283 **
37284 **   This mechanism means that when running in exclusive mode, a connection 
37285 **   need only update the change-counter once, for the first transaction
37286 **   committed.
37287 **
37288 ** setMaster
37289 **
37290 **   When PagerCommitPhaseOne() is called to commit a transaction, it may
37291 **   (or may not) specify a master-journal name to be written into the 
37292 **   journal file before it is synced to disk.
37293 **
37294 **   Whether or not a journal file contains a master-journal pointer affects 
37295 **   the way in which the journal file is finalized after the transaction is 
37296 **   committed or rolled back when running in "journal_mode=PERSIST" mode.
37297 **   If a journal file does not contain a master-journal pointer, it is
37298 **   finalized by overwriting the first journal header with zeroes. If
37299 **   it does contain a master-journal pointer the journal file is finalized 
37300 **   by truncating it to zero bytes, just as if the connection were 
37301 **   running in "journal_mode=truncate" mode.
37302 **
37303 **   Journal files that contain master journal pointers cannot be finalized
37304 **   simply by overwriting the first journal-header with zeroes, as the
37305 **   master journal pointer could interfere with hot-journal rollback of any
37306 **   subsequently interrupted transaction that reuses the journal file.
37307 **
37308 **   The flag is cleared as soon as the journal file is finalized (either
37309 **   by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
37310 **   journal file from being successfully finalized, the setMaster flag
37311 **   is cleared anyway (and the pager will move to ERROR state).
37312 **
37313 ** doNotSpill, doNotSyncSpill
37314 **
37315 **   These two boolean variables control the behaviour of cache-spills
37316 **   (calls made by the pcache module to the pagerStress() routine to
37317 **   write cached data to the file-system in order to free up memory).
37318 **
37319 **   When doNotSpill is non-zero, writing to the database from pagerStress()
37320 **   is disabled altogether. This is done in a very obscure case that
37321 **   comes up during savepoint rollback that requires the pcache module
37322 **   to allocate a new page to prevent the journal file from being written
37323 **   while it is being traversed by code in pager_playback().
37324 ** 
37325 **   If doNotSyncSpill is non-zero, writing to the database from pagerStress()
37326 **   is permitted, but syncing the journal file is not. This flag is set
37327 **   by sqlite3PagerWrite() when the file-system sector-size is larger than
37328 **   the database page-size in order to prevent a journal sync from happening 
37329 **   in between the journalling of two pages on the same sector. 
37330 **
37331 ** subjInMemory
37332 **
37333 **   This is a boolean variable. If true, then any required sub-journal
37334 **   is opened as an in-memory journal file. If false, then in-memory
37335 **   sub-journals are only used for in-memory pager files.
37336 **
37337 **   This variable is updated by the upper layer each time a new 
37338 **   write-transaction is opened.
37339 **
37340 ** dbSize, dbOrigSize, dbFileSize
37341 **
37342 **   Variable dbSize is set to the number of pages in the database file.
37343 **   It is valid in PAGER_READER and higher states (all states except for
37344 **   OPEN and ERROR). 
37345 **
37346 **   dbSize is set based on the size of the database file, which may be 
37347 **   larger than the size of the database (the value stored at offset
37348 **   28 of the database header by the btree). If the size of the file
37349 **   is not an integer multiple of the page-size, the value stored in
37350 **   dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
37351 **   Except, any file that is greater than 0 bytes in size is considered
37352 **   to have at least one page. (i.e. a 1KB file with 2K page-size leads
37353 **   to dbSize==1).
37354 **
37355 **   During a write-transaction, if pages with page-numbers greater than
37356 **   dbSize are modified in the cache, dbSize is updated accordingly.
37357 **   Similarly, if the database is truncated using PagerTruncateImage(), 
37358 **   dbSize is updated.
37359 **
37360 **   Variables dbOrigSize and dbFileSize are valid in states 
37361 **   PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
37362 **   variable at the start of the transaction. It is used during rollback,
37363 **   and to determine whether or not pages need to be journalled before
37364 **   being modified.
37365 **
37366 **   Throughout a write-transaction, dbFileSize contains the size of
37367 **   the file on disk in pages. It is set to a copy of dbSize when the
37368 **   write-transaction is first opened, and updated when VFS calls are made
37369 **   to write or truncate the database file on disk. 
37370 **
37371 **   The only reason the dbFileSize variable is required is to suppress 
37372 **   unnecessary calls to xTruncate() after committing a transaction. If, 
37373 **   when a transaction is committed, the dbFileSize variable indicates 
37374 **   that the database file is larger than the database image (Pager.dbSize), 
37375 **   pager_truncate() is called. The pager_truncate() call uses xFilesize()
37376 **   to measure the database file on disk, and then truncates it if required.
37377 **   dbFileSize is not used when rolling back a transaction. In this case
37378 **   pager_truncate() is called unconditionally (which means there may be
37379 **   a call to xFilesize() that is not strictly required). In either case,
37380 **   pager_truncate() may cause the file to become smaller or larger.
37381 **
37382 ** dbHintSize
37383 **
37384 **   The dbHintSize variable is used to limit the number of calls made to
37385 **   the VFS xFileControl(FCNTL_SIZE_HINT) method. 
37386 **
37387 **   dbHintSize is set to a copy of the dbSize variable when a
37388 **   write-transaction is opened (at the same time as dbFileSize and
37389 **   dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
37390 **   dbHintSize is increased to the number of pages that correspond to the
37391 **   size-hint passed to the method call. See pager_write_pagelist() for 
37392 **   details.
37393 **
37394 ** errCode
37395 **
37396 **   The Pager.errCode variable is only ever used in PAGER_ERROR state. It
37397 **   is set to zero in all other states. In PAGER_ERROR state, Pager.errCode 
37398 **   is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX 
37399 **   sub-codes.
37400 */
37401 struct Pager {
37402   sqlite3_vfs *pVfs;          /* OS functions to use for IO */
37403   u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
37404   u8 journalMode;             /* One of the PAGER_JOURNALMODE_* values */
37405   u8 useJournal;              /* Use a rollback journal on this file */
37406   u8 noReadlock;              /* Do not bother to obtain readlocks */
37407   u8 noSync;                  /* Do not sync the journal if true */
37408   u8 fullSync;                /* Do extra syncs of the journal for robustness */
37409   u8 ckptSyncFlags;           /* SYNC_NORMAL or SYNC_FULL for checkpoint */
37410   u8 syncFlags;               /* SYNC_NORMAL or SYNC_FULL otherwise */
37411   u8 tempFile;                /* zFilename is a temporary file */
37412   u8 readOnly;                /* True for a read-only database */
37413   u8 memDb;                   /* True to inhibit all file I/O */
37414
37415   /**************************************************************************
37416   ** The following block contains those class members that change during
37417   ** routine opertion.  Class members not in this block are either fixed
37418   ** when the pager is first created or else only change when there is a
37419   ** significant mode change (such as changing the page_size, locking_mode,
37420   ** or the journal_mode).  From another view, these class members describe
37421   ** the "state" of the pager, while other class members describe the
37422   ** "configuration" of the pager.
37423   */
37424   u8 eState;                  /* Pager state (OPEN, READER, WRITER_LOCKED..) */
37425   u8 eLock;                   /* Current lock held on database file */
37426   u8 changeCountDone;         /* Set after incrementing the change-counter */
37427   u8 setMaster;               /* True if a m-j name has been written to jrnl */
37428   u8 doNotSpill;              /* Do not spill the cache when non-zero */
37429   u8 doNotSyncSpill;          /* Do not do a spill that requires jrnl sync */
37430   u8 subjInMemory;            /* True to use in-memory sub-journals */
37431   Pgno dbSize;                /* Number of pages in the database */
37432   Pgno dbOrigSize;            /* dbSize before the current transaction */
37433   Pgno dbFileSize;            /* Number of pages in the database file */
37434   Pgno dbHintSize;            /* Value passed to FCNTL_SIZE_HINT call */
37435   int errCode;                /* One of several kinds of errors */
37436   int nRec;                   /* Pages journalled since last j-header written */
37437   u32 cksumInit;              /* Quasi-random value added to every checksum */
37438   u32 nSubRec;                /* Number of records written to sub-journal */
37439   Bitvec *pInJournal;         /* One bit for each page in the database file */
37440   sqlite3_file *fd;           /* File descriptor for database */
37441   sqlite3_file *jfd;          /* File descriptor for main journal */
37442   sqlite3_file *sjfd;         /* File descriptor for sub-journal */
37443   i64 journalOff;             /* Current write offset in the journal file */
37444   i64 journalHdr;             /* Byte offset to previous journal header */
37445   sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
37446   PagerSavepoint *aSavepoint; /* Array of active savepoints */
37447   int nSavepoint;             /* Number of elements in aSavepoint[] */
37448   char dbFileVers[16];        /* Changes whenever database file changes */
37449   /*
37450   ** End of the routinely-changing class members
37451   ***************************************************************************/
37452
37453   u16 nExtra;                 /* Add this many bytes to each in-memory page */
37454   i16 nReserve;               /* Number of unused bytes at end of each page */
37455   u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
37456   u32 sectorSize;             /* Assumed sector size during rollback */
37457   int pageSize;               /* Number of bytes in a page */
37458   Pgno mxPgno;                /* Maximum allowed size of the database */
37459   i64 journalSizeLimit;       /* Size limit for persistent journal files */
37460   char *zFilename;            /* Name of the database file */
37461   char *zJournal;             /* Name of the journal file */
37462   int (*xBusyHandler)(void*); /* Function to call when busy */
37463   void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
37464 #ifdef SQLITE_TEST
37465   int nHit, nMiss;            /* Cache hits and missing */
37466   int nRead, nWrite;          /* Database pages read/written */
37467 #endif
37468   void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
37469 #ifdef SQLITE_HAS_CODEC
37470   void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
37471   void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
37472   void (*xCodecFree)(void*);             /* Destructor for the codec */
37473   void *pCodec;               /* First argument to xCodec... methods */
37474 #endif
37475   char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
37476   PCache *pPCache;            /* Pointer to page cache object */
37477 #ifndef SQLITE_OMIT_WAL
37478   Wal *pWal;                  /* Write-ahead log used by "journal_mode=wal" */
37479   char *zWal;                 /* File name for write-ahead log */
37480 #endif
37481 };
37482
37483 /*
37484 ** The following global variables hold counters used for
37485 ** testing purposes only.  These variables do not exist in
37486 ** a non-testing build.  These variables are not thread-safe.
37487 */
37488 #ifdef SQLITE_TEST
37489 SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
37490 SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
37491 SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
37492 # define PAGER_INCR(v)  v++
37493 #else
37494 # define PAGER_INCR(v)
37495 #endif
37496
37497
37498
37499 /*
37500 ** Journal files begin with the following magic string.  The data
37501 ** was obtained from /dev/random.  It is used only as a sanity check.
37502 **
37503 ** Since version 2.8.0, the journal format contains additional sanity
37504 ** checking information.  If the power fails while the journal is being
37505 ** written, semi-random garbage data might appear in the journal
37506 ** file after power is restored.  If an attempt is then made
37507 ** to roll the journal back, the database could be corrupted.  The additional
37508 ** sanity checking data is an attempt to discover the garbage in the
37509 ** journal and ignore it.
37510 **
37511 ** The sanity checking information for the new journal format consists
37512 ** of a 32-bit checksum on each page of data.  The checksum covers both
37513 ** the page number and the pPager->pageSize bytes of data for the page.
37514 ** This cksum is initialized to a 32-bit random value that appears in the
37515 ** journal file right after the header.  The random initializer is important,
37516 ** because garbage data that appears at the end of a journal is likely
37517 ** data that was once in other files that have now been deleted.  If the
37518 ** garbage data came from an obsolete journal file, the checksums might
37519 ** be correct.  But by initializing the checksum to random value which
37520 ** is different for every journal, we minimize that risk.
37521 */
37522 static const unsigned char aJournalMagic[] = {
37523   0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
37524 };
37525
37526 /*
37527 ** The size of the of each page record in the journal is given by
37528 ** the following macro.
37529 */
37530 #define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
37531
37532 /*
37533 ** The journal header size for this pager. This is usually the same 
37534 ** size as a single disk sector. See also setSectorSize().
37535 */
37536 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
37537
37538 /*
37539 ** The macro MEMDB is true if we are dealing with an in-memory database.
37540 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
37541 ** the value of MEMDB will be a constant and the compiler will optimize
37542 ** out code that would never execute.
37543 */
37544 #ifdef SQLITE_OMIT_MEMORYDB
37545 # define MEMDB 0
37546 #else
37547 # define MEMDB pPager->memDb
37548 #endif
37549
37550 /*
37551 ** The maximum legal page number is (2^31 - 1).
37552 */
37553 #define PAGER_MAX_PGNO 2147483647
37554
37555 /*
37556 ** The argument to this macro is a file descriptor (type sqlite3_file*).
37557 ** Return 0 if it is not open, or non-zero (but not 1) if it is.
37558 **
37559 ** This is so that expressions can be written as:
37560 **
37561 **   if( isOpen(pPager->jfd) ){ ...
37562 **
37563 ** instead of
37564 **
37565 **   if( pPager->jfd->pMethods ){ ...
37566 */
37567 #define isOpen(pFd) ((pFd)->pMethods)
37568
37569 /*
37570 ** Return true if this pager uses a write-ahead log instead of the usual
37571 ** rollback journal. Otherwise false.
37572 */
37573 #ifndef SQLITE_OMIT_WAL
37574 static int pagerUseWal(Pager *pPager){
37575   return (pPager->pWal!=0);
37576 }
37577 #else
37578 # define pagerUseWal(x) 0
37579 # define pagerRollbackWal(x) 0
37580 # define pagerWalFrames(v,w,x,y,z) 0
37581 # define pagerOpenWalIfPresent(z) SQLITE_OK
37582 # define pagerBeginReadTransaction(z) SQLITE_OK
37583 #endif
37584
37585 #ifndef NDEBUG 
37586 /*
37587 ** Usage:
37588 **
37589 **   assert( assert_pager_state(pPager) );
37590 **
37591 ** This function runs many asserts to try to find inconsistencies in
37592 ** the internal state of the Pager object.
37593 */
37594 static int assert_pager_state(Pager *p){
37595   Pager *pPager = p;
37596
37597   /* State must be valid. */
37598   assert( p->eState==PAGER_OPEN
37599        || p->eState==PAGER_READER
37600        || p->eState==PAGER_WRITER_LOCKED
37601        || p->eState==PAGER_WRITER_CACHEMOD
37602        || p->eState==PAGER_WRITER_DBMOD
37603        || p->eState==PAGER_WRITER_FINISHED
37604        || p->eState==PAGER_ERROR
37605   );
37606
37607   /* Regardless of the current state, a temp-file connection always behaves
37608   ** as if it has an exclusive lock on the database file. It never updates
37609   ** the change-counter field, so the changeCountDone flag is always set.
37610   */
37611   assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
37612   assert( p->tempFile==0 || pPager->changeCountDone );
37613
37614   /* If the useJournal flag is clear, the journal-mode must be "OFF". 
37615   ** And if the journal-mode is "OFF", the journal file must not be open.
37616   */
37617   assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
37618   assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
37619
37620   /* Check that MEMDB implies noSync. And an in-memory journal. Since 
37621   ** this means an in-memory pager performs no IO at all, it cannot encounter 
37622   ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing 
37623   ** a journal file. (although the in-memory journal implementation may 
37624   ** return SQLITE_IOERR_NOMEM while the journal file is being written). It 
37625   ** is therefore not possible for an in-memory pager to enter the ERROR 
37626   ** state.
37627   */
37628   if( MEMDB ){
37629     assert( p->noSync );
37630     assert( p->journalMode==PAGER_JOURNALMODE_OFF 
37631          || p->journalMode==PAGER_JOURNALMODE_MEMORY 
37632     );
37633     assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
37634     assert( pagerUseWal(p)==0 );
37635   }
37636
37637   /* If changeCountDone is set, a RESERVED lock or greater must be held
37638   ** on the file.
37639   */
37640   assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
37641   assert( p->eLock!=PENDING_LOCK );
37642
37643   switch( p->eState ){
37644     case PAGER_OPEN:
37645       assert( !MEMDB );
37646       assert( pPager->errCode==SQLITE_OK );
37647       assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
37648       break;
37649
37650     case PAGER_READER:
37651       assert( pPager->errCode==SQLITE_OK );
37652       assert( p->eLock!=UNKNOWN_LOCK );
37653       assert( p->eLock>=SHARED_LOCK || p->noReadlock );
37654       break;
37655
37656     case PAGER_WRITER_LOCKED:
37657       assert( p->eLock!=UNKNOWN_LOCK );
37658       assert( pPager->errCode==SQLITE_OK );
37659       if( !pagerUseWal(pPager) ){
37660         assert( p->eLock>=RESERVED_LOCK );
37661       }
37662       assert( pPager->dbSize==pPager->dbOrigSize );
37663       assert( pPager->dbOrigSize==pPager->dbFileSize );
37664       assert( pPager->dbOrigSize==pPager->dbHintSize );
37665       assert( pPager->setMaster==0 );
37666       break;
37667
37668     case PAGER_WRITER_CACHEMOD:
37669       assert( p->eLock!=UNKNOWN_LOCK );
37670       assert( pPager->errCode==SQLITE_OK );
37671       if( !pagerUseWal(pPager) ){
37672         /* It is possible that if journal_mode=wal here that neither the
37673         ** journal file nor the WAL file are open. This happens during
37674         ** a rollback transaction that switches from journal_mode=off
37675         ** to journal_mode=wal.
37676         */
37677         assert( p->eLock>=RESERVED_LOCK );
37678         assert( isOpen(p->jfd) 
37679              || p->journalMode==PAGER_JOURNALMODE_OFF 
37680              || p->journalMode==PAGER_JOURNALMODE_WAL 
37681         );
37682       }
37683       assert( pPager->dbOrigSize==pPager->dbFileSize );
37684       assert( pPager->dbOrigSize==pPager->dbHintSize );
37685       break;
37686
37687     case PAGER_WRITER_DBMOD:
37688       assert( p->eLock==EXCLUSIVE_LOCK );
37689       assert( pPager->errCode==SQLITE_OK );
37690       assert( !pagerUseWal(pPager) );
37691       assert( p->eLock>=EXCLUSIVE_LOCK );
37692       assert( isOpen(p->jfd) 
37693            || p->journalMode==PAGER_JOURNALMODE_OFF 
37694            || p->journalMode==PAGER_JOURNALMODE_WAL 
37695       );
37696       assert( pPager->dbOrigSize<=pPager->dbHintSize );
37697       break;
37698
37699     case PAGER_WRITER_FINISHED:
37700       assert( p->eLock==EXCLUSIVE_LOCK );
37701       assert( pPager->errCode==SQLITE_OK );
37702       assert( !pagerUseWal(pPager) );
37703       assert( isOpen(p->jfd) 
37704            || p->journalMode==PAGER_JOURNALMODE_OFF 
37705            || p->journalMode==PAGER_JOURNALMODE_WAL 
37706       );
37707       break;
37708
37709     case PAGER_ERROR:
37710       /* There must be at least one outstanding reference to the pager if
37711       ** in ERROR state. Otherwise the pager should have already dropped
37712       ** back to OPEN state.
37713       */
37714       assert( pPager->errCode!=SQLITE_OK );
37715       assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
37716       break;
37717   }
37718
37719   return 1;
37720 }
37721 #endif /* ifndef NDEBUG */
37722
37723 #ifdef SQLITE_DEBUG 
37724 /*
37725 ** Return a pointer to a human readable string in a static buffer
37726 ** containing the state of the Pager object passed as an argument. This
37727 ** is intended to be used within debuggers. For example, as an alternative
37728 ** to "print *pPager" in gdb:
37729 **
37730 ** (gdb) printf "%s", print_pager_state(pPager)
37731 */
37732 static char *print_pager_state(Pager *p){
37733   static char zRet[1024];
37734
37735   sqlite3_snprintf(1024, zRet,
37736       "Filename:      %s\n"
37737       "State:         %s errCode=%d\n"
37738       "Lock:          %s\n"
37739       "Locking mode:  locking_mode=%s\n"
37740       "Journal mode:  journal_mode=%s\n"
37741       "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
37742       "Journal:       journalOff=%lld journalHdr=%lld\n"
37743       "Size:          dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
37744       , p->zFilename
37745       , p->eState==PAGER_OPEN            ? "OPEN" :
37746         p->eState==PAGER_READER          ? "READER" :
37747         p->eState==PAGER_WRITER_LOCKED   ? "WRITER_LOCKED" :
37748         p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
37749         p->eState==PAGER_WRITER_DBMOD    ? "WRITER_DBMOD" :
37750         p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
37751         p->eState==PAGER_ERROR           ? "ERROR" : "?error?"
37752       , (int)p->errCode
37753       , p->eLock==NO_LOCK         ? "NO_LOCK" :
37754         p->eLock==RESERVED_LOCK   ? "RESERVED" :
37755         p->eLock==EXCLUSIVE_LOCK  ? "EXCLUSIVE" :
37756         p->eLock==SHARED_LOCK     ? "SHARED" :
37757         p->eLock==UNKNOWN_LOCK    ? "UNKNOWN" : "?error?"
37758       , p->exclusiveMode ? "exclusive" : "normal"
37759       , p->journalMode==PAGER_JOURNALMODE_MEMORY   ? "memory" :
37760         p->journalMode==PAGER_JOURNALMODE_OFF      ? "off" :
37761         p->journalMode==PAGER_JOURNALMODE_DELETE   ? "delete" :
37762         p->journalMode==PAGER_JOURNALMODE_PERSIST  ? "persist" :
37763         p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
37764         p->journalMode==PAGER_JOURNALMODE_WAL      ? "wal" : "?error?"
37765       , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
37766       , p->journalOff, p->journalHdr
37767       , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
37768   );
37769
37770   return zRet;
37771 }
37772 #endif
37773
37774 /*
37775 ** Return true if it is necessary to write page *pPg into the sub-journal.
37776 ** A page needs to be written into the sub-journal if there exists one
37777 ** or more open savepoints for which:
37778 **
37779 **   * The page-number is less than or equal to PagerSavepoint.nOrig, and
37780 **   * The bit corresponding to the page-number is not set in
37781 **     PagerSavepoint.pInSavepoint.
37782 */
37783 static int subjRequiresPage(PgHdr *pPg){
37784   Pgno pgno = pPg->pgno;
37785   Pager *pPager = pPg->pPager;
37786   int i;
37787   for(i=0; i<pPager->nSavepoint; i++){
37788     PagerSavepoint *p = &pPager->aSavepoint[i];
37789     if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
37790       return 1;
37791     }
37792   }
37793   return 0;
37794 }
37795
37796 /*
37797 ** Return true if the page is already in the journal file.
37798 */
37799 static int pageInJournal(PgHdr *pPg){
37800   return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
37801 }
37802
37803 /*
37804 ** Read a 32-bit integer from the given file descriptor.  Store the integer
37805 ** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
37806 ** error code is something goes wrong.
37807 **
37808 ** All values are stored on disk as big-endian.
37809 */
37810 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
37811   unsigned char ac[4];
37812   int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
37813   if( rc==SQLITE_OK ){
37814     *pRes = sqlite3Get4byte(ac);
37815   }
37816   return rc;
37817 }
37818
37819 /*
37820 ** Write a 32-bit integer into a string buffer in big-endian byte order.
37821 */
37822 #define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
37823
37824
37825 /*
37826 ** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
37827 ** on success or an error code is something goes wrong.
37828 */
37829 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
37830   char ac[4];
37831   put32bits(ac, val);
37832   return sqlite3OsWrite(fd, ac, 4, offset);
37833 }
37834
37835 /*
37836 ** Unlock the database file to level eLock, which must be either NO_LOCK
37837 ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
37838 ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
37839 **
37840 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
37841 ** called, do not modify it. See the comment above the #define of 
37842 ** UNKNOWN_LOCK for an explanation of this.
37843 */
37844 static int pagerUnlockDb(Pager *pPager, int eLock){
37845   int rc = SQLITE_OK;
37846
37847   assert( !pPager->exclusiveMode || pPager->eLock==eLock );
37848   assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
37849   assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
37850   if( isOpen(pPager->fd) ){
37851     assert( pPager->eLock>=eLock );
37852     rc = sqlite3OsUnlock(pPager->fd, eLock);
37853     if( pPager->eLock!=UNKNOWN_LOCK ){
37854       pPager->eLock = (u8)eLock;
37855     }
37856     IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
37857   }
37858   return rc;
37859 }
37860
37861 /*
37862 ** Lock the database file to level eLock, which must be either SHARED_LOCK,
37863 ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
37864 ** Pager.eLock variable to the new locking state. 
37865 **
37866 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is 
37867 ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK. 
37868 ** See the comment above the #define of UNKNOWN_LOCK for an explanation 
37869 ** of this.
37870 */
37871 static int pagerLockDb(Pager *pPager, int eLock){
37872   int rc = SQLITE_OK;
37873
37874   assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
37875   if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
37876     rc = sqlite3OsLock(pPager->fd, eLock);
37877     if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
37878       pPager->eLock = (u8)eLock;
37879       IOTRACE(("LOCK %p %d\n", pPager, eLock))
37880     }
37881   }
37882   return rc;
37883 }
37884
37885 /*
37886 ** This function determines whether or not the atomic-write optimization
37887 ** can be used with this pager. The optimization can be used if:
37888 **
37889 **  (a) the value returned by OsDeviceCharacteristics() indicates that
37890 **      a database page may be written atomically, and
37891 **  (b) the value returned by OsSectorSize() is less than or equal
37892 **      to the page size.
37893 **
37894 ** The optimization is also always enabled for temporary files. It is
37895 ** an error to call this function if pPager is opened on an in-memory
37896 ** database.
37897 **
37898 ** If the optimization cannot be used, 0 is returned. If it can be used,
37899 ** then the value returned is the size of the journal file when it
37900 ** contains rollback data for exactly one page.
37901 */
37902 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
37903 static int jrnlBufferSize(Pager *pPager){
37904   assert( !MEMDB );
37905   if( !pPager->tempFile ){
37906     int dc;                           /* Device characteristics */
37907     int nSector;                      /* Sector size */
37908     int szPage;                       /* Page size */
37909
37910     assert( isOpen(pPager->fd) );
37911     dc = sqlite3OsDeviceCharacteristics(pPager->fd);
37912     nSector = pPager->sectorSize;
37913     szPage = pPager->pageSize;
37914
37915     assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
37916     assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
37917     if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
37918       return 0;
37919     }
37920   }
37921
37922   return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
37923 }
37924 #endif
37925
37926 /*
37927 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
37928 ** on the cache using a hash function.  This is used for testing
37929 ** and debugging only.
37930 */
37931 #ifdef SQLITE_CHECK_PAGES
37932 /*
37933 ** Return a 32-bit hash of the page data for pPage.
37934 */
37935 static u32 pager_datahash(int nByte, unsigned char *pData){
37936   u32 hash = 0;
37937   int i;
37938   for(i=0; i<nByte; i++){
37939     hash = (hash*1039) + pData[i];
37940   }
37941   return hash;
37942 }
37943 static u32 pager_pagehash(PgHdr *pPage){
37944   return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
37945 }
37946 static void pager_set_pagehash(PgHdr *pPage){
37947   pPage->pageHash = pager_pagehash(pPage);
37948 }
37949
37950 /*
37951 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
37952 ** is defined, and NDEBUG is not defined, an assert() statement checks
37953 ** that the page is either dirty or still matches the calculated page-hash.
37954 */
37955 #define CHECK_PAGE(x) checkPage(x)
37956 static void checkPage(PgHdr *pPg){
37957   Pager *pPager = pPg->pPager;
37958   assert( pPager->eState!=PAGER_ERROR );
37959   assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
37960 }
37961
37962 #else
37963 #define pager_datahash(X,Y)  0
37964 #define pager_pagehash(X)  0
37965 #define pager_set_pagehash(X)
37966 #define CHECK_PAGE(x)
37967 #endif  /* SQLITE_CHECK_PAGES */
37968
37969 /*
37970 ** When this is called the journal file for pager pPager must be open.
37971 ** This function attempts to read a master journal file name from the 
37972 ** end of the file and, if successful, copies it into memory supplied 
37973 ** by the caller. See comments above writeMasterJournal() for the format
37974 ** used to store a master journal file name at the end of a journal file.
37975 **
37976 ** zMaster must point to a buffer of at least nMaster bytes allocated by
37977 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
37978 ** enough space to write the master journal name). If the master journal
37979 ** name in the journal is longer than nMaster bytes (including a
37980 ** nul-terminator), then this is handled as if no master journal name
37981 ** were present in the journal.
37982 **
37983 ** If a master journal file name is present at the end of the journal
37984 ** file, then it is copied into the buffer pointed to by zMaster. A
37985 ** nul-terminator byte is appended to the buffer following the master
37986 ** journal file name.
37987 **
37988 ** If it is determined that no master journal file name is present 
37989 ** zMaster[0] is set to 0 and SQLITE_OK returned.
37990 **
37991 ** If an error occurs while reading from the journal file, an SQLite
37992 ** error code is returned.
37993 */
37994 static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
37995   int rc;                    /* Return code */
37996   u32 len;                   /* Length in bytes of master journal name */
37997   i64 szJ;                   /* Total size in bytes of journal file pJrnl */
37998   u32 cksum;                 /* MJ checksum value read from journal */
37999   u32 u;                     /* Unsigned loop counter */
38000   unsigned char aMagic[8];   /* A buffer to hold the magic header */
38001   zMaster[0] = '\0';
38002
38003   if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
38004    || szJ<16
38005    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
38006    || len>=nMaster 
38007    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
38008    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
38009    || memcmp(aMagic, aJournalMagic, 8)
38010    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
38011   ){
38012     return rc;
38013   }
38014
38015   /* See if the checksum matches the master journal name */
38016   for(u=0; u<len; u++){
38017     cksum -= zMaster[u];
38018   }
38019   if( cksum ){
38020     /* If the checksum doesn't add up, then one or more of the disk sectors
38021     ** containing the master journal filename is corrupted. This means
38022     ** definitely roll back, so just return SQLITE_OK and report a (nul)
38023     ** master-journal filename.
38024     */
38025     len = 0;
38026   }
38027   zMaster[len] = '\0';
38028    
38029   return SQLITE_OK;
38030 }
38031
38032 /*
38033 ** Return the offset of the sector boundary at or immediately 
38034 ** following the value in pPager->journalOff, assuming a sector 
38035 ** size of pPager->sectorSize bytes.
38036 **
38037 ** i.e for a sector size of 512:
38038 **
38039 **   Pager.journalOff          Return value
38040 **   ---------------------------------------
38041 **   0                         0
38042 **   512                       512
38043 **   100                       512
38044 **   2000                      2048
38045 ** 
38046 */
38047 static i64 journalHdrOffset(Pager *pPager){
38048   i64 offset = 0;
38049   i64 c = pPager->journalOff;
38050   if( c ){
38051     offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
38052   }
38053   assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
38054   assert( offset>=c );
38055   assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
38056   return offset;
38057 }
38058
38059 /*
38060 ** The journal file must be open when this function is called.
38061 **
38062 ** This function is a no-op if the journal file has not been written to
38063 ** within the current transaction (i.e. if Pager.journalOff==0).
38064 **
38065 ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
38066 ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
38067 ** zero the 28-byte header at the start of the journal file. In either case, 
38068 ** if the pager is not in no-sync mode, sync the journal file immediately 
38069 ** after writing or truncating it.
38070 **
38071 ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
38072 ** following the truncation or zeroing described above the size of the 
38073 ** journal file in bytes is larger than this value, then truncate the
38074 ** journal file to Pager.journalSizeLimit bytes. The journal file does
38075 ** not need to be synced following this operation.
38076 **
38077 ** If an IO error occurs, abandon processing and return the IO error code.
38078 ** Otherwise, return SQLITE_OK.
38079 */
38080 static int zeroJournalHdr(Pager *pPager, int doTruncate){
38081   int rc = SQLITE_OK;                               /* Return code */
38082   assert( isOpen(pPager->jfd) );
38083   if( pPager->journalOff ){
38084     const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
38085
38086     IOTRACE(("JZEROHDR %p\n", pPager))
38087     if( doTruncate || iLimit==0 ){
38088       rc = sqlite3OsTruncate(pPager->jfd, 0);
38089     }else{
38090       static const char zeroHdr[28] = {0};
38091       rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
38092     }
38093     if( rc==SQLITE_OK && !pPager->noSync ){
38094       rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
38095     }
38096
38097     /* At this point the transaction is committed but the write lock 
38098     ** is still held on the file. If there is a size limit configured for 
38099     ** the persistent journal and the journal file currently consumes more
38100     ** space than that limit allows for, truncate it now. There is no need
38101     ** to sync the file following this operation.
38102     */
38103     if( rc==SQLITE_OK && iLimit>0 ){
38104       i64 sz;
38105       rc = sqlite3OsFileSize(pPager->jfd, &sz);
38106       if( rc==SQLITE_OK && sz>iLimit ){
38107         rc = sqlite3OsTruncate(pPager->jfd, iLimit);
38108       }
38109     }
38110   }
38111   return rc;
38112 }
38113
38114 /*
38115 ** The journal file must be open when this routine is called. A journal
38116 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
38117 ** current location.
38118 **
38119 ** The format for the journal header is as follows:
38120 ** - 8 bytes: Magic identifying journal format.
38121 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
38122 ** - 4 bytes: Random number used for page hash.
38123 ** - 4 bytes: Initial database page count.
38124 ** - 4 bytes: Sector size used by the process that wrote this journal.
38125 ** - 4 bytes: Database page size.
38126 ** 
38127 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
38128 */
38129 static int writeJournalHdr(Pager *pPager){
38130   int rc = SQLITE_OK;                 /* Return code */
38131   char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
38132   u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
38133   u32 nWrite;                         /* Bytes of header sector written */
38134   int ii;                             /* Loop counter */
38135
38136   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
38137
38138   if( nHeader>JOURNAL_HDR_SZ(pPager) ){
38139     nHeader = JOURNAL_HDR_SZ(pPager);
38140   }
38141
38142   /* If there are active savepoints and any of them were created 
38143   ** since the most recent journal header was written, update the 
38144   ** PagerSavepoint.iHdrOffset fields now.
38145   */
38146   for(ii=0; ii<pPager->nSavepoint; ii++){
38147     if( pPager->aSavepoint[ii].iHdrOffset==0 ){
38148       pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
38149     }
38150   }
38151
38152   pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
38153
38154   /* 
38155   ** Write the nRec Field - the number of page records that follow this
38156   ** journal header. Normally, zero is written to this value at this time.
38157   ** After the records are added to the journal (and the journal synced, 
38158   ** if in full-sync mode), the zero is overwritten with the true number
38159   ** of records (see syncJournal()).
38160   **
38161   ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
38162   ** reading the journal this value tells SQLite to assume that the
38163   ** rest of the journal file contains valid page records. This assumption
38164   ** is dangerous, as if a failure occurred whilst writing to the journal
38165   ** file it may contain some garbage data. There are two scenarios
38166   ** where this risk can be ignored:
38167   **
38168   **   * When the pager is in no-sync mode. Corruption can follow a
38169   **     power failure in this case anyway.
38170   **
38171   **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
38172   **     that garbage data is never appended to the journal file.
38173   */
38174   assert( isOpen(pPager->fd) || pPager->noSync );
38175   if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
38176    || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND) 
38177   ){
38178     memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
38179     put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
38180   }else{
38181     memset(zHeader, 0, sizeof(aJournalMagic)+4);
38182   }
38183
38184   /* The random check-hash initialiser */ 
38185   sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
38186   put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
38187   /* The initial database size */
38188   put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
38189   /* The assumed sector size for this process */
38190   put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
38191
38192   /* The page size */
38193   put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
38194
38195   /* Initializing the tail of the buffer is not necessary.  Everything
38196   ** works find if the following memset() is omitted.  But initializing
38197   ** the memory prevents valgrind from complaining, so we are willing to
38198   ** take the performance hit.
38199   */
38200   memset(&zHeader[sizeof(aJournalMagic)+20], 0,
38201          nHeader-(sizeof(aJournalMagic)+20));
38202
38203   /* In theory, it is only necessary to write the 28 bytes that the 
38204   ** journal header consumes to the journal file here. Then increment the 
38205   ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next 
38206   ** record is written to the following sector (leaving a gap in the file
38207   ** that will be implicitly filled in by the OS).
38208   **
38209   ** However it has been discovered that on some systems this pattern can 
38210   ** be significantly slower than contiguously writing data to the file,
38211   ** even if that means explicitly writing data to the block of 
38212   ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
38213   ** is done. 
38214   **
38215   ** The loop is required here in case the sector-size is larger than the 
38216   ** database page size. Since the zHeader buffer is only Pager.pageSize
38217   ** bytes in size, more than one call to sqlite3OsWrite() may be required
38218   ** to populate the entire journal header sector.
38219   */ 
38220   for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
38221     IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
38222     rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
38223     assert( pPager->journalHdr <= pPager->journalOff );
38224     pPager->journalOff += nHeader;
38225   }
38226
38227   return rc;
38228 }
38229
38230 /*
38231 ** The journal file must be open when this is called. A journal header file
38232 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
38233 ** file. The current location in the journal file is given by
38234 ** pPager->journalOff. See comments above function writeJournalHdr() for
38235 ** a description of the journal header format.
38236 **
38237 ** If the header is read successfully, *pNRec is set to the number of
38238 ** page records following this header and *pDbSize is set to the size of the
38239 ** database before the transaction began, in pages. Also, pPager->cksumInit
38240 ** is set to the value read from the journal header. SQLITE_OK is returned
38241 ** in this case.
38242 **
38243 ** If the journal header file appears to be corrupted, SQLITE_DONE is
38244 ** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
38245 ** cannot be read from the journal file an error code is returned.
38246 */
38247 static int readJournalHdr(
38248   Pager *pPager,               /* Pager object */
38249   int isHot,
38250   i64 journalSize,             /* Size of the open journal file in bytes */
38251   u32 *pNRec,                  /* OUT: Value read from the nRec field */
38252   u32 *pDbSize                 /* OUT: Value of original database size field */
38253 ){
38254   int rc;                      /* Return code */
38255   unsigned char aMagic[8];     /* A buffer to hold the magic header */
38256   i64 iHdrOff;                 /* Offset of journal header being read */
38257
38258   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
38259
38260   /* Advance Pager.journalOff to the start of the next sector. If the
38261   ** journal file is too small for there to be a header stored at this
38262   ** point, return SQLITE_DONE.
38263   */
38264   pPager->journalOff = journalHdrOffset(pPager);
38265   if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
38266     return SQLITE_DONE;
38267   }
38268   iHdrOff = pPager->journalOff;
38269
38270   /* Read in the first 8 bytes of the journal header. If they do not match
38271   ** the  magic string found at the start of each journal header, return
38272   ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
38273   ** proceed.
38274   */
38275   if( isHot || iHdrOff!=pPager->journalHdr ){
38276     rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
38277     if( rc ){
38278       return rc;
38279     }
38280     if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
38281       return SQLITE_DONE;
38282     }
38283   }
38284
38285   /* Read the first three 32-bit fields of the journal header: The nRec
38286   ** field, the checksum-initializer and the database size at the start
38287   ** of the transaction. Return an error code if anything goes wrong.
38288   */
38289   if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
38290    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
38291    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
38292   ){
38293     return rc;
38294   }
38295
38296   if( pPager->journalOff==0 ){
38297     u32 iPageSize;               /* Page-size field of journal header */
38298     u32 iSectorSize;             /* Sector-size field of journal header */
38299
38300     /* Read the page-size and sector-size journal header fields. */
38301     if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
38302      || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
38303     ){
38304       return rc;
38305     }
38306
38307     /* Versions of SQLite prior to 3.5.8 set the page-size field of the
38308     ** journal header to zero. In this case, assume that the Pager.pageSize
38309     ** variable is already set to the correct page size.
38310     */
38311     if( iPageSize==0 ){
38312       iPageSize = pPager->pageSize;
38313     }
38314
38315     /* Check that the values read from the page-size and sector-size fields
38316     ** are within range. To be 'in range', both values need to be a power
38317     ** of two greater than or equal to 512 or 32, and not greater than their 
38318     ** respective compile time maximum limits.
38319     */
38320     if( iPageSize<512                  || iSectorSize<32
38321      || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
38322      || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0 
38323     ){
38324       /* If the either the page-size or sector-size in the journal-header is 
38325       ** invalid, then the process that wrote the journal-header must have 
38326       ** crashed before the header was synced. In this case stop reading 
38327       ** the journal file here.
38328       */
38329       return SQLITE_DONE;
38330     }
38331
38332     /* Update the page-size to match the value read from the journal. 
38333     ** Use a testcase() macro to make sure that malloc failure within 
38334     ** PagerSetPagesize() is tested.
38335     */
38336     rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
38337     testcase( rc!=SQLITE_OK );
38338
38339     /* Update the assumed sector-size to match the value used by 
38340     ** the process that created this journal. If this journal was
38341     ** created by a process other than this one, then this routine
38342     ** is being called from within pager_playback(). The local value
38343     ** of Pager.sectorSize is restored at the end of that routine.
38344     */
38345     pPager->sectorSize = iSectorSize;
38346   }
38347
38348   pPager->journalOff += JOURNAL_HDR_SZ(pPager);
38349   return rc;
38350 }
38351
38352
38353 /*
38354 ** Write the supplied master journal name into the journal file for pager
38355 ** pPager at the current location. The master journal name must be the last
38356 ** thing written to a journal file. If the pager is in full-sync mode, the
38357 ** journal file descriptor is advanced to the next sector boundary before
38358 ** anything is written. The format is:
38359 **
38360 **   + 4 bytes: PAGER_MJ_PGNO.
38361 **   + N bytes: Master journal filename in utf-8.
38362 **   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
38363 **   + 4 bytes: Master journal name checksum.
38364 **   + 8 bytes: aJournalMagic[].
38365 **
38366 ** The master journal page checksum is the sum of the bytes in the master
38367 ** journal name, where each byte is interpreted as a signed 8-bit integer.
38368 **
38369 ** If zMaster is a NULL pointer (occurs for a single database transaction), 
38370 ** this call is a no-op.
38371 */
38372 static int writeMasterJournal(Pager *pPager, const char *zMaster){
38373   int rc;                          /* Return code */
38374   int nMaster;                     /* Length of string zMaster */
38375   i64 iHdrOff;                     /* Offset of header in journal file */
38376   i64 jrnlSize;                    /* Size of journal file on disk */
38377   u32 cksum = 0;                   /* Checksum of string zMaster */
38378
38379   assert( pPager->setMaster==0 );
38380   assert( !pagerUseWal(pPager) );
38381
38382   if( !zMaster 
38383    || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
38384    || pPager->journalMode==PAGER_JOURNALMODE_OFF 
38385   ){
38386     return SQLITE_OK;
38387   }
38388   pPager->setMaster = 1;
38389   assert( isOpen(pPager->jfd) );
38390   assert( pPager->journalHdr <= pPager->journalOff );
38391
38392   /* Calculate the length in bytes and the checksum of zMaster */
38393   for(nMaster=0; zMaster[nMaster]; nMaster++){
38394     cksum += zMaster[nMaster];
38395   }
38396
38397   /* If in full-sync mode, advance to the next disk sector before writing
38398   ** the master journal name. This is in case the previous page written to
38399   ** the journal has already been synced.
38400   */
38401   if( pPager->fullSync ){
38402     pPager->journalOff = journalHdrOffset(pPager);
38403   }
38404   iHdrOff = pPager->journalOff;
38405
38406   /* Write the master journal data to the end of the journal file. If
38407   ** an error occurs, return the error code to the caller.
38408   */
38409   if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
38410    || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
38411    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
38412    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
38413    || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
38414   ){
38415     return rc;
38416   }
38417   pPager->journalOff += (nMaster+20);
38418
38419   /* If the pager is in peristent-journal mode, then the physical 
38420   ** journal-file may extend past the end of the master-journal name
38421   ** and 8 bytes of magic data just written to the file. This is 
38422   ** dangerous because the code to rollback a hot-journal file
38423   ** will not be able to find the master-journal name to determine 
38424   ** whether or not the journal is hot. 
38425   **
38426   ** Easiest thing to do in this scenario is to truncate the journal 
38427   ** file to the required size.
38428   */ 
38429   if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
38430    && jrnlSize>pPager->journalOff
38431   ){
38432     rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
38433   }
38434   return rc;
38435 }
38436
38437 /*
38438 ** Find a page in the hash table given its page number. Return
38439 ** a pointer to the page or NULL if the requested page is not 
38440 ** already in memory.
38441 */
38442 static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
38443   PgHdr *p;                         /* Return value */
38444
38445   /* It is not possible for a call to PcacheFetch() with createFlag==0 to
38446   ** fail, since no attempt to allocate dynamic memory will be made.
38447   */
38448   (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
38449   return p;
38450 }
38451
38452 /*
38453 ** Discard the entire contents of the in-memory page-cache.
38454 */
38455 static void pager_reset(Pager *pPager){
38456   sqlite3BackupRestart(pPager->pBackup);
38457   sqlite3PcacheClear(pPager->pPCache);
38458 }
38459
38460 /*
38461 ** Free all structures in the Pager.aSavepoint[] array and set both
38462 ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
38463 ** if it is open and the pager is not in exclusive mode.
38464 */
38465 static void releaseAllSavepoints(Pager *pPager){
38466   int ii;               /* Iterator for looping through Pager.aSavepoint */
38467   for(ii=0; ii<pPager->nSavepoint; ii++){
38468     sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
38469   }
38470   if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
38471     sqlite3OsClose(pPager->sjfd);
38472   }
38473   sqlite3_free(pPager->aSavepoint);
38474   pPager->aSavepoint = 0;
38475   pPager->nSavepoint = 0;
38476   pPager->nSubRec = 0;
38477 }
38478
38479 /*
38480 ** Set the bit number pgno in the PagerSavepoint.pInSavepoint 
38481 ** bitvecs of all open savepoints. Return SQLITE_OK if successful
38482 ** or SQLITE_NOMEM if a malloc failure occurs.
38483 */
38484 static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
38485   int ii;                   /* Loop counter */
38486   int rc = SQLITE_OK;       /* Result code */
38487
38488   for(ii=0; ii<pPager->nSavepoint; ii++){
38489     PagerSavepoint *p = &pPager->aSavepoint[ii];
38490     if( pgno<=p->nOrig ){
38491       rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
38492       testcase( rc==SQLITE_NOMEM );
38493       assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
38494     }
38495   }
38496   return rc;
38497 }
38498
38499 /*
38500 ** This function is a no-op if the pager is in exclusive mode and not
38501 ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
38502 ** state.
38503 **
38504 ** If the pager is not in exclusive-access mode, the database file is
38505 ** completely unlocked. If the file is unlocked and the file-system does
38506 ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
38507 ** closed (if it is open).
38508 **
38509 ** If the pager is in ERROR state when this function is called, the 
38510 ** contents of the pager cache are discarded before switching back to 
38511 ** the OPEN state. Regardless of whether the pager is in exclusive-mode
38512 ** or not, any journal file left in the file-system will be treated
38513 ** as a hot-journal and rolled back the next time a read-transaction
38514 ** is opened (by this or by any other connection).
38515 */
38516 static void pager_unlock(Pager *pPager){
38517
38518   assert( pPager->eState==PAGER_READER 
38519        || pPager->eState==PAGER_OPEN 
38520        || pPager->eState==PAGER_ERROR 
38521   );
38522
38523   sqlite3BitvecDestroy(pPager->pInJournal);
38524   pPager->pInJournal = 0;
38525   releaseAllSavepoints(pPager);
38526
38527   if( pagerUseWal(pPager) ){
38528     assert( !isOpen(pPager->jfd) );
38529     sqlite3WalEndReadTransaction(pPager->pWal);
38530     pPager->eState = PAGER_OPEN;
38531   }else if( !pPager->exclusiveMode ){
38532     int rc;                       /* Error code returned by pagerUnlockDb() */
38533     int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
38534
38535     /* If the operating system support deletion of open files, then
38536     ** close the journal file when dropping the database lock.  Otherwise
38537     ** another connection with journal_mode=delete might delete the file
38538     ** out from under us.
38539     */
38540     assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );
38541     assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );
38542     assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );
38543     assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );
38544     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
38545     assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );
38546     if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
38547      || 1!=(pPager->journalMode & 5)
38548     ){
38549       sqlite3OsClose(pPager->jfd);
38550     }
38551
38552     /* If the pager is in the ERROR state and the call to unlock the database
38553     ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
38554     ** above the #define for UNKNOWN_LOCK for an explanation of why this
38555     ** is necessary.
38556     */
38557     rc = pagerUnlockDb(pPager, NO_LOCK);
38558     if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
38559       pPager->eLock = UNKNOWN_LOCK;
38560     }
38561
38562     /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
38563     ** without clearing the error code. This is intentional - the error
38564     ** code is cleared and the cache reset in the block below.
38565     */
38566     assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
38567     pPager->changeCountDone = 0;
38568     pPager->eState = PAGER_OPEN;
38569   }
38570
38571   /* If Pager.errCode is set, the contents of the pager cache cannot be
38572   ** trusted. Now that there are no outstanding references to the pager,
38573   ** it can safely move back to PAGER_OPEN state. This happens in both
38574   ** normal and exclusive-locking mode.
38575   */
38576   if( pPager->errCode ){
38577     assert( !MEMDB );
38578     pager_reset(pPager);
38579     pPager->changeCountDone = pPager->tempFile;
38580     pPager->eState = PAGER_OPEN;
38581     pPager->errCode = SQLITE_OK;
38582   }
38583
38584   pPager->journalOff = 0;
38585   pPager->journalHdr = 0;
38586   pPager->setMaster = 0;
38587 }
38588
38589 /*
38590 ** This function is called whenever an IOERR or FULL error that requires
38591 ** the pager to transition into the ERROR state may ahve occurred.
38592 ** The first argument is a pointer to the pager structure, the second 
38593 ** the error-code about to be returned by a pager API function. The 
38594 ** value returned is a copy of the second argument to this function. 
38595 **
38596 ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
38597 ** IOERR sub-codes, the pager enters the ERROR state and the error code
38598 ** is stored in Pager.errCode. While the pager remains in the ERROR state,
38599 ** all major API calls on the Pager will immediately return Pager.errCode.
38600 **
38601 ** The ERROR state indicates that the contents of the pager-cache 
38602 ** cannot be trusted. This state can be cleared by completely discarding 
38603 ** the contents of the pager-cache. If a transaction was active when
38604 ** the persistent error occurred, then the rollback journal may need
38605 ** to be replayed to restore the contents of the database file (as if
38606 ** it were a hot-journal).
38607 */
38608 static int pager_error(Pager *pPager, int rc){
38609   int rc2 = rc & 0xff;
38610   assert( rc==SQLITE_OK || !MEMDB );
38611   assert(
38612        pPager->errCode==SQLITE_FULL ||
38613        pPager->errCode==SQLITE_OK ||
38614        (pPager->errCode & 0xff)==SQLITE_IOERR
38615   );
38616   if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
38617     pPager->errCode = rc;
38618     pPager->eState = PAGER_ERROR;
38619   }
38620   return rc;
38621 }
38622
38623 /*
38624 ** This routine ends a transaction. A transaction is usually ended by 
38625 ** either a COMMIT or a ROLLBACK operation. This routine may be called 
38626 ** after rollback of a hot-journal, or if an error occurs while opening
38627 ** the journal file or writing the very first journal-header of a
38628 ** database transaction.
38629 ** 
38630 ** This routine is never called in PAGER_ERROR state. If it is called
38631 ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
38632 ** exclusive than a RESERVED lock, it is a no-op.
38633 **
38634 ** Otherwise, any active savepoints are released.
38635 **
38636 ** If the journal file is open, then it is "finalized". Once a journal 
38637 ** file has been finalized it is not possible to use it to roll back a 
38638 ** transaction. Nor will it be considered to be a hot-journal by this
38639 ** or any other database connection. Exactly how a journal is finalized
38640 ** depends on whether or not the pager is running in exclusive mode and
38641 ** the current journal-mode (Pager.journalMode value), as follows:
38642 **
38643 **   journalMode==MEMORY
38644 **     Journal file descriptor is simply closed. This destroys an 
38645 **     in-memory journal.
38646 **
38647 **   journalMode==TRUNCATE
38648 **     Journal file is truncated to zero bytes in size.
38649 **
38650 **   journalMode==PERSIST
38651 **     The first 28 bytes of the journal file are zeroed. This invalidates
38652 **     the first journal header in the file, and hence the entire journal
38653 **     file. An invalid journal file cannot be rolled back.
38654 **
38655 **   journalMode==DELETE
38656 **     The journal file is closed and deleted using sqlite3OsDelete().
38657 **
38658 **     If the pager is running in exclusive mode, this method of finalizing
38659 **     the journal file is never used. Instead, if the journalMode is
38660 **     DELETE and the pager is in exclusive mode, the method described under
38661 **     journalMode==PERSIST is used instead.
38662 **
38663 ** After the journal is finalized, the pager moves to PAGER_READER state.
38664 ** If running in non-exclusive rollback mode, the lock on the file is 
38665 ** downgraded to a SHARED_LOCK.
38666 **
38667 ** SQLITE_OK is returned if no error occurs. If an error occurs during
38668 ** any of the IO operations to finalize the journal file or unlock the
38669 ** database then the IO error code is returned to the user. If the 
38670 ** operation to finalize the journal file fails, then the code still
38671 ** tries to unlock the database file if not in exclusive mode. If the
38672 ** unlock operation fails as well, then the first error code related
38673 ** to the first error encountered (the journal finalization one) is
38674 ** returned.
38675 */
38676 static int pager_end_transaction(Pager *pPager, int hasMaster){
38677   int rc = SQLITE_OK;      /* Error code from journal finalization operation */
38678   int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
38679
38680   /* Do nothing if the pager does not have an open write transaction
38681   ** or at least a RESERVED lock. This function may be called when there
38682   ** is no write-transaction active but a RESERVED or greater lock is
38683   ** held under two circumstances:
38684   **
38685   **   1. After a successful hot-journal rollback, it is called with
38686   **      eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
38687   **
38688   **   2. If a connection with locking_mode=exclusive holding an EXCLUSIVE 
38689   **      lock switches back to locking_mode=normal and then executes a
38690   **      read-transaction, this function is called with eState==PAGER_READER 
38691   **      and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
38692   */
38693   assert( assert_pager_state(pPager) );
38694   assert( pPager->eState!=PAGER_ERROR );
38695   if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
38696     return SQLITE_OK;
38697   }
38698
38699   releaseAllSavepoints(pPager);
38700   assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
38701   if( isOpen(pPager->jfd) ){
38702     assert( !pagerUseWal(pPager) );
38703
38704     /* Finalize the journal file. */
38705     if( sqlite3IsMemJournal(pPager->jfd) ){
38706       assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
38707       sqlite3OsClose(pPager->jfd);
38708     }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
38709       if( pPager->journalOff==0 ){
38710         rc = SQLITE_OK;
38711       }else{
38712         rc = sqlite3OsTruncate(pPager->jfd, 0);
38713       }
38714       pPager->journalOff = 0;
38715     }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
38716       || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
38717     ){
38718       rc = zeroJournalHdr(pPager, hasMaster);
38719       pPager->journalOff = 0;
38720     }else{
38721       /* This branch may be executed with Pager.journalMode==MEMORY if
38722       ** a hot-journal was just rolled back. In this case the journal
38723       ** file should be closed and deleted. If this connection writes to
38724       ** the database file, it will do so using an in-memory journal. 
38725       */
38726       assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE 
38727            || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
38728            || pPager->journalMode==PAGER_JOURNALMODE_WAL 
38729       );
38730       sqlite3OsClose(pPager->jfd);
38731       if( !pPager->tempFile ){
38732         rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
38733       }
38734     }
38735   }
38736
38737 #ifdef SQLITE_CHECK_PAGES
38738   sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
38739   if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
38740     PgHdr *p = pager_lookup(pPager, 1);
38741     if( p ){
38742       p->pageHash = 0;
38743       sqlite3PagerUnref(p);
38744     }
38745   }
38746 #endif
38747
38748   sqlite3BitvecDestroy(pPager->pInJournal);
38749   pPager->pInJournal = 0;
38750   pPager->nRec = 0;
38751   sqlite3PcacheCleanAll(pPager->pPCache);
38752   sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
38753
38754   if( pagerUseWal(pPager) ){
38755     /* Drop the WAL write-lock, if any. Also, if the connection was in 
38756     ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE 
38757     ** lock held on the database file.
38758     */
38759     rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
38760     assert( rc2==SQLITE_OK );
38761   }
38762   if( !pPager->exclusiveMode 
38763    && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
38764   ){
38765     rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
38766     pPager->changeCountDone = 0;
38767   }
38768   pPager->eState = PAGER_READER;
38769   pPager->setMaster = 0;
38770
38771   return (rc==SQLITE_OK?rc2:rc);
38772 }
38773
38774 /*
38775 ** Execute a rollback if a transaction is active and unlock the 
38776 ** database file. 
38777 **
38778 ** If the pager has already entered the ERROR state, do not attempt 
38779 ** the rollback at this time. Instead, pager_unlock() is called. The
38780 ** call to pager_unlock() will discard all in-memory pages, unlock
38781 ** the database file and move the pager back to OPEN state. If this 
38782 ** means that there is a hot-journal left in the file-system, the next 
38783 ** connection to obtain a shared lock on the pager (which may be this one) 
38784 ** will roll it back.
38785 **
38786 ** If the pager has not already entered the ERROR state, but an IO or
38787 ** malloc error occurs during a rollback, then this will itself cause 
38788 ** the pager to enter the ERROR state. Which will be cleared by the
38789 ** call to pager_unlock(), as described above.
38790 */
38791 static void pagerUnlockAndRollback(Pager *pPager){
38792   if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
38793     assert( assert_pager_state(pPager) );
38794     if( pPager->eState>=PAGER_WRITER_LOCKED ){
38795       sqlite3BeginBenignMalloc();
38796       sqlite3PagerRollback(pPager);
38797       sqlite3EndBenignMalloc();
38798     }else if( !pPager->exclusiveMode ){
38799       assert( pPager->eState==PAGER_READER );
38800       pager_end_transaction(pPager, 0);
38801     }
38802   }
38803   pager_unlock(pPager);
38804 }
38805
38806 /*
38807 ** Parameter aData must point to a buffer of pPager->pageSize bytes
38808 ** of data. Compute and return a checksum based ont the contents of the 
38809 ** page of data and the current value of pPager->cksumInit.
38810 **
38811 ** This is not a real checksum. It is really just the sum of the 
38812 ** random initial value (pPager->cksumInit) and every 200th byte
38813 ** of the page data, starting with byte offset (pPager->pageSize%200).
38814 ** Each byte is interpreted as an 8-bit unsigned integer.
38815 **
38816 ** Changing the formula used to compute this checksum results in an
38817 ** incompatible journal file format.
38818 **
38819 ** If journal corruption occurs due to a power failure, the most likely 
38820 ** scenario is that one end or the other of the record will be changed. 
38821 ** It is much less likely that the two ends of the journal record will be
38822 ** correct and the middle be corrupt.  Thus, this "checksum" scheme,
38823 ** though fast and simple, catches the mostly likely kind of corruption.
38824 */
38825 static u32 pager_cksum(Pager *pPager, const u8 *aData){
38826   u32 cksum = pPager->cksumInit;         /* Checksum value to return */
38827   int i = pPager->pageSize-200;          /* Loop counter */
38828   while( i>0 ){
38829     cksum += aData[i];
38830     i -= 200;
38831   }
38832   return cksum;
38833 }
38834
38835 /*
38836 ** Report the current page size and number of reserved bytes back
38837 ** to the codec.
38838 */
38839 #ifdef SQLITE_HAS_CODEC
38840 static void pagerReportSize(Pager *pPager){
38841   if( pPager->xCodecSizeChng ){
38842     pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
38843                            (int)pPager->nReserve);
38844   }
38845 }
38846 #else
38847 # define pagerReportSize(X)     /* No-op if we do not support a codec */
38848 #endif
38849
38850 /*
38851 ** Read a single page from either the journal file (if isMainJrnl==1) or
38852 ** from the sub-journal (if isMainJrnl==0) and playback that page.
38853 ** The page begins at offset *pOffset into the file. The *pOffset
38854 ** value is increased to the start of the next page in the journal.
38855 **
38856 ** The main rollback journal uses checksums - the statement journal does 
38857 ** not.
38858 **
38859 ** If the page number of the page record read from the (sub-)journal file
38860 ** is greater than the current value of Pager.dbSize, then playback is
38861 ** skipped and SQLITE_OK is returned.
38862 **
38863 ** If pDone is not NULL, then it is a record of pages that have already
38864 ** been played back.  If the page at *pOffset has already been played back
38865 ** (if the corresponding pDone bit is set) then skip the playback.
38866 ** Make sure the pDone bit corresponding to the *pOffset page is set
38867 ** prior to returning.
38868 **
38869 ** If the page record is successfully read from the (sub-)journal file
38870 ** and played back, then SQLITE_OK is returned. If an IO error occurs
38871 ** while reading the record from the (sub-)journal file or while writing
38872 ** to the database file, then the IO error code is returned. If data
38873 ** is successfully read from the (sub-)journal file but appears to be
38874 ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
38875 ** two circumstances:
38876 ** 
38877 **   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
38878 **   * If the record is being rolled back from the main journal file
38879 **     and the checksum field does not match the record content.
38880 **
38881 ** Neither of these two scenarios are possible during a savepoint rollback.
38882 **
38883 ** If this is a savepoint rollback, then memory may have to be dynamically
38884 ** allocated by this function. If this is the case and an allocation fails,
38885 ** SQLITE_NOMEM is returned.
38886 */
38887 static int pager_playback_one_page(
38888   Pager *pPager,                /* The pager being played back */
38889   i64 *pOffset,                 /* Offset of record to playback */
38890   Bitvec *pDone,                /* Bitvec of pages already played back */
38891   int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
38892   int isSavepnt                 /* True for a savepoint rollback */
38893 ){
38894   int rc;
38895   PgHdr *pPg;                   /* An existing page in the cache */
38896   Pgno pgno;                    /* The page number of a page in journal */
38897   u32 cksum;                    /* Checksum used for sanity checking */
38898   char *aData;                  /* Temporary storage for the page */
38899   sqlite3_file *jfd;            /* The file descriptor for the journal file */
38900   int isSynced;                 /* True if journal page is synced */
38901
38902   assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
38903   assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
38904   assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
38905   assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
38906
38907   aData = pPager->pTmpSpace;
38908   assert( aData );         /* Temp storage must have already been allocated */
38909   assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
38910
38911   /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction 
38912   ** or savepoint rollback done at the request of the caller) or this is
38913   ** a hot-journal rollback. If it is a hot-journal rollback, the pager
38914   ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
38915   ** only reads from the main journal, not the sub-journal.
38916   */
38917   assert( pPager->eState>=PAGER_WRITER_CACHEMOD
38918        || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
38919   );
38920   assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
38921
38922   /* Read the page number and page data from the journal or sub-journal
38923   ** file. Return an error code to the caller if an IO error occurs.
38924   */
38925   jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
38926   rc = read32bits(jfd, *pOffset, &pgno);
38927   if( rc!=SQLITE_OK ) return rc;
38928   rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
38929   if( rc!=SQLITE_OK ) return rc;
38930   *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
38931
38932   /* Sanity checking on the page.  This is more important that I originally
38933   ** thought.  If a power failure occurs while the journal is being written,
38934   ** it could cause invalid data to be written into the journal.  We need to
38935   ** detect this invalid data (with high probability) and ignore it.
38936   */
38937   if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
38938     assert( !isSavepnt );
38939     return SQLITE_DONE;
38940   }
38941   if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
38942     return SQLITE_OK;
38943   }
38944   if( isMainJrnl ){
38945     rc = read32bits(jfd, (*pOffset)-4, &cksum);
38946     if( rc ) return rc;
38947     if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
38948       return SQLITE_DONE;
38949     }
38950   }
38951
38952   /* If this page has already been played by before during the current
38953   ** rollback, then don't bother to play it back again.
38954   */
38955   if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
38956     return rc;
38957   }
38958
38959   /* When playing back page 1, restore the nReserve setting
38960   */
38961   if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
38962     pPager->nReserve = ((u8*)aData)[20];
38963     pagerReportSize(pPager);
38964   }
38965
38966   /* If the pager is in CACHEMOD state, then there must be a copy of this
38967   ** page in the pager cache. In this case just update the pager cache,
38968   ** not the database file. The page is left marked dirty in this case.
38969   **
38970   ** An exception to the above rule: If the database is in no-sync mode
38971   ** and a page is moved during an incremental vacuum then the page may
38972   ** not be in the pager cache. Later: if a malloc() or IO error occurs
38973   ** during a Movepage() call, then the page may not be in the cache
38974   ** either. So the condition described in the above paragraph is not
38975   ** assert()able.
38976   **
38977   ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
38978   ** pager cache if it exists and the main file. The page is then marked 
38979   ** not dirty. Since this code is only executed in PAGER_OPEN state for
38980   ** a hot-journal rollback, it is guaranteed that the page-cache is empty
38981   ** if the pager is in OPEN state.
38982   **
38983   ** Ticket #1171:  The statement journal might contain page content that is
38984   ** different from the page content at the start of the transaction.
38985   ** This occurs when a page is changed prior to the start of a statement
38986   ** then changed again within the statement.  When rolling back such a
38987   ** statement we must not write to the original database unless we know
38988   ** for certain that original page contents are synced into the main rollback
38989   ** journal.  Otherwise, a power loss might leave modified data in the
38990   ** database file without an entry in the rollback journal that can
38991   ** restore the database to its original form.  Two conditions must be
38992   ** met before writing to the database files. (1) the database must be
38993   ** locked.  (2) we know that the original page content is fully synced
38994   ** in the main journal either because the page is not in cache or else
38995   ** the page is marked as needSync==0.
38996   **
38997   ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
38998   ** is possible to fail a statement on a database that does not yet exist.
38999   ** Do not attempt to write if database file has never been opened.
39000   */
39001   if( pagerUseWal(pPager) ){
39002     pPg = 0;
39003   }else{
39004     pPg = pager_lookup(pPager, pgno);
39005   }
39006   assert( pPg || !MEMDB );
39007   assert( pPager->eState!=PAGER_OPEN || pPg==0 );
39008   PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
39009            PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
39010            (isMainJrnl?"main-journal":"sub-journal")
39011   ));
39012   if( isMainJrnl ){
39013     isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
39014   }else{
39015     isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
39016   }
39017   if( isOpen(pPager->fd)
39018    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
39019    && isSynced
39020   ){
39021     i64 ofst = (pgno-1)*(i64)pPager->pageSize;
39022     testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
39023     assert( !pagerUseWal(pPager) );
39024     rc = sqlite3OsWrite(pPager->fd, (u8*)aData, pPager->pageSize, ofst);
39025     if( pgno>pPager->dbFileSize ){
39026       pPager->dbFileSize = pgno;
39027     }
39028     if( pPager->pBackup ){
39029       CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
39030       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
39031       CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
39032     }
39033   }else if( !isMainJrnl && pPg==0 ){
39034     /* If this is a rollback of a savepoint and data was not written to
39035     ** the database and the page is not in-memory, there is a potential
39036     ** problem. When the page is next fetched by the b-tree layer, it 
39037     ** will be read from the database file, which may or may not be 
39038     ** current. 
39039     **
39040     ** There are a couple of different ways this can happen. All are quite
39041     ** obscure. When running in synchronous mode, this can only happen 
39042     ** if the page is on the free-list at the start of the transaction, then
39043     ** populated, then moved using sqlite3PagerMovepage().
39044     **
39045     ** The solution is to add an in-memory page to the cache containing
39046     ** the data just read from the sub-journal. Mark the page as dirty 
39047     ** and if the pager requires a journal-sync, then mark the page as 
39048     ** requiring a journal-sync before it is written.
39049     */
39050     assert( isSavepnt );
39051     assert( pPager->doNotSpill==0 );
39052     pPager->doNotSpill++;
39053     rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
39054     assert( pPager->doNotSpill==1 );
39055     pPager->doNotSpill--;
39056     if( rc!=SQLITE_OK ) return rc;
39057     pPg->flags &= ~PGHDR_NEED_READ;
39058     sqlite3PcacheMakeDirty(pPg);
39059   }
39060   if( pPg ){
39061     /* No page should ever be explicitly rolled back that is in use, except
39062     ** for page 1 which is held in use in order to keep the lock on the
39063     ** database active. However such a page may be rolled back as a result
39064     ** of an internal error resulting in an automatic call to
39065     ** sqlite3PagerRollback().
39066     */
39067     void *pData;
39068     pData = pPg->pData;
39069     memcpy(pData, (u8*)aData, pPager->pageSize);
39070     pPager->xReiniter(pPg);
39071     if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
39072       /* If the contents of this page were just restored from the main 
39073       ** journal file, then its content must be as they were when the 
39074       ** transaction was first opened. In this case we can mark the page
39075       ** as clean, since there will be no need to write it out to the
39076       ** database.
39077       **
39078       ** There is one exception to this rule. If the page is being rolled
39079       ** back as part of a savepoint (or statement) rollback from an 
39080       ** unsynced portion of the main journal file, then it is not safe
39081       ** to mark the page as clean. This is because marking the page as
39082       ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
39083       ** already in the journal file (recorded in Pager.pInJournal) and
39084       ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
39085       ** again within this transaction, it will be marked as dirty but
39086       ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
39087       ** be written out into the database file before its journal file
39088       ** segment is synced. If a crash occurs during or following this,
39089       ** database corruption may ensue.
39090       */
39091       assert( !pagerUseWal(pPager) );
39092       sqlite3PcacheMakeClean(pPg);
39093     }
39094     pager_set_pagehash(pPg);
39095
39096     /* If this was page 1, then restore the value of Pager.dbFileVers.
39097     ** Do this before any decoding. */
39098     if( pgno==1 ){
39099       memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
39100     }
39101
39102     /* Decode the page just read from disk */
39103     CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
39104     sqlite3PcacheRelease(pPg);
39105   }
39106   return rc;
39107 }
39108
39109 /*
39110 ** Parameter zMaster is the name of a master journal file. A single journal
39111 ** file that referred to the master journal file has just been rolled back.
39112 ** This routine checks if it is possible to delete the master journal file,
39113 ** and does so if it is.
39114 **
39115 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not 
39116 ** available for use within this function.
39117 **
39118 ** When a master journal file is created, it is populated with the names 
39119 ** of all of its child journals, one after another, formatted as utf-8 
39120 ** encoded text. The end of each child journal file is marked with a 
39121 ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
39122 ** file for a transaction involving two databases might be:
39123 **
39124 **   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
39125 **
39126 ** A master journal file may only be deleted once all of its child 
39127 ** journals have been rolled back.
39128 **
39129 ** This function reads the contents of the master-journal file into 
39130 ** memory and loops through each of the child journal names. For
39131 ** each child journal, it checks if:
39132 **
39133 **   * if the child journal exists, and if so
39134 **   * if the child journal contains a reference to master journal 
39135 **     file zMaster
39136 **
39137 ** If a child journal can be found that matches both of the criteria
39138 ** above, this function returns without doing anything. Otherwise, if
39139 ** no such child journal can be found, file zMaster is deleted from
39140 ** the file-system using sqlite3OsDelete().
39141 **
39142 ** If an IO error within this function, an error code is returned. This
39143 ** function allocates memory by calling sqlite3Malloc(). If an allocation
39144 ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors 
39145 ** occur, SQLITE_OK is returned.
39146 **
39147 ** TODO: This function allocates a single block of memory to load
39148 ** the entire contents of the master journal file. This could be
39149 ** a couple of kilobytes or so - potentially larger than the page 
39150 ** size.
39151 */
39152 static int pager_delmaster(Pager *pPager, const char *zMaster){
39153   sqlite3_vfs *pVfs = pPager->pVfs;
39154   int rc;                   /* Return code */
39155   sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
39156   sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
39157   char *zMasterJournal = 0; /* Contents of master journal file */
39158   i64 nMasterJournal;       /* Size of master journal file */
39159   char *zJournal;           /* Pointer to one journal within MJ file */
39160   char *zMasterPtr;         /* Space to hold MJ filename from a journal file */
39161   int nMasterPtr;           /* Amount of space allocated to zMasterPtr[] */
39162
39163   /* Allocate space for both the pJournal and pMaster file descriptors.
39164   ** If successful, open the master journal file for reading.
39165   */
39166   pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
39167   pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
39168   if( !pMaster ){
39169     rc = SQLITE_NOMEM;
39170   }else{
39171     const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
39172     rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
39173   }
39174   if( rc!=SQLITE_OK ) goto delmaster_out;
39175
39176   /* Load the entire master journal file into space obtained from
39177   ** sqlite3_malloc() and pointed to by zMasterJournal.   Also obtain
39178   ** sufficient space (in zMasterPtr) to hold the names of master
39179   ** journal files extracted from regular rollback-journals.
39180   */
39181   rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
39182   if( rc!=SQLITE_OK ) goto delmaster_out;
39183   nMasterPtr = pVfs->mxPathname+1;
39184   zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
39185   if( !zMasterJournal ){
39186     rc = SQLITE_NOMEM;
39187     goto delmaster_out;
39188   }
39189   zMasterPtr = &zMasterJournal[nMasterJournal+1];
39190   rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
39191   if( rc!=SQLITE_OK ) goto delmaster_out;
39192   zMasterJournal[nMasterJournal] = 0;
39193
39194   zJournal = zMasterJournal;
39195   while( (zJournal-zMasterJournal)<nMasterJournal ){
39196     int exists;
39197     rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
39198     if( rc!=SQLITE_OK ){
39199       goto delmaster_out;
39200     }
39201     if( exists ){
39202       /* One of the journals pointed to by the master journal exists.
39203       ** Open it and check if it points at the master journal. If
39204       ** so, return without deleting the master journal file.
39205       */
39206       int c;
39207       int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
39208       rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
39209       if( rc!=SQLITE_OK ){
39210         goto delmaster_out;
39211       }
39212
39213       rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
39214       sqlite3OsClose(pJournal);
39215       if( rc!=SQLITE_OK ){
39216         goto delmaster_out;
39217       }
39218
39219       c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
39220       if( c ){
39221         /* We have a match. Do not delete the master journal file. */
39222         goto delmaster_out;
39223       }
39224     }
39225     zJournal += (sqlite3Strlen30(zJournal)+1);
39226   }
39227  
39228   sqlite3OsClose(pMaster);
39229   rc = sqlite3OsDelete(pVfs, zMaster, 0);
39230
39231 delmaster_out:
39232   sqlite3_free(zMasterJournal);
39233   if( pMaster ){
39234     sqlite3OsClose(pMaster);
39235     assert( !isOpen(pJournal) );
39236     sqlite3_free(pMaster);
39237   }
39238   return rc;
39239 }
39240
39241
39242 /*
39243 ** This function is used to change the actual size of the database 
39244 ** file in the file-system. This only happens when committing a transaction,
39245 ** or rolling back a transaction (including rolling back a hot-journal).
39246 **
39247 ** If the main database file is not open, or the pager is not in either
39248 ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size 
39249 ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes). 
39250 ** If the file on disk is currently larger than nPage pages, then use the VFS
39251 ** xTruncate() method to truncate it.
39252 **
39253 ** Or, it might might be the case that the file on disk is smaller than 
39254 ** nPage pages. Some operating system implementations can get confused if 
39255 ** you try to truncate a file to some size that is larger than it 
39256 ** currently is, so detect this case and write a single zero byte to 
39257 ** the end of the new file instead.
39258 **
39259 ** If successful, return SQLITE_OK. If an IO error occurs while modifying
39260 ** the database file, return the error code to the caller.
39261 */
39262 static int pager_truncate(Pager *pPager, Pgno nPage){
39263   int rc = SQLITE_OK;
39264   assert( pPager->eState!=PAGER_ERROR );
39265   assert( pPager->eState!=PAGER_READER );
39266   
39267   if( isOpen(pPager->fd) 
39268    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN) 
39269   ){
39270     i64 currentSize, newSize;
39271     int szPage = pPager->pageSize;
39272     assert( pPager->eLock==EXCLUSIVE_LOCK );
39273     /* TODO: Is it safe to use Pager.dbFileSize here? */
39274     rc = sqlite3OsFileSize(pPager->fd, &currentSize);
39275     newSize = szPage*(i64)nPage;
39276     if( rc==SQLITE_OK && currentSize!=newSize ){
39277       if( currentSize>newSize ){
39278         rc = sqlite3OsTruncate(pPager->fd, newSize);
39279       }else{
39280         char *pTmp = pPager->pTmpSpace;
39281         memset(pTmp, 0, szPage);
39282         testcase( (newSize-szPage) <  currentSize );
39283         testcase( (newSize-szPage) == currentSize );
39284         testcase( (newSize-szPage) >  currentSize );
39285         rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
39286       }
39287       if( rc==SQLITE_OK ){
39288         pPager->dbFileSize = nPage;
39289       }
39290     }
39291   }
39292   return rc;
39293 }
39294
39295 /*
39296 ** Set the value of the Pager.sectorSize variable for the given
39297 ** pager based on the value returned by the xSectorSize method
39298 ** of the open database file. The sector size will be used used 
39299 ** to determine the size and alignment of journal header and 
39300 ** master journal pointers within created journal files.
39301 **
39302 ** For temporary files the effective sector size is always 512 bytes.
39303 **
39304 ** Otherwise, for non-temporary files, the effective sector size is
39305 ** the value returned by the xSectorSize() method rounded up to 32 if
39306 ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
39307 ** is greater than MAX_SECTOR_SIZE.
39308 */
39309 static void setSectorSize(Pager *pPager){
39310   assert( isOpen(pPager->fd) || pPager->tempFile );
39311
39312   if( !pPager->tempFile ){
39313     /* Sector size doesn't matter for temporary files. Also, the file
39314     ** may not have been opened yet, in which case the OsSectorSize()
39315     ** call will segfault.
39316     */
39317     pPager->sectorSize = sqlite3OsSectorSize(pPager->fd);
39318   }
39319   if( pPager->sectorSize<32 ){
39320     pPager->sectorSize = 512;
39321   }
39322   if( pPager->sectorSize>MAX_SECTOR_SIZE ){
39323     assert( MAX_SECTOR_SIZE>=512 );
39324     pPager->sectorSize = MAX_SECTOR_SIZE;
39325   }
39326 }
39327
39328 /*
39329 ** Playback the journal and thus restore the database file to
39330 ** the state it was in before we started making changes.  
39331 **
39332 ** The journal file format is as follows: 
39333 **
39334 **  (1)  8 byte prefix.  A copy of aJournalMagic[].
39335 **  (2)  4 byte big-endian integer which is the number of valid page records
39336 **       in the journal.  If this value is 0xffffffff, then compute the
39337 **       number of page records from the journal size.
39338 **  (3)  4 byte big-endian integer which is the initial value for the 
39339 **       sanity checksum.
39340 **  (4)  4 byte integer which is the number of pages to truncate the
39341 **       database to during a rollback.
39342 **  (5)  4 byte big-endian integer which is the sector size.  The header
39343 **       is this many bytes in size.
39344 **  (6)  4 byte big-endian integer which is the page size.
39345 **  (7)  zero padding out to the next sector size.
39346 **  (8)  Zero or more pages instances, each as follows:
39347 **        +  4 byte page number.
39348 **        +  pPager->pageSize bytes of data.
39349 **        +  4 byte checksum
39350 **
39351 ** When we speak of the journal header, we mean the first 7 items above.
39352 ** Each entry in the journal is an instance of the 8th item.
39353 **
39354 ** Call the value from the second bullet "nRec".  nRec is the number of
39355 ** valid page entries in the journal.  In most cases, you can compute the
39356 ** value of nRec from the size of the journal file.  But if a power
39357 ** failure occurred while the journal was being written, it could be the
39358 ** case that the size of the journal file had already been increased but
39359 ** the extra entries had not yet made it safely to disk.  In such a case,
39360 ** the value of nRec computed from the file size would be too large.  For
39361 ** that reason, we always use the nRec value in the header.
39362 **
39363 ** If the nRec value is 0xffffffff it means that nRec should be computed
39364 ** from the file size.  This value is used when the user selects the
39365 ** no-sync option for the journal.  A power failure could lead to corruption
39366 ** in this case.  But for things like temporary table (which will be
39367 ** deleted when the power is restored) we don't care.  
39368 **
39369 ** If the file opened as the journal file is not a well-formed
39370 ** journal file then all pages up to the first corrupted page are rolled
39371 ** back (or no pages if the journal header is corrupted). The journal file
39372 ** is then deleted and SQLITE_OK returned, just as if no corruption had
39373 ** been encountered.
39374 **
39375 ** If an I/O or malloc() error occurs, the journal-file is not deleted
39376 ** and an error code is returned.
39377 **
39378 ** The isHot parameter indicates that we are trying to rollback a journal
39379 ** that might be a hot journal.  Or, it could be that the journal is 
39380 ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
39381 ** If the journal really is hot, reset the pager cache prior rolling
39382 ** back any content.  If the journal is merely persistent, no reset is
39383 ** needed.
39384 */
39385 static int pager_playback(Pager *pPager, int isHot){
39386   sqlite3_vfs *pVfs = pPager->pVfs;
39387   i64 szJ;                 /* Size of the journal file in bytes */
39388   u32 nRec;                /* Number of Records in the journal */
39389   u32 u;                   /* Unsigned loop counter */
39390   Pgno mxPg = 0;           /* Size of the original file in pages */
39391   int rc;                  /* Result code of a subroutine */
39392   int res = 1;             /* Value returned by sqlite3OsAccess() */
39393   char *zMaster = 0;       /* Name of master journal file if any */
39394   int needPagerReset;      /* True to reset page prior to first page rollback */
39395
39396   /* Figure out how many records are in the journal.  Abort early if
39397   ** the journal is empty.
39398   */
39399   assert( isOpen(pPager->jfd) );
39400   rc = sqlite3OsFileSize(pPager->jfd, &szJ);
39401   if( rc!=SQLITE_OK ){
39402     goto end_playback;
39403   }
39404
39405   /* Read the master journal name from the journal, if it is present.
39406   ** If a master journal file name is specified, but the file is not
39407   ** present on disk, then the journal is not hot and does not need to be
39408   ** played back.
39409   **
39410   ** TODO: Technically the following is an error because it assumes that
39411   ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
39412   ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
39413   **  mxPathname is 512, which is the same as the minimum allowable value
39414   ** for pageSize.
39415   */
39416   zMaster = pPager->pTmpSpace;
39417   rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
39418   if( rc==SQLITE_OK && zMaster[0] ){
39419     rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
39420   }
39421   zMaster = 0;
39422   if( rc!=SQLITE_OK || !res ){
39423     goto end_playback;
39424   }
39425   pPager->journalOff = 0;
39426   needPagerReset = isHot;
39427
39428   /* This loop terminates either when a readJournalHdr() or 
39429   ** pager_playback_one_page() call returns SQLITE_DONE or an IO error 
39430   ** occurs. 
39431   */
39432   while( 1 ){
39433     /* Read the next journal header from the journal file.  If there are
39434     ** not enough bytes left in the journal file for a complete header, or
39435     ** it is corrupted, then a process must have failed while writing it.
39436     ** This indicates nothing more needs to be rolled back.
39437     */
39438     rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
39439     if( rc!=SQLITE_OK ){ 
39440       if( rc==SQLITE_DONE ){
39441         rc = SQLITE_OK;
39442       }
39443       goto end_playback;
39444     }
39445
39446     /* If nRec is 0xffffffff, then this journal was created by a process
39447     ** working in no-sync mode. This means that the rest of the journal
39448     ** file consists of pages, there are no more journal headers. Compute
39449     ** the value of nRec based on this assumption.
39450     */
39451     if( nRec==0xffffffff ){
39452       assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
39453       nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
39454     }
39455
39456     /* If nRec is 0 and this rollback is of a transaction created by this
39457     ** process and if this is the final header in the journal, then it means
39458     ** that this part of the journal was being filled but has not yet been
39459     ** synced to disk.  Compute the number of pages based on the remaining
39460     ** size of the file.
39461     **
39462     ** The third term of the test was added to fix ticket #2565.
39463     ** When rolling back a hot journal, nRec==0 always means that the next
39464     ** chunk of the journal contains zero pages to be rolled back.  But
39465     ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
39466     ** the journal, it means that the journal might contain additional
39467     ** pages that need to be rolled back and that the number of pages 
39468     ** should be computed based on the journal file size.
39469     */
39470     if( nRec==0 && !isHot &&
39471         pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
39472       nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
39473     }
39474
39475     /* If this is the first header read from the journal, truncate the
39476     ** database file back to its original size.
39477     */
39478     if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
39479       rc = pager_truncate(pPager, mxPg);
39480       if( rc!=SQLITE_OK ){
39481         goto end_playback;
39482       }
39483       pPager->dbSize = mxPg;
39484     }
39485
39486     /* Copy original pages out of the journal and back into the 
39487     ** database file and/or page cache.
39488     */
39489     for(u=0; u<nRec; u++){
39490       if( needPagerReset ){
39491         pager_reset(pPager);
39492         needPagerReset = 0;
39493       }
39494       rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
39495       if( rc!=SQLITE_OK ){
39496         if( rc==SQLITE_DONE ){
39497           rc = SQLITE_OK;
39498           pPager->journalOff = szJ;
39499           break;
39500         }else if( rc==SQLITE_IOERR_SHORT_READ ){
39501           /* If the journal has been truncated, simply stop reading and
39502           ** processing the journal. This might happen if the journal was
39503           ** not completely written and synced prior to a crash.  In that
39504           ** case, the database should have never been written in the
39505           ** first place so it is OK to simply abandon the rollback. */
39506           rc = SQLITE_OK;
39507           goto end_playback;
39508         }else{
39509           /* If we are unable to rollback, quit and return the error
39510           ** code.  This will cause the pager to enter the error state
39511           ** so that no further harm will be done.  Perhaps the next
39512           ** process to come along will be able to rollback the database.
39513           */
39514           goto end_playback;
39515         }
39516       }
39517     }
39518   }
39519   /*NOTREACHED*/
39520   assert( 0 );
39521
39522 end_playback:
39523   /* Following a rollback, the database file should be back in its original
39524   ** state prior to the start of the transaction, so invoke the
39525   ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
39526   ** assertion that the transaction counter was modified.
39527   */
39528   assert(
39529     pPager->fd->pMethods==0 ||
39530     sqlite3OsFileControl(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0)>=SQLITE_OK
39531   );
39532
39533   /* If this playback is happening automatically as a result of an IO or 
39534   ** malloc error that occurred after the change-counter was updated but 
39535   ** before the transaction was committed, then the change-counter 
39536   ** modification may just have been reverted. If this happens in exclusive 
39537   ** mode, then subsequent transactions performed by the connection will not
39538   ** update the change-counter at all. This may lead to cache inconsistency
39539   ** problems for other processes at some point in the future. So, just
39540   ** in case this has happened, clear the changeCountDone flag now.
39541   */
39542   pPager->changeCountDone = pPager->tempFile;
39543
39544   if( rc==SQLITE_OK ){
39545     zMaster = pPager->pTmpSpace;
39546     rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
39547     testcase( rc!=SQLITE_OK );
39548   }
39549   if( rc==SQLITE_OK
39550    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
39551   ){
39552     rc = sqlite3PagerSync(pPager);
39553   }
39554   if( rc==SQLITE_OK ){
39555     rc = pager_end_transaction(pPager, zMaster[0]!='\0');
39556     testcase( rc!=SQLITE_OK );
39557   }
39558   if( rc==SQLITE_OK && zMaster[0] && res ){
39559     /* If there was a master journal and this routine will return success,
39560     ** see if it is possible to delete the master journal.
39561     */
39562     rc = pager_delmaster(pPager, zMaster);
39563     testcase( rc!=SQLITE_OK );
39564   }
39565
39566   /* The Pager.sectorSize variable may have been updated while rolling
39567   ** back a journal created by a process with a different sector size
39568   ** value. Reset it to the correct value for this process.
39569   */
39570   setSectorSize(pPager);
39571   return rc;
39572 }
39573
39574
39575 /*
39576 ** Read the content for page pPg out of the database file and into 
39577 ** pPg->pData. A shared lock or greater must be held on the database
39578 ** file before this function is called.
39579 **
39580 ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
39581 ** the value read from the database file.
39582 **
39583 ** If an IO error occurs, then the IO error is returned to the caller.
39584 ** Otherwise, SQLITE_OK is returned.
39585 */
39586 static int readDbPage(PgHdr *pPg){
39587   Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
39588   Pgno pgno = pPg->pgno;       /* Page number to read */
39589   int rc = SQLITE_OK;          /* Return code */
39590   int isInWal = 0;             /* True if page is in log file */
39591   int pgsz = pPager->pageSize; /* Number of bytes to read */
39592
39593   assert( pPager->eState>=PAGER_READER && !MEMDB );
39594   assert( isOpen(pPager->fd) );
39595
39596   if( NEVER(!isOpen(pPager->fd)) ){
39597     assert( pPager->tempFile );
39598     memset(pPg->pData, 0, pPager->pageSize);
39599     return SQLITE_OK;
39600   }
39601
39602   if( pagerUseWal(pPager) ){
39603     /* Try to pull the page from the write-ahead log. */
39604     rc = sqlite3WalRead(pPager->pWal, pgno, &isInWal, pgsz, pPg->pData);
39605   }
39606   if( rc==SQLITE_OK && !isInWal ){
39607     i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
39608     rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
39609     if( rc==SQLITE_IOERR_SHORT_READ ){
39610       rc = SQLITE_OK;
39611     }
39612   }
39613
39614   if( pgno==1 ){
39615     if( rc ){
39616       /* If the read is unsuccessful, set the dbFileVers[] to something
39617       ** that will never be a valid file version.  dbFileVers[] is a copy
39618       ** of bytes 24..39 of the database.  Bytes 28..31 should always be
39619       ** zero or the size of the database in page. Bytes 32..35 and 35..39
39620       ** should be page numbers which are never 0xffffffff.  So filling
39621       ** pPager->dbFileVers[] with all 0xff bytes should suffice.
39622       **
39623       ** For an encrypted database, the situation is more complex:  bytes
39624       ** 24..39 of the database are white noise.  But the probability of
39625       ** white noising equaling 16 bytes of 0xff is vanishingly small so
39626       ** we should still be ok.
39627       */
39628       memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
39629     }else{
39630       u8 *dbFileVers = &((u8*)pPg->pData)[24];
39631       memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
39632     }
39633   }
39634   CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
39635
39636   PAGER_INCR(sqlite3_pager_readdb_count);
39637   PAGER_INCR(pPager->nRead);
39638   IOTRACE(("PGIN %p %d\n", pPager, pgno));
39639   PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
39640                PAGERID(pPager), pgno, pager_pagehash(pPg)));
39641
39642   return rc;
39643 }
39644
39645 /*
39646 ** Update the value of the change-counter at offsets 24 and 92 in
39647 ** the header and the sqlite version number at offset 96.
39648 **
39649 ** This is an unconditional update.  See also the pager_incr_changecounter()
39650 ** routine which only updates the change-counter if the update is actually
39651 ** needed, as determined by the pPager->changeCountDone state variable.
39652 */
39653 static void pager_write_changecounter(PgHdr *pPg){
39654   u32 change_counter;
39655
39656   /* Increment the value just read and write it back to byte 24. */
39657   change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
39658   put32bits(((char*)pPg->pData)+24, change_counter);
39659
39660   /* Also store the SQLite version number in bytes 96..99 and in
39661   ** bytes 92..95 store the change counter for which the version number
39662   ** is valid. */
39663   put32bits(((char*)pPg->pData)+92, change_counter);
39664   put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
39665 }
39666
39667 #ifndef SQLITE_OMIT_WAL
39668 /*
39669 ** This function is invoked once for each page that has already been 
39670 ** written into the log file when a WAL transaction is rolled back.
39671 ** Parameter iPg is the page number of said page. The pCtx argument 
39672 ** is actually a pointer to the Pager structure.
39673 **
39674 ** If page iPg is present in the cache, and has no outstanding references,
39675 ** it is discarded. Otherwise, if there are one or more outstanding
39676 ** references, the page content is reloaded from the database. If the
39677 ** attempt to reload content from the database is required and fails, 
39678 ** return an SQLite error code. Otherwise, SQLITE_OK.
39679 */
39680 static int pagerUndoCallback(void *pCtx, Pgno iPg){
39681   int rc = SQLITE_OK;
39682   Pager *pPager = (Pager *)pCtx;
39683   PgHdr *pPg;
39684
39685   pPg = sqlite3PagerLookup(pPager, iPg);
39686   if( pPg ){
39687     if( sqlite3PcachePageRefcount(pPg)==1 ){
39688       sqlite3PcacheDrop(pPg);
39689     }else{
39690       rc = readDbPage(pPg);
39691       if( rc==SQLITE_OK ){
39692         pPager->xReiniter(pPg);
39693       }
39694       sqlite3PagerUnref(pPg);
39695     }
39696   }
39697
39698   /* Normally, if a transaction is rolled back, any backup processes are
39699   ** updated as data is copied out of the rollback journal and into the
39700   ** database. This is not generally possible with a WAL database, as
39701   ** rollback involves simply truncating the log file. Therefore, if one
39702   ** or more frames have already been written to the log (and therefore 
39703   ** also copied into the backup databases) as part of this transaction,
39704   ** the backups must be restarted.
39705   */
39706   sqlite3BackupRestart(pPager->pBackup);
39707
39708   return rc;
39709 }
39710
39711 /*
39712 ** This function is called to rollback a transaction on a WAL database.
39713 */
39714 static int pagerRollbackWal(Pager *pPager){
39715   int rc;                         /* Return Code */
39716   PgHdr *pList;                   /* List of dirty pages to revert */
39717
39718   /* For all pages in the cache that are currently dirty or have already
39719   ** been written (but not committed) to the log file, do one of the 
39720   ** following:
39721   **
39722   **   + Discard the cached page (if refcount==0), or
39723   **   + Reload page content from the database (if refcount>0).
39724   */
39725   pPager->dbSize = pPager->dbOrigSize;
39726   rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
39727   pList = sqlite3PcacheDirtyList(pPager->pPCache);
39728   while( pList && rc==SQLITE_OK ){
39729     PgHdr *pNext = pList->pDirty;
39730     rc = pagerUndoCallback((void *)pPager, pList->pgno);
39731     pList = pNext;
39732   }
39733
39734   return rc;
39735 }
39736
39737 /*
39738 ** This function is a wrapper around sqlite3WalFrames(). As well as logging
39739 ** the contents of the list of pages headed by pList (connected by pDirty),
39740 ** this function notifies any active backup processes that the pages have
39741 ** changed. 
39742 **
39743 ** The list of pages passed into this routine is always sorted by page number.
39744 ** Hence, if page 1 appears anywhere on the list, it will be the first page.
39745 */ 
39746 static int pagerWalFrames(
39747   Pager *pPager,                  /* Pager object */
39748   PgHdr *pList,                   /* List of frames to log */
39749   Pgno nTruncate,                 /* Database size after this commit */
39750   int isCommit,                   /* True if this is a commit */
39751   int syncFlags                   /* Flags to pass to OsSync() (or 0) */
39752 ){
39753   int rc;                         /* Return code */
39754 #if defined(SQLITE_DEBUG) || defined(SQLITE_CHECK_PAGES)
39755   PgHdr *p;                       /* For looping over pages */
39756 #endif
39757
39758   assert( pPager->pWal );
39759 #ifdef SQLITE_DEBUG
39760   /* Verify that the page list is in accending order */
39761   for(p=pList; p && p->pDirty; p=p->pDirty){
39762     assert( p->pgno < p->pDirty->pgno );
39763   }
39764 #endif
39765
39766   if( isCommit ){
39767     /* If a WAL transaction is being committed, there is no point in writing
39768     ** any pages with page numbers greater than nTruncate into the WAL file.
39769     ** They will never be read by any client. So remove them from the pDirty
39770     ** list here. */
39771     PgHdr *p;
39772     PgHdr **ppNext = &pList;
39773     for(p=pList; (*ppNext = p); p=p->pDirty){
39774       if( p->pgno<=nTruncate ) ppNext = &p->pDirty;
39775     }
39776     assert( pList );
39777   }
39778
39779   if( pList->pgno==1 ) pager_write_changecounter(pList);
39780   rc = sqlite3WalFrames(pPager->pWal, 
39781       pPager->pageSize, pList, nTruncate, isCommit, syncFlags
39782   );
39783   if( rc==SQLITE_OK && pPager->pBackup ){
39784     PgHdr *p;
39785     for(p=pList; p; p=p->pDirty){
39786       sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
39787     }
39788   }
39789
39790 #ifdef SQLITE_CHECK_PAGES
39791   pList = sqlite3PcacheDirtyList(pPager->pPCache);
39792   for(p=pList; p; p=p->pDirty){
39793     pager_set_pagehash(p);
39794   }
39795 #endif
39796
39797   return rc;
39798 }
39799
39800 /*
39801 ** Begin a read transaction on the WAL.
39802 **
39803 ** This routine used to be called "pagerOpenSnapshot()" because it essentially
39804 ** makes a snapshot of the database at the current point in time and preserves
39805 ** that snapshot for use by the reader in spite of concurrently changes by
39806 ** other writers or checkpointers.
39807 */
39808 static int pagerBeginReadTransaction(Pager *pPager){
39809   int rc;                         /* Return code */
39810   int changed = 0;                /* True if cache must be reset */
39811
39812   assert( pagerUseWal(pPager) );
39813   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
39814
39815   /* sqlite3WalEndReadTransaction() was not called for the previous
39816   ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we
39817   ** are in locking_mode=NORMAL and EndRead() was previously called,
39818   ** the duplicate call is harmless.
39819   */
39820   sqlite3WalEndReadTransaction(pPager->pWal);
39821
39822   rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
39823   if( rc!=SQLITE_OK || changed ){
39824     pager_reset(pPager);
39825   }
39826
39827   return rc;
39828 }
39829 #endif
39830
39831 /*
39832 ** This function is called as part of the transition from PAGER_OPEN
39833 ** to PAGER_READER state to determine the size of the database file
39834 ** in pages (assuming the page size currently stored in Pager.pageSize).
39835 **
39836 ** If no error occurs, SQLITE_OK is returned and the size of the database
39837 ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
39838 ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
39839 */
39840 static int pagerPagecount(Pager *pPager, Pgno *pnPage){
39841   Pgno nPage;                     /* Value to return via *pnPage */
39842
39843   /* Query the WAL sub-system for the database size. The WalDbsize()
39844   ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
39845   ** if the database size is not available. The database size is not
39846   ** available from the WAL sub-system if the log file is empty or
39847   ** contains no valid committed transactions.
39848   */
39849   assert( pPager->eState==PAGER_OPEN );
39850   assert( pPager->eLock>=SHARED_LOCK || pPager->noReadlock );
39851   nPage = sqlite3WalDbsize(pPager->pWal);
39852
39853   /* If the database size was not available from the WAL sub-system,
39854   ** determine it based on the size of the database file. If the size
39855   ** of the database file is not an integer multiple of the page-size,
39856   ** round down to the nearest page. Except, any file larger than 0
39857   ** bytes in size is considered to contain at least one page.
39858   */
39859   if( nPage==0 ){
39860     i64 n = 0;                    /* Size of db file in bytes */
39861     assert( isOpen(pPager->fd) || pPager->tempFile );
39862     if( isOpen(pPager->fd) ){
39863       int rc = sqlite3OsFileSize(pPager->fd, &n);
39864       if( rc!=SQLITE_OK ){
39865         return rc;
39866       }
39867     }
39868     nPage = (Pgno)(n / pPager->pageSize);
39869     if( nPage==0 && n>0 ){
39870       nPage = 1;
39871     }
39872   }
39873
39874   /* If the current number of pages in the file is greater than the
39875   ** configured maximum pager number, increase the allowed limit so
39876   ** that the file can be read.
39877   */
39878   if( nPage>pPager->mxPgno ){
39879     pPager->mxPgno = (Pgno)nPage;
39880   }
39881
39882   *pnPage = nPage;
39883   return SQLITE_OK;
39884 }
39885
39886 #ifndef SQLITE_OMIT_WAL
39887 /*
39888 ** Check if the *-wal file that corresponds to the database opened by pPager
39889 ** exists if the database is not empy, or verify that the *-wal file does
39890 ** not exist (by deleting it) if the database file is empty.
39891 **
39892 ** If the database is not empty and the *-wal file exists, open the pager
39893 ** in WAL mode.  If the database is empty or if no *-wal file exists and
39894 ** if no error occurs, make sure Pager.journalMode is not set to
39895 ** PAGER_JOURNALMODE_WAL.
39896 **
39897 ** Return SQLITE_OK or an error code.
39898 **
39899 ** The caller must hold a SHARED lock on the database file to call this
39900 ** function. Because an EXCLUSIVE lock on the db file is required to delete 
39901 ** a WAL on a none-empty database, this ensures there is no race condition 
39902 ** between the xAccess() below and an xDelete() being executed by some 
39903 ** other connection.
39904 */
39905 static int pagerOpenWalIfPresent(Pager *pPager){
39906   int rc = SQLITE_OK;
39907   assert( pPager->eState==PAGER_OPEN );
39908   assert( pPager->eLock>=SHARED_LOCK || pPager->noReadlock );
39909
39910   if( !pPager->tempFile ){
39911     int isWal;                    /* True if WAL file exists */
39912     Pgno nPage;                   /* Size of the database file */
39913
39914     rc = pagerPagecount(pPager, &nPage);
39915     if( rc ) return rc;
39916     if( nPage==0 ){
39917       rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
39918       isWal = 0;
39919     }else{
39920       rc = sqlite3OsAccess(
39921           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
39922       );
39923     }
39924     if( rc==SQLITE_OK ){
39925       if( isWal ){
39926         testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
39927         rc = sqlite3PagerOpenWal(pPager, 0);
39928       }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
39929         pPager->journalMode = PAGER_JOURNALMODE_DELETE;
39930       }
39931     }
39932   }
39933   return rc;
39934 }
39935 #endif
39936
39937 /*
39938 ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
39939 ** the entire master journal file. The case pSavepoint==NULL occurs when 
39940 ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction 
39941 ** savepoint.
39942 **
39943 ** When pSavepoint is not NULL (meaning a non-transaction savepoint is 
39944 ** being rolled back), then the rollback consists of up to three stages,
39945 ** performed in the order specified:
39946 **
39947 **   * Pages are played back from the main journal starting at byte
39948 **     offset PagerSavepoint.iOffset and continuing to 
39949 **     PagerSavepoint.iHdrOffset, or to the end of the main journal
39950 **     file if PagerSavepoint.iHdrOffset is zero.
39951 **
39952 **   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
39953 **     back starting from the journal header immediately following 
39954 **     PagerSavepoint.iHdrOffset to the end of the main journal file.
39955 **
39956 **   * Pages are then played back from the sub-journal file, starting
39957 **     with the PagerSavepoint.iSubRec and continuing to the end of
39958 **     the journal file.
39959 **
39960 ** Throughout the rollback process, each time a page is rolled back, the
39961 ** corresponding bit is set in a bitvec structure (variable pDone in the
39962 ** implementation below). This is used to ensure that a page is only
39963 ** rolled back the first time it is encountered in either journal.
39964 **
39965 ** If pSavepoint is NULL, then pages are only played back from the main
39966 ** journal file. There is no need for a bitvec in this case.
39967 **
39968 ** In either case, before playback commences the Pager.dbSize variable
39969 ** is reset to the value that it held at the start of the savepoint 
39970 ** (or transaction). No page with a page-number greater than this value
39971 ** is played back. If one is encountered it is simply skipped.
39972 */
39973 static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
39974   i64 szJ;                 /* Effective size of the main journal */
39975   i64 iHdrOff;             /* End of first segment of main-journal records */
39976   int rc = SQLITE_OK;      /* Return code */
39977   Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
39978
39979   assert( pPager->eState!=PAGER_ERROR );
39980   assert( pPager->eState>=PAGER_WRITER_LOCKED );
39981
39982   /* Allocate a bitvec to use to store the set of pages rolled back */
39983   if( pSavepoint ){
39984     pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
39985     if( !pDone ){
39986       return SQLITE_NOMEM;
39987     }
39988   }
39989
39990   /* Set the database size back to the value it was before the savepoint 
39991   ** being reverted was opened.
39992   */
39993   pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
39994   pPager->changeCountDone = pPager->tempFile;
39995
39996   if( !pSavepoint && pagerUseWal(pPager) ){
39997     return pagerRollbackWal(pPager);
39998   }
39999
40000   /* Use pPager->journalOff as the effective size of the main rollback
40001   ** journal.  The actual file might be larger than this in
40002   ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
40003   ** past pPager->journalOff is off-limits to us.
40004   */
40005   szJ = pPager->journalOff;
40006   assert( pagerUseWal(pPager)==0 || szJ==0 );
40007
40008   /* Begin by rolling back records from the main journal starting at
40009   ** PagerSavepoint.iOffset and continuing to the next journal header.
40010   ** There might be records in the main journal that have a page number
40011   ** greater than the current database size (pPager->dbSize) but those
40012   ** will be skipped automatically.  Pages are added to pDone as they
40013   ** are played back.
40014   */
40015   if( pSavepoint && !pagerUseWal(pPager) ){
40016     iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
40017     pPager->journalOff = pSavepoint->iOffset;
40018     while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
40019       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
40020     }
40021     assert( rc!=SQLITE_DONE );
40022   }else{
40023     pPager->journalOff = 0;
40024   }
40025
40026   /* Continue rolling back records out of the main journal starting at
40027   ** the first journal header seen and continuing until the effective end
40028   ** of the main journal file.  Continue to skip out-of-range pages and
40029   ** continue adding pages rolled back to pDone.
40030   */
40031   while( rc==SQLITE_OK && pPager->journalOff<szJ ){
40032     u32 ii;            /* Loop counter */
40033     u32 nJRec = 0;     /* Number of Journal Records */
40034     u32 dummy;
40035     rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
40036     assert( rc!=SQLITE_DONE );
40037
40038     /*
40039     ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
40040     ** test is related to ticket #2565.  See the discussion in the
40041     ** pager_playback() function for additional information.
40042     */
40043     if( nJRec==0 
40044      && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
40045     ){
40046       nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
40047     }
40048     for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
40049       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
40050     }
40051     assert( rc!=SQLITE_DONE );
40052   }
40053   assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
40054
40055   /* Finally,  rollback pages from the sub-journal.  Page that were
40056   ** previously rolled back out of the main journal (and are hence in pDone)
40057   ** will be skipped.  Out-of-range pages are also skipped.
40058   */
40059   if( pSavepoint ){
40060     u32 ii;            /* Loop counter */
40061     i64 offset = pSavepoint->iSubRec*(4+pPager->pageSize);
40062
40063     if( pagerUseWal(pPager) ){
40064       rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
40065     }
40066     for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
40067       assert( offset==ii*(4+pPager->pageSize) );
40068       rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
40069     }
40070     assert( rc!=SQLITE_DONE );
40071   }
40072
40073   sqlite3BitvecDestroy(pDone);
40074   if( rc==SQLITE_OK ){
40075     pPager->journalOff = szJ;
40076   }
40077
40078   return rc;
40079 }
40080
40081 /*
40082 ** Change the maximum number of in-memory pages that are allowed.
40083 */
40084 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
40085   sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
40086 }
40087
40088 /*
40089 ** Adjust the robustness of the database to damage due to OS crashes
40090 ** or power failures by changing the number of syncs()s when writing
40091 ** the rollback journal.  There are three levels:
40092 **
40093 **    OFF       sqlite3OsSync() is never called.  This is the default
40094 **              for temporary and transient files.
40095 **
40096 **    NORMAL    The journal is synced once before writes begin on the
40097 **              database.  This is normally adequate protection, but
40098 **              it is theoretically possible, though very unlikely,
40099 **              that an inopertune power failure could leave the journal
40100 **              in a state which would cause damage to the database
40101 **              when it is rolled back.
40102 **
40103 **    FULL      The journal is synced twice before writes begin on the
40104 **              database (with some additional information - the nRec field
40105 **              of the journal header - being written in between the two
40106 **              syncs).  If we assume that writing a
40107 **              single disk sector is atomic, then this mode provides
40108 **              assurance that the journal will not be corrupted to the
40109 **              point of causing damage to the database during rollback.
40110 **
40111 ** The above is for a rollback-journal mode.  For WAL mode, OFF continues
40112 ** to mean that no syncs ever occur.  NORMAL means that the WAL is synced
40113 ** prior to the start of checkpoint and that the database file is synced
40114 ** at the conclusion of the checkpoint if the entire content of the WAL
40115 ** was written back into the database.  But no sync operations occur for
40116 ** an ordinary commit in NORMAL mode with WAL.  FULL means that the WAL
40117 ** file is synced following each commit operation, in addition to the
40118 ** syncs associated with NORMAL.
40119 **
40120 ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL.  The
40121 ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
40122 ** using fcntl(F_FULLFSYNC).  SQLITE_SYNC_NORMAL means to do an
40123 ** ordinary fsync() call.  There is no difference between SQLITE_SYNC_FULL
40124 ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX.  But the
40125 ** synchronous=FULL versus synchronous=NORMAL setting determines when
40126 ** the xSync primitive is called and is relevant to all platforms.
40127 **
40128 ** Numeric values associated with these states are OFF==1, NORMAL=2,
40129 ** and FULL=3.
40130 */
40131 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
40132 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(
40133   Pager *pPager,        /* The pager to set safety level for */
40134   int level,            /* PRAGMA synchronous.  1=OFF, 2=NORMAL, 3=FULL */  
40135   int bFullFsync,       /* PRAGMA fullfsync */
40136   int bCkptFullFsync    /* PRAGMA checkpoint_fullfsync */
40137 ){
40138   assert( level>=1 && level<=3 );
40139   pPager->noSync =  (level==1 || pPager->tempFile) ?1:0;
40140   pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
40141   if( pPager->noSync ){
40142     pPager->syncFlags = 0;
40143     pPager->ckptSyncFlags = 0;
40144   }else if( bFullFsync ){
40145     pPager->syncFlags = SQLITE_SYNC_FULL;
40146     pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
40147   }else if( bCkptFullFsync ){
40148     pPager->syncFlags = SQLITE_SYNC_NORMAL;
40149     pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
40150   }else{
40151     pPager->syncFlags = SQLITE_SYNC_NORMAL;
40152     pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
40153   }
40154 }
40155 #endif
40156
40157 /*
40158 ** The following global variable is incremented whenever the library
40159 ** attempts to open a temporary file.  This information is used for
40160 ** testing and analysis only.  
40161 */
40162 #ifdef SQLITE_TEST
40163 SQLITE_API int sqlite3_opentemp_count = 0;
40164 #endif
40165
40166 /*
40167 ** Open a temporary file.
40168 **
40169 ** Write the file descriptor into *pFile. Return SQLITE_OK on success 
40170 ** or some other error code if we fail. The OS will automatically 
40171 ** delete the temporary file when it is closed.
40172 **
40173 ** The flags passed to the VFS layer xOpen() call are those specified
40174 ** by parameter vfsFlags ORed with the following:
40175 **
40176 **     SQLITE_OPEN_READWRITE
40177 **     SQLITE_OPEN_CREATE
40178 **     SQLITE_OPEN_EXCLUSIVE
40179 **     SQLITE_OPEN_DELETEONCLOSE
40180 */
40181 static int pagerOpentemp(
40182   Pager *pPager,        /* The pager object */
40183   sqlite3_file *pFile,  /* Write the file descriptor here */
40184   int vfsFlags          /* Flags passed through to the VFS */
40185 ){
40186   int rc;               /* Return code */
40187
40188 #ifdef SQLITE_TEST
40189   sqlite3_opentemp_count++;  /* Used for testing and analysis only */
40190 #endif
40191
40192   vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
40193             SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
40194   rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
40195   assert( rc!=SQLITE_OK || isOpen(pFile) );
40196   return rc;
40197 }
40198
40199 /*
40200 ** Set the busy handler function.
40201 **
40202 ** The pager invokes the busy-handler if sqlite3OsLock() returns 
40203 ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
40204 ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE 
40205 ** lock. It does *not* invoke the busy handler when upgrading from
40206 ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
40207 ** (which occurs during hot-journal rollback). Summary:
40208 **
40209 **   Transition                        | Invokes xBusyHandler
40210 **   --------------------------------------------------------
40211 **   NO_LOCK       -> SHARED_LOCK      | Yes
40212 **   SHARED_LOCK   -> RESERVED_LOCK    | No
40213 **   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
40214 **   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
40215 **
40216 ** If the busy-handler callback returns non-zero, the lock is 
40217 ** retried. If it returns zero, then the SQLITE_BUSY error is
40218 ** returned to the caller of the pager API function.
40219 */
40220 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
40221   Pager *pPager,                       /* Pager object */
40222   int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
40223   void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
40224 ){  
40225   pPager->xBusyHandler = xBusyHandler;
40226   pPager->pBusyHandlerArg = pBusyHandlerArg;
40227 }
40228
40229 /*
40230 ** Change the page size used by the Pager object. The new page size 
40231 ** is passed in *pPageSize.
40232 **
40233 ** If the pager is in the error state when this function is called, it
40234 ** is a no-op. The value returned is the error state error code (i.e. 
40235 ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
40236 **
40237 ** Otherwise, if all of the following are true:
40238 **
40239 **   * the new page size (value of *pPageSize) is valid (a power 
40240 **     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
40241 **
40242 **   * there are no outstanding page references, and
40243 **
40244 **   * the database is either not an in-memory database or it is
40245 **     an in-memory database that currently consists of zero pages.
40246 **
40247 ** then the pager object page size is set to *pPageSize.
40248 **
40249 ** If the page size is changed, then this function uses sqlite3PagerMalloc() 
40250 ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt 
40251 ** fails, SQLITE_NOMEM is returned and the page size remains unchanged. 
40252 ** In all other cases, SQLITE_OK is returned.
40253 **
40254 ** If the page size is not changed, either because one of the enumerated
40255 ** conditions above is not true, the pager was in error state when this
40256 ** function was called, or because the memory allocation attempt failed, 
40257 ** then *pPageSize is set to the old, retained page size before returning.
40258 */
40259 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
40260   int rc = SQLITE_OK;
40261
40262   /* It is not possible to do a full assert_pager_state() here, as this
40263   ** function may be called from within PagerOpen(), before the state
40264   ** of the Pager object is internally consistent.
40265   **
40266   ** At one point this function returned an error if the pager was in 
40267   ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
40268   ** there is at least one outstanding page reference, this function
40269   ** is a no-op for that case anyhow.
40270   */
40271
40272   u32 pageSize = *pPageSize;
40273   assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
40274   if( (pPager->memDb==0 || pPager->dbSize==0)
40275    && sqlite3PcacheRefCount(pPager->pPCache)==0 
40276    && pageSize && pageSize!=(u32)pPager->pageSize 
40277   ){
40278     char *pNew = NULL;             /* New temp space */
40279     i64 nByte = 0;
40280
40281     if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
40282       rc = sqlite3OsFileSize(pPager->fd, &nByte);
40283     }
40284     if( rc==SQLITE_OK ){
40285       pNew = (char *)sqlite3PageMalloc(pageSize);
40286       if( !pNew ) rc = SQLITE_NOMEM;
40287     }
40288
40289     if( rc==SQLITE_OK ){
40290       pager_reset(pPager);
40291       pPager->dbSize = (Pgno)(nByte/pageSize);
40292       pPager->pageSize = pageSize;
40293       sqlite3PageFree(pPager->pTmpSpace);
40294       pPager->pTmpSpace = pNew;
40295       sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
40296     }
40297   }
40298
40299   *pPageSize = pPager->pageSize;
40300   if( rc==SQLITE_OK ){
40301     if( nReserve<0 ) nReserve = pPager->nReserve;
40302     assert( nReserve>=0 && nReserve<1000 );
40303     pPager->nReserve = (i16)nReserve;
40304     pagerReportSize(pPager);
40305   }
40306   return rc;
40307 }
40308
40309 /*
40310 ** Return a pointer to the "temporary page" buffer held internally
40311 ** by the pager.  This is a buffer that is big enough to hold the
40312 ** entire content of a database page.  This buffer is used internally
40313 ** during rollback and will be overwritten whenever a rollback
40314 ** occurs.  But other modules are free to use it too, as long as
40315 ** no rollbacks are happening.
40316 */
40317 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
40318   return pPager->pTmpSpace;
40319 }
40320
40321 /*
40322 ** Attempt to set the maximum database page count if mxPage is positive. 
40323 ** Make no changes if mxPage is zero or negative.  And never reduce the
40324 ** maximum page count below the current size of the database.
40325 **
40326 ** Regardless of mxPage, return the current maximum page count.
40327 */
40328 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
40329   if( mxPage>0 ){
40330     pPager->mxPgno = mxPage;
40331   }
40332   assert( pPager->eState!=PAGER_OPEN );      /* Called only by OP_MaxPgcnt */
40333   assert( pPager->mxPgno>=pPager->dbSize );  /* OP_MaxPgcnt enforces this */
40334   return pPager->mxPgno;
40335 }
40336
40337 /*
40338 ** The following set of routines are used to disable the simulated
40339 ** I/O error mechanism.  These routines are used to avoid simulated
40340 ** errors in places where we do not care about errors.
40341 **
40342 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
40343 ** and generate no code.
40344 */
40345 #ifdef SQLITE_TEST
40346 SQLITE_API extern int sqlite3_io_error_pending;
40347 SQLITE_API extern int sqlite3_io_error_hit;
40348 static int saved_cnt;
40349 void disable_simulated_io_errors(void){
40350   saved_cnt = sqlite3_io_error_pending;
40351   sqlite3_io_error_pending = -1;
40352 }
40353 void enable_simulated_io_errors(void){
40354   sqlite3_io_error_pending = saved_cnt;
40355 }
40356 #else
40357 # define disable_simulated_io_errors()
40358 # define enable_simulated_io_errors()
40359 #endif
40360
40361 /*
40362 ** Read the first N bytes from the beginning of the file into memory
40363 ** that pDest points to. 
40364 **
40365 ** If the pager was opened on a transient file (zFilename==""), or
40366 ** opened on a file less than N bytes in size, the output buffer is
40367 ** zeroed and SQLITE_OK returned. The rationale for this is that this 
40368 ** function is used to read database headers, and a new transient or
40369 ** zero sized database has a header than consists entirely of zeroes.
40370 **
40371 ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
40372 ** the error code is returned to the caller and the contents of the
40373 ** output buffer undefined.
40374 */
40375 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
40376   int rc = SQLITE_OK;
40377   memset(pDest, 0, N);
40378   assert( isOpen(pPager->fd) || pPager->tempFile );
40379
40380   /* This routine is only called by btree immediately after creating
40381   ** the Pager object.  There has not been an opportunity to transition
40382   ** to WAL mode yet.
40383   */
40384   assert( !pagerUseWal(pPager) );
40385
40386   if( isOpen(pPager->fd) ){
40387     IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
40388     rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
40389     if( rc==SQLITE_IOERR_SHORT_READ ){
40390       rc = SQLITE_OK;
40391     }
40392   }
40393   return rc;
40394 }
40395
40396 /*
40397 ** This function may only be called when a read-transaction is open on
40398 ** the pager. It returns the total number of pages in the database.
40399 **
40400 ** However, if the file is between 1 and <page-size> bytes in size, then 
40401 ** this is considered a 1 page file.
40402 */
40403 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
40404   assert( pPager->eState>=PAGER_READER );
40405   assert( pPager->eState!=PAGER_WRITER_FINISHED );
40406   *pnPage = (int)pPager->dbSize;
40407 }
40408
40409
40410 /*
40411 ** Try to obtain a lock of type locktype on the database file. If
40412 ** a similar or greater lock is already held, this function is a no-op
40413 ** (returning SQLITE_OK immediately).
40414 **
40415 ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke 
40416 ** the busy callback if the lock is currently not available. Repeat 
40417 ** until the busy callback returns false or until the attempt to 
40418 ** obtain the lock succeeds.
40419 **
40420 ** Return SQLITE_OK on success and an error code if we cannot obtain
40421 ** the lock. If the lock is obtained successfully, set the Pager.state 
40422 ** variable to locktype before returning.
40423 */
40424 static int pager_wait_on_lock(Pager *pPager, int locktype){
40425   int rc;                              /* Return code */
40426
40427   /* Check that this is either a no-op (because the requested lock is 
40428   ** already held, or one of the transistions that the busy-handler
40429   ** may be invoked during, according to the comment above
40430   ** sqlite3PagerSetBusyhandler().
40431   */
40432   assert( (pPager->eLock>=locktype)
40433        || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
40434        || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
40435   );
40436
40437   do {
40438     rc = pagerLockDb(pPager, locktype);
40439   }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
40440   return rc;
40441 }
40442
40443 /*
40444 ** Function assertTruncateConstraint(pPager) checks that one of the 
40445 ** following is true for all dirty pages currently in the page-cache:
40446 **
40447 **   a) The page number is less than or equal to the size of the 
40448 **      current database image, in pages, OR
40449 **
40450 **   b) if the page content were written at this time, it would not
40451 **      be necessary to write the current content out to the sub-journal
40452 **      (as determined by function subjRequiresPage()).
40453 **
40454 ** If the condition asserted by this function were not true, and the
40455 ** dirty page were to be discarded from the cache via the pagerStress()
40456 ** routine, pagerStress() would not write the current page content to
40457 ** the database file. If a savepoint transaction were rolled back after
40458 ** this happened, the correct behaviour would be to restore the current
40459 ** content of the page. However, since this content is not present in either
40460 ** the database file or the portion of the rollback journal and 
40461 ** sub-journal rolled back the content could not be restored and the
40462 ** database image would become corrupt. It is therefore fortunate that 
40463 ** this circumstance cannot arise.
40464 */
40465 #if defined(SQLITE_DEBUG)
40466 static void assertTruncateConstraintCb(PgHdr *pPg){
40467   assert( pPg->flags&PGHDR_DIRTY );
40468   assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
40469 }
40470 static void assertTruncateConstraint(Pager *pPager){
40471   sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
40472 }
40473 #else
40474 # define assertTruncateConstraint(pPager)
40475 #endif
40476
40477 /*
40478 ** Truncate the in-memory database file image to nPage pages. This 
40479 ** function does not actually modify the database file on disk. It 
40480 ** just sets the internal state of the pager object so that the 
40481 ** truncation will be done when the current transaction is committed.
40482 */
40483 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
40484   assert( pPager->dbSize>=nPage );
40485   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
40486   pPager->dbSize = nPage;
40487   assertTruncateConstraint(pPager);
40488 }
40489
40490
40491 /*
40492 ** This function is called before attempting a hot-journal rollback. It
40493 ** syncs the journal file to disk, then sets pPager->journalHdr to the
40494 ** size of the journal file so that the pager_playback() routine knows
40495 ** that the entire journal file has been synced.
40496 **
40497 ** Syncing a hot-journal to disk before attempting to roll it back ensures 
40498 ** that if a power-failure occurs during the rollback, the process that
40499 ** attempts rollback following system recovery sees the same journal
40500 ** content as this process.
40501 **
40502 ** If everything goes as planned, SQLITE_OK is returned. Otherwise, 
40503 ** an SQLite error code.
40504 */
40505 static int pagerSyncHotJournal(Pager *pPager){
40506   int rc = SQLITE_OK;
40507   if( !pPager->noSync ){
40508     rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
40509   }
40510   if( rc==SQLITE_OK ){
40511     rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
40512   }
40513   return rc;
40514 }
40515
40516 /*
40517 ** Shutdown the page cache.  Free all memory and close all files.
40518 **
40519 ** If a transaction was in progress when this routine is called, that
40520 ** transaction is rolled back.  All outstanding pages are invalidated
40521 ** and their memory is freed.  Any attempt to use a page associated
40522 ** with this page cache after this function returns will likely
40523 ** result in a coredump.
40524 **
40525 ** This function always succeeds. If a transaction is active an attempt
40526 ** is made to roll it back. If an error occurs during the rollback 
40527 ** a hot journal may be left in the filesystem but no error is returned
40528 ** to the caller.
40529 */
40530 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
40531   u8 *pTmp = (u8 *)pPager->pTmpSpace;
40532
40533   disable_simulated_io_errors();
40534   sqlite3BeginBenignMalloc();
40535   /* pPager->errCode = 0; */
40536   pPager->exclusiveMode = 0;
40537 #ifndef SQLITE_OMIT_WAL
40538   sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
40539   pPager->pWal = 0;
40540 #endif
40541   pager_reset(pPager);
40542   if( MEMDB ){
40543     pager_unlock(pPager);
40544   }else{
40545     /* If it is open, sync the journal file before calling UnlockAndRollback.
40546     ** If this is not done, then an unsynced portion of the open journal 
40547     ** file may be played back into the database. If a power failure occurs 
40548     ** while this is happening, the database could become corrupt.
40549     **
40550     ** If an error occurs while trying to sync the journal, shift the pager
40551     ** into the ERROR state. This causes UnlockAndRollback to unlock the
40552     ** database and close the journal file without attempting to roll it
40553     ** back or finalize it. The next database user will have to do hot-journal
40554     ** rollback before accessing the database file.
40555     */
40556     if( isOpen(pPager->jfd) ){
40557       pager_error(pPager, pagerSyncHotJournal(pPager));
40558     }
40559     pagerUnlockAndRollback(pPager);
40560   }
40561   sqlite3EndBenignMalloc();
40562   enable_simulated_io_errors();
40563   PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
40564   IOTRACE(("CLOSE %p\n", pPager))
40565   sqlite3OsClose(pPager->jfd);
40566   sqlite3OsClose(pPager->fd);
40567   sqlite3PageFree(pTmp);
40568   sqlite3PcacheClose(pPager->pPCache);
40569
40570 #ifdef SQLITE_HAS_CODEC
40571   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
40572 #endif
40573
40574   assert( !pPager->aSavepoint && !pPager->pInJournal );
40575   assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
40576
40577   sqlite3_free(pPager);
40578   return SQLITE_OK;
40579 }
40580
40581 #if !defined(NDEBUG) || defined(SQLITE_TEST)
40582 /*
40583 ** Return the page number for page pPg.
40584 */
40585 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
40586   return pPg->pgno;
40587 }
40588 #endif
40589
40590 /*
40591 ** Increment the reference count for page pPg.
40592 */
40593 SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
40594   sqlite3PcacheRef(pPg);
40595 }
40596
40597 /*
40598 ** Sync the journal. In other words, make sure all the pages that have
40599 ** been written to the journal have actually reached the surface of the
40600 ** disk and can be restored in the event of a hot-journal rollback.
40601 **
40602 ** If the Pager.noSync flag is set, then this function is a no-op.
40603 ** Otherwise, the actions required depend on the journal-mode and the 
40604 ** device characteristics of the the file-system, as follows:
40605 **
40606 **   * If the journal file is an in-memory journal file, no action need
40607 **     be taken.
40608 **
40609 **   * Otherwise, if the device does not support the SAFE_APPEND property,
40610 **     then the nRec field of the most recently written journal header
40611 **     is updated to contain the number of journal records that have
40612 **     been written following it. If the pager is operating in full-sync
40613 **     mode, then the journal file is synced before this field is updated.
40614 **
40615 **   * If the device does not support the SEQUENTIAL property, then 
40616 **     journal file is synced.
40617 **
40618 ** Or, in pseudo-code:
40619 **
40620 **   if( NOT <in-memory journal> ){
40621 **     if( NOT SAFE_APPEND ){
40622 **       if( <full-sync mode> ) xSync(<journal file>);
40623 **       <update nRec field>
40624 **     } 
40625 **     if( NOT SEQUENTIAL ) xSync(<journal file>);
40626 **   }
40627 **
40628 ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every 
40629 ** page currently held in memory before returning SQLITE_OK. If an IO
40630 ** error is encountered, then the IO error code is returned to the caller.
40631 */
40632 static int syncJournal(Pager *pPager, int newHdr){
40633   int rc;                         /* Return code */
40634
40635   assert( pPager->eState==PAGER_WRITER_CACHEMOD
40636        || pPager->eState==PAGER_WRITER_DBMOD
40637   );
40638   assert( assert_pager_state(pPager) );
40639   assert( !pagerUseWal(pPager) );
40640
40641   rc = sqlite3PagerExclusiveLock(pPager);
40642   if( rc!=SQLITE_OK ) return rc;
40643
40644   if( !pPager->noSync ){
40645     assert( !pPager->tempFile );
40646     if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
40647       const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
40648       assert( isOpen(pPager->jfd) );
40649
40650       if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
40651         /* This block deals with an obscure problem. If the last connection
40652         ** that wrote to this database was operating in persistent-journal
40653         ** mode, then the journal file may at this point actually be larger
40654         ** than Pager.journalOff bytes. If the next thing in the journal
40655         ** file happens to be a journal-header (written as part of the
40656         ** previous connection's transaction), and a crash or power-failure 
40657         ** occurs after nRec is updated but before this connection writes 
40658         ** anything else to the journal file (or commits/rolls back its 
40659         ** transaction), then SQLite may become confused when doing the 
40660         ** hot-journal rollback following recovery. It may roll back all
40661         ** of this connections data, then proceed to rolling back the old,
40662         ** out-of-date data that follows it. Database corruption.
40663         **
40664         ** To work around this, if the journal file does appear to contain
40665         ** a valid header following Pager.journalOff, then write a 0x00
40666         ** byte to the start of it to prevent it from being recognized.
40667         **
40668         ** Variable iNextHdrOffset is set to the offset at which this
40669         ** problematic header will occur, if it exists. aMagic is used 
40670         ** as a temporary buffer to inspect the first couple of bytes of
40671         ** the potential journal header.
40672         */
40673         i64 iNextHdrOffset;
40674         u8 aMagic[8];
40675         u8 zHeader[sizeof(aJournalMagic)+4];
40676
40677         memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
40678         put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
40679
40680         iNextHdrOffset = journalHdrOffset(pPager);
40681         rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
40682         if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
40683           static const u8 zerobyte = 0;
40684           rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
40685         }
40686         if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
40687           return rc;
40688         }
40689
40690         /* Write the nRec value into the journal file header. If in
40691         ** full-synchronous mode, sync the journal first. This ensures that
40692         ** all data has really hit the disk before nRec is updated to mark
40693         ** it as a candidate for rollback.
40694         **
40695         ** This is not required if the persistent media supports the
40696         ** SAFE_APPEND property. Because in this case it is not possible 
40697         ** for garbage data to be appended to the file, the nRec field
40698         ** is populated with 0xFFFFFFFF when the journal header is written
40699         ** and never needs to be updated.
40700         */
40701         if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
40702           PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
40703           IOTRACE(("JSYNC %p\n", pPager))
40704           rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
40705           if( rc!=SQLITE_OK ) return rc;
40706         }
40707         IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
40708         rc = sqlite3OsWrite(
40709             pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
40710         );
40711         if( rc!=SQLITE_OK ) return rc;
40712       }
40713       if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
40714         PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
40715         IOTRACE(("JSYNC %p\n", pPager))
40716         rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags| 
40717           (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
40718         );
40719         if( rc!=SQLITE_OK ) return rc;
40720       }
40721
40722       pPager->journalHdr = pPager->journalOff;
40723       if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
40724         pPager->nRec = 0;
40725         rc = writeJournalHdr(pPager);
40726         if( rc!=SQLITE_OK ) return rc;
40727       }
40728     }else{
40729       pPager->journalHdr = pPager->journalOff;
40730     }
40731   }
40732
40733   /* Unless the pager is in noSync mode, the journal file was just 
40734   ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on 
40735   ** all pages.
40736   */
40737   sqlite3PcacheClearSyncFlags(pPager->pPCache);
40738   pPager->eState = PAGER_WRITER_DBMOD;
40739   assert( assert_pager_state(pPager) );
40740   return SQLITE_OK;
40741 }
40742
40743 /*
40744 ** The argument is the first in a linked list of dirty pages connected
40745 ** by the PgHdr.pDirty pointer. This function writes each one of the
40746 ** in-memory pages in the list to the database file. The argument may
40747 ** be NULL, representing an empty list. In this case this function is
40748 ** a no-op.
40749 **
40750 ** The pager must hold at least a RESERVED lock when this function
40751 ** is called. Before writing anything to the database file, this lock
40752 ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
40753 ** SQLITE_BUSY is returned and no data is written to the database file.
40754 ** 
40755 ** If the pager is a temp-file pager and the actual file-system file
40756 ** is not yet open, it is created and opened before any data is 
40757 ** written out.
40758 **
40759 ** Once the lock has been upgraded and, if necessary, the file opened,
40760 ** the pages are written out to the database file in list order. Writing
40761 ** a page is skipped if it meets either of the following criteria:
40762 **
40763 **   * The page number is greater than Pager.dbSize, or
40764 **   * The PGHDR_DONT_WRITE flag is set on the page.
40765 **
40766 ** If writing out a page causes the database file to grow, Pager.dbFileSize
40767 ** is updated accordingly. If page 1 is written out, then the value cached
40768 ** in Pager.dbFileVers[] is updated to match the new value stored in
40769 ** the database file.
40770 **
40771 ** If everything is successful, SQLITE_OK is returned. If an IO error 
40772 ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
40773 ** be obtained, SQLITE_BUSY is returned.
40774 */
40775 static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
40776   int rc = SQLITE_OK;                  /* Return code */
40777
40778   /* This function is only called for rollback pagers in WRITER_DBMOD state. */
40779   assert( !pagerUseWal(pPager) );
40780   assert( pPager->eState==PAGER_WRITER_DBMOD );
40781   assert( pPager->eLock==EXCLUSIVE_LOCK );
40782
40783   /* If the file is a temp-file has not yet been opened, open it now. It
40784   ** is not possible for rc to be other than SQLITE_OK if this branch
40785   ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
40786   */
40787   if( !isOpen(pPager->fd) ){
40788     assert( pPager->tempFile && rc==SQLITE_OK );
40789     rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
40790   }
40791
40792   /* Before the first write, give the VFS a hint of what the final
40793   ** file size will be.
40794   */
40795   assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
40796   if( rc==SQLITE_OK && pPager->dbSize>pPager->dbHintSize ){
40797     sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
40798     sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
40799     pPager->dbHintSize = pPager->dbSize;
40800   }
40801
40802   while( rc==SQLITE_OK && pList ){
40803     Pgno pgno = pList->pgno;
40804
40805     /* If there are dirty pages in the page cache with page numbers greater
40806     ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
40807     ** make the file smaller (presumably by auto-vacuum code). Do not write
40808     ** any such pages to the file.
40809     **
40810     ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
40811     ** set (set by sqlite3PagerDontWrite()).
40812     */
40813     if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
40814       i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
40815       char *pData;                                   /* Data to write */    
40816
40817       assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
40818       if( pList->pgno==1 ) pager_write_changecounter(pList);
40819
40820       /* Encode the database */
40821       CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
40822
40823       /* Write out the page data. */
40824       rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
40825
40826       /* If page 1 was just written, update Pager.dbFileVers to match
40827       ** the value now stored in the database file. If writing this 
40828       ** page caused the database file to grow, update dbFileSize. 
40829       */
40830       if( pgno==1 ){
40831         memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
40832       }
40833       if( pgno>pPager->dbFileSize ){
40834         pPager->dbFileSize = pgno;
40835       }
40836
40837       /* Update any backup objects copying the contents of this pager. */
40838       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
40839
40840       PAGERTRACE(("STORE %d page %d hash(%08x)\n",
40841                    PAGERID(pPager), pgno, pager_pagehash(pList)));
40842       IOTRACE(("PGOUT %p %d\n", pPager, pgno));
40843       PAGER_INCR(sqlite3_pager_writedb_count);
40844       PAGER_INCR(pPager->nWrite);
40845     }else{
40846       PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
40847     }
40848     pager_set_pagehash(pList);
40849     pList = pList->pDirty;
40850   }
40851
40852   return rc;
40853 }
40854
40855 /*
40856 ** Ensure that the sub-journal file is open. If it is already open, this 
40857 ** function is a no-op.
40858 **
40859 ** SQLITE_OK is returned if everything goes according to plan. An 
40860 ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen() 
40861 ** fails.
40862 */
40863 static int openSubJournal(Pager *pPager){
40864   int rc = SQLITE_OK;
40865   if( !isOpen(pPager->sjfd) ){
40866     if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
40867       sqlite3MemJournalOpen(pPager->sjfd);
40868     }else{
40869       rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
40870     }
40871   }
40872   return rc;
40873 }
40874
40875 /*
40876 ** Append a record of the current state of page pPg to the sub-journal. 
40877 ** It is the callers responsibility to use subjRequiresPage() to check 
40878 ** that it is really required before calling this function.
40879 **
40880 ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
40881 ** for all open savepoints before returning.
40882 **
40883 ** This function returns SQLITE_OK if everything is successful, an IO
40884 ** error code if the attempt to write to the sub-journal fails, or 
40885 ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
40886 ** bitvec.
40887 */
40888 static int subjournalPage(PgHdr *pPg){
40889   int rc = SQLITE_OK;
40890   Pager *pPager = pPg->pPager;
40891   if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
40892
40893     /* Open the sub-journal, if it has not already been opened */
40894     assert( pPager->useJournal );
40895     assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
40896     assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
40897     assert( pagerUseWal(pPager) 
40898          || pageInJournal(pPg) 
40899          || pPg->pgno>pPager->dbOrigSize 
40900     );
40901     rc = openSubJournal(pPager);
40902
40903     /* If the sub-journal was opened successfully (or was already open),
40904     ** write the journal record into the file.  */
40905     if( rc==SQLITE_OK ){
40906       void *pData = pPg->pData;
40907       i64 offset = pPager->nSubRec*(4+pPager->pageSize);
40908       char *pData2;
40909   
40910       CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
40911       PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
40912       rc = write32bits(pPager->sjfd, offset, pPg->pgno);
40913       if( rc==SQLITE_OK ){
40914         rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
40915       }
40916     }
40917   }
40918   if( rc==SQLITE_OK ){
40919     pPager->nSubRec++;
40920     assert( pPager->nSavepoint>0 );
40921     rc = addToSavepointBitvecs(pPager, pPg->pgno);
40922   }
40923   return rc;
40924 }
40925
40926 /*
40927 ** This function is called by the pcache layer when it has reached some
40928 ** soft memory limit. The first argument is a pointer to a Pager object
40929 ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
40930 ** database). The second argument is a reference to a page that is 
40931 ** currently dirty but has no outstanding references. The page
40932 ** is always associated with the Pager object passed as the first 
40933 ** argument.
40934 **
40935 ** The job of this function is to make pPg clean by writing its contents
40936 ** out to the database file, if possible. This may involve syncing the
40937 ** journal file. 
40938 **
40939 ** If successful, sqlite3PcacheMakeClean() is called on the page and
40940 ** SQLITE_OK returned. If an IO error occurs while trying to make the
40941 ** page clean, the IO error code is returned. If the page cannot be
40942 ** made clean for some other reason, but no error occurs, then SQLITE_OK
40943 ** is returned by sqlite3PcacheMakeClean() is not called.
40944 */
40945 static int pagerStress(void *p, PgHdr *pPg){
40946   Pager *pPager = (Pager *)p;
40947   int rc = SQLITE_OK;
40948
40949   assert( pPg->pPager==pPager );
40950   assert( pPg->flags&PGHDR_DIRTY );
40951
40952   /* The doNotSyncSpill flag is set during times when doing a sync of
40953   ** journal (and adding a new header) is not allowed.  This occurs
40954   ** during calls to sqlite3PagerWrite() while trying to journal multiple
40955   ** pages belonging to the same sector.
40956   **
40957   ** The doNotSpill flag inhibits all cache spilling regardless of whether
40958   ** or not a sync is required.  This is set during a rollback.
40959   **
40960   ** Spilling is also prohibited when in an error state since that could
40961   ** lead to database corruption.   In the current implementaton it 
40962   ** is impossible for sqlite3PCacheFetch() to be called with createFlag==1
40963   ** while in the error state, hence it is impossible for this routine to
40964   ** be called in the error state.  Nevertheless, we include a NEVER()
40965   ** test for the error state as a safeguard against future changes.
40966   */
40967   if( NEVER(pPager->errCode) ) return SQLITE_OK;
40968   if( pPager->doNotSpill ) return SQLITE_OK;
40969   if( pPager->doNotSyncSpill && (pPg->flags & PGHDR_NEED_SYNC)!=0 ){
40970     return SQLITE_OK;
40971   }
40972
40973   pPg->pDirty = 0;
40974   if( pagerUseWal(pPager) ){
40975     /* Write a single frame for this page to the log. */
40976     if( subjRequiresPage(pPg) ){ 
40977       rc = subjournalPage(pPg); 
40978     }
40979     if( rc==SQLITE_OK ){
40980       rc = pagerWalFrames(pPager, pPg, 0, 0, 0);
40981     }
40982   }else{
40983   
40984     /* Sync the journal file if required. */
40985     if( pPg->flags&PGHDR_NEED_SYNC 
40986      || pPager->eState==PAGER_WRITER_CACHEMOD
40987     ){
40988       rc = syncJournal(pPager, 1);
40989     }
40990   
40991     /* If the page number of this page is larger than the current size of
40992     ** the database image, it may need to be written to the sub-journal.
40993     ** This is because the call to pager_write_pagelist() below will not
40994     ** actually write data to the file in this case.
40995     **
40996     ** Consider the following sequence of events:
40997     **
40998     **   BEGIN;
40999     **     <journal page X>
41000     **     <modify page X>
41001     **     SAVEPOINT sp;
41002     **       <shrink database file to Y pages>
41003     **       pagerStress(page X)
41004     **     ROLLBACK TO sp;
41005     **
41006     ** If (X>Y), then when pagerStress is called page X will not be written
41007     ** out to the database file, but will be dropped from the cache. Then,
41008     ** following the "ROLLBACK TO sp" statement, reading page X will read
41009     ** data from the database file. This will be the copy of page X as it
41010     ** was when the transaction started, not as it was when "SAVEPOINT sp"
41011     ** was executed.
41012     **
41013     ** The solution is to write the current data for page X into the 
41014     ** sub-journal file now (if it is not already there), so that it will
41015     ** be restored to its current value when the "ROLLBACK TO sp" is 
41016     ** executed.
41017     */
41018     if( NEVER(
41019         rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
41020     ) ){
41021       rc = subjournalPage(pPg);
41022     }
41023   
41024     /* Write the contents of the page out to the database file. */
41025     if( rc==SQLITE_OK ){
41026       assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
41027       rc = pager_write_pagelist(pPager, pPg);
41028     }
41029   }
41030
41031   /* Mark the page as clean. */
41032   if( rc==SQLITE_OK ){
41033     PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
41034     sqlite3PcacheMakeClean(pPg);
41035   }
41036
41037   return pager_error(pPager, rc); 
41038 }
41039
41040
41041 /*
41042 ** Allocate and initialize a new Pager object and put a pointer to it
41043 ** in *ppPager. The pager should eventually be freed by passing it
41044 ** to sqlite3PagerClose().
41045 **
41046 ** The zFilename argument is the path to the database file to open.
41047 ** If zFilename is NULL then a randomly-named temporary file is created
41048 ** and used as the file to be cached. Temporary files are be deleted
41049 ** automatically when they are closed. If zFilename is ":memory:" then 
41050 ** all information is held in cache. It is never written to disk. 
41051 ** This can be used to implement an in-memory database.
41052 **
41053 ** The nExtra parameter specifies the number of bytes of space allocated
41054 ** along with each page reference. This space is available to the user
41055 ** via the sqlite3PagerGetExtra() API.
41056 **
41057 ** The flags argument is used to specify properties that affect the
41058 ** operation of the pager. It should be passed some bitwise combination
41059 ** of the PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK flags.
41060 **
41061 ** The vfsFlags parameter is a bitmask to pass to the flags parameter
41062 ** of the xOpen() method of the supplied VFS when opening files. 
41063 **
41064 ** If the pager object is allocated and the specified file opened 
41065 ** successfully, SQLITE_OK is returned and *ppPager set to point to
41066 ** the new pager object. If an error occurs, *ppPager is set to NULL
41067 ** and error code returned. This function may return SQLITE_NOMEM
41068 ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or 
41069 ** various SQLITE_IO_XXX errors.
41070 */
41071 SQLITE_PRIVATE int sqlite3PagerOpen(
41072   sqlite3_vfs *pVfs,       /* The virtual file system to use */
41073   Pager **ppPager,         /* OUT: Return the Pager structure here */
41074   const char *zFilename,   /* Name of the database file to open */
41075   int nExtra,              /* Extra bytes append to each in-memory page */
41076   int flags,               /* flags controlling this file */
41077   int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
41078   void (*xReinit)(DbPage*) /* Function to reinitialize pages */
41079 ){
41080   u8 *pPtr;
41081   Pager *pPager = 0;       /* Pager object to allocate and return */
41082   int rc = SQLITE_OK;      /* Return code */
41083   int tempFile = 0;        /* True for temp files (incl. in-memory files) */
41084   int memDb = 0;           /* True if this is an in-memory file */
41085   int readOnly = 0;        /* True if this is a read-only file */
41086   int journalFileSize;     /* Bytes to allocate for each journal fd */
41087   char *zPathname = 0;     /* Full path to database file */
41088   int nPathname = 0;       /* Number of bytes in zPathname */
41089   int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
41090   int noReadlock = (flags & PAGER_NO_READLOCK)!=0;  /* True to omit read-lock */
41091   int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
41092   u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
41093   const char *zUri = 0;    /* URI args to copy */
41094   int nUri = 0;            /* Number of bytes of URI args at *zUri */
41095
41096   /* Figure out how much space is required for each journal file-handle
41097   ** (there are two of them, the main journal and the sub-journal). This
41098   ** is the maximum space required for an in-memory journal file handle 
41099   ** and a regular journal file-handle. Note that a "regular journal-handle"
41100   ** may be a wrapper capable of caching the first portion of the journal
41101   ** file in memory to implement the atomic-write optimization (see 
41102   ** source file journal.c).
41103   */
41104   if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
41105     journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
41106   }else{
41107     journalFileSize = ROUND8(sqlite3MemJournalSize());
41108   }
41109
41110   /* Set the output variable to NULL in case an error occurs. */
41111   *ppPager = 0;
41112
41113 #ifndef SQLITE_OMIT_MEMORYDB
41114   if( flags & PAGER_MEMORY ){
41115     memDb = 1;
41116     zFilename = 0;
41117   }
41118 #endif
41119
41120   /* Compute and store the full pathname in an allocated buffer pointed
41121   ** to by zPathname, length nPathname. Or, if this is a temporary file,
41122   ** leave both nPathname and zPathname set to 0.
41123   */
41124   if( zFilename && zFilename[0] ){
41125     const char *z;
41126     nPathname = pVfs->mxPathname+1;
41127     zPathname = sqlite3Malloc(nPathname*2);
41128     if( zPathname==0 ){
41129       return SQLITE_NOMEM;
41130     }
41131     zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
41132     rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
41133     nPathname = sqlite3Strlen30(zPathname);
41134     z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
41135     while( *z ){
41136       z += sqlite3Strlen30(z)+1;
41137       z += sqlite3Strlen30(z)+1;
41138     }
41139     nUri = &z[1] - zUri;
41140     if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
41141       /* This branch is taken when the journal path required by
41142       ** the database being opened will be more than pVfs->mxPathname
41143       ** bytes in length. This means the database cannot be opened,
41144       ** as it will not be possible to open the journal file or even
41145       ** check for a hot-journal before reading.
41146       */
41147       rc = SQLITE_CANTOPEN_BKPT;
41148     }
41149     if( rc!=SQLITE_OK ){
41150       sqlite3_free(zPathname);
41151       return rc;
41152     }
41153   }
41154
41155   /* Allocate memory for the Pager structure, PCache object, the
41156   ** three file descriptors, the database file name and the journal 
41157   ** file name. The layout in memory is as follows:
41158   **
41159   **     Pager object                    (sizeof(Pager) bytes)
41160   **     PCache object                   (sqlite3PcacheSize() bytes)
41161   **     Database file handle            (pVfs->szOsFile bytes)
41162   **     Sub-journal file handle         (journalFileSize bytes)
41163   **     Main journal file handle        (journalFileSize bytes)
41164   **     Database file name              (nPathname+1 bytes)
41165   **     Journal file name               (nPathname+8+1 bytes)
41166   */
41167   pPtr = (u8 *)sqlite3MallocZero(
41168     ROUND8(sizeof(*pPager)) +      /* Pager structure */
41169     ROUND8(pcacheSize) +           /* PCache object */
41170     ROUND8(pVfs->szOsFile) +       /* The main db file */
41171     journalFileSize * 2 +          /* The two journal files */ 
41172     nPathname + 1 + nUri +         /* zFilename */
41173     nPathname + 8 + 1              /* zJournal */
41174 #ifndef SQLITE_OMIT_WAL
41175     + nPathname + 4 + 1              /* zWal */
41176 #endif
41177   );
41178   assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
41179   if( !pPtr ){
41180     sqlite3_free(zPathname);
41181     return SQLITE_NOMEM;
41182   }
41183   pPager =              (Pager*)(pPtr);
41184   pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
41185   pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
41186   pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
41187   pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
41188   pPager->zFilename =    (char*)(pPtr += journalFileSize);
41189   assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
41190
41191   /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
41192   if( zPathname ){
41193     assert( nPathname>0 );
41194     pPager->zJournal =   (char*)(pPtr += nPathname + 1 + nUri);
41195     memcpy(pPager->zFilename, zPathname, nPathname);
41196     memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
41197     memcpy(pPager->zJournal, zPathname, nPathname);
41198     memcpy(&pPager->zJournal[nPathname], "-journal", 8);
41199     sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
41200 #ifndef SQLITE_OMIT_WAL
41201     pPager->zWal = &pPager->zJournal[nPathname+8+1];
41202     memcpy(pPager->zWal, zPathname, nPathname);
41203     memcpy(&pPager->zWal[nPathname], "-wal", 4);
41204     sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
41205 #endif
41206     sqlite3_free(zPathname);
41207   }
41208   pPager->pVfs = pVfs;
41209   pPager->vfsFlags = vfsFlags;
41210
41211   /* Open the pager file.
41212   */
41213   if( zFilename && zFilename[0] ){
41214     int fout = 0;                    /* VFS flags returned by xOpen() */
41215     rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
41216     assert( !memDb );
41217     readOnly = (fout&SQLITE_OPEN_READONLY);
41218
41219     /* If the file was successfully opened for read/write access,
41220     ** choose a default page size in case we have to create the
41221     ** database file. The default page size is the maximum of:
41222     **
41223     **    + SQLITE_DEFAULT_PAGE_SIZE,
41224     **    + The value returned by sqlite3OsSectorSize()
41225     **    + The largest page size that can be written atomically.
41226     */
41227     if( rc==SQLITE_OK && !readOnly ){
41228       setSectorSize(pPager);
41229       assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
41230       if( szPageDflt<pPager->sectorSize ){
41231         if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
41232           szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
41233         }else{
41234           szPageDflt = (u32)pPager->sectorSize;
41235         }
41236       }
41237 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
41238       {
41239         int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
41240         int ii;
41241         assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
41242         assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
41243         assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
41244         for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
41245           if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
41246             szPageDflt = ii;
41247           }
41248         }
41249       }
41250 #endif
41251     }
41252   }else{
41253     /* If a temporary file is requested, it is not opened immediately.
41254     ** In this case we accept the default page size and delay actually
41255     ** opening the file until the first call to OsWrite().
41256     **
41257     ** This branch is also run for an in-memory database. An in-memory
41258     ** database is the same as a temp-file that is never written out to
41259     ** disk and uses an in-memory rollback journal.
41260     */ 
41261     tempFile = 1;
41262     pPager->eState = PAGER_READER;
41263     pPager->eLock = EXCLUSIVE_LOCK;
41264     readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
41265   }
41266
41267   /* The following call to PagerSetPagesize() serves to set the value of 
41268   ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
41269   */
41270   if( rc==SQLITE_OK ){
41271     assert( pPager->memDb==0 );
41272     rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
41273     testcase( rc!=SQLITE_OK );
41274   }
41275
41276   /* If an error occurred in either of the blocks above, free the 
41277   ** Pager structure and close the file.
41278   */
41279   if( rc!=SQLITE_OK ){
41280     assert( !pPager->pTmpSpace );
41281     sqlite3OsClose(pPager->fd);
41282     sqlite3_free(pPager);
41283     return rc;
41284   }
41285
41286   /* Initialize the PCache object. */
41287   assert( nExtra<1000 );
41288   nExtra = ROUND8(nExtra);
41289   sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
41290                     !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
41291
41292   PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
41293   IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
41294
41295   pPager->useJournal = (u8)useJournal;
41296   pPager->noReadlock = (noReadlock && readOnly) ?1:0;
41297   /* pPager->stmtOpen = 0; */
41298   /* pPager->stmtInUse = 0; */
41299   /* pPager->nRef = 0; */
41300   /* pPager->stmtSize = 0; */
41301   /* pPager->stmtJSize = 0; */
41302   /* pPager->nPage = 0; */
41303   pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
41304   /* pPager->state = PAGER_UNLOCK; */
41305 #if 0
41306   assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
41307 #endif
41308   /* pPager->errMask = 0; */
41309   pPager->tempFile = (u8)tempFile;
41310   assert( tempFile==PAGER_LOCKINGMODE_NORMAL 
41311           || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
41312   assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
41313   pPager->exclusiveMode = (u8)tempFile; 
41314   pPager->changeCountDone = pPager->tempFile;
41315   pPager->memDb = (u8)memDb;
41316   pPager->readOnly = (u8)readOnly;
41317   assert( useJournal || pPager->tempFile );
41318   pPager->noSync = pPager->tempFile;
41319   pPager->fullSync = pPager->noSync ?0:1;
41320   pPager->syncFlags = pPager->noSync ? 0 : SQLITE_SYNC_NORMAL;
41321   pPager->ckptSyncFlags = pPager->syncFlags;
41322   /* pPager->pFirst = 0; */
41323   /* pPager->pFirstSynced = 0; */
41324   /* pPager->pLast = 0; */
41325   pPager->nExtra = (u16)nExtra;
41326   pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
41327   assert( isOpen(pPager->fd) || tempFile );
41328   setSectorSize(pPager);
41329   if( !useJournal ){
41330     pPager->journalMode = PAGER_JOURNALMODE_OFF;
41331   }else if( memDb ){
41332     pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
41333   }
41334   /* pPager->xBusyHandler = 0; */
41335   /* pPager->pBusyHandlerArg = 0; */
41336   pPager->xReiniter = xReinit;
41337   /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
41338
41339   *ppPager = pPager;
41340   return SQLITE_OK;
41341 }
41342
41343
41344
41345 /*
41346 ** This function is called after transitioning from PAGER_UNLOCK to
41347 ** PAGER_SHARED state. It tests if there is a hot journal present in
41348 ** the file-system for the given pager. A hot journal is one that 
41349 ** needs to be played back. According to this function, a hot-journal
41350 ** file exists if the following criteria are met:
41351 **
41352 **   * The journal file exists in the file system, and
41353 **   * No process holds a RESERVED or greater lock on the database file, and
41354 **   * The database file itself is greater than 0 bytes in size, and
41355 **   * The first byte of the journal file exists and is not 0x00.
41356 **
41357 ** If the current size of the database file is 0 but a journal file
41358 ** exists, that is probably an old journal left over from a prior
41359 ** database with the same name. In this case the journal file is
41360 ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
41361 ** is returned.
41362 **
41363 ** This routine does not check if there is a master journal filename
41364 ** at the end of the file. If there is, and that master journal file
41365 ** does not exist, then the journal file is not really hot. In this
41366 ** case this routine will return a false-positive. The pager_playback()
41367 ** routine will discover that the journal file is not really hot and 
41368 ** will not roll it back. 
41369 **
41370 ** If a hot-journal file is found to exist, *pExists is set to 1 and 
41371 ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
41372 ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
41373 ** to determine whether or not a hot-journal file exists, the IO error
41374 ** code is returned and the value of *pExists is undefined.
41375 */
41376 static int hasHotJournal(Pager *pPager, int *pExists){
41377   sqlite3_vfs * const pVfs = pPager->pVfs;
41378   int rc = SQLITE_OK;           /* Return code */
41379   int exists = 1;               /* True if a journal file is present */
41380   int jrnlOpen = !!isOpen(pPager->jfd);
41381
41382   assert( pPager->useJournal );
41383   assert( isOpen(pPager->fd) );
41384   assert( pPager->eState==PAGER_OPEN );
41385
41386   assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
41387     SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
41388   ));
41389
41390   *pExists = 0;
41391   if( !jrnlOpen ){
41392     rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
41393   }
41394   if( rc==SQLITE_OK && exists ){
41395     int locked = 0;             /* True if some process holds a RESERVED lock */
41396
41397     /* Race condition here:  Another process might have been holding the
41398     ** the RESERVED lock and have a journal open at the sqlite3OsAccess() 
41399     ** call above, but then delete the journal and drop the lock before
41400     ** we get to the following sqlite3OsCheckReservedLock() call.  If that
41401     ** is the case, this routine might think there is a hot journal when
41402     ** in fact there is none.  This results in a false-positive which will
41403     ** be dealt with by the playback routine.  Ticket #3883.
41404     */
41405     rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
41406     if( rc==SQLITE_OK && !locked ){
41407       Pgno nPage;                 /* Number of pages in database file */
41408
41409       /* Check the size of the database file. If it consists of 0 pages,
41410       ** then delete the journal file. See the header comment above for 
41411       ** the reasoning here.  Delete the obsolete journal file under
41412       ** a RESERVED lock to avoid race conditions and to avoid violating
41413       ** [H33020].
41414       */
41415       rc = pagerPagecount(pPager, &nPage);
41416       if( rc==SQLITE_OK ){
41417         if( nPage==0 ){
41418           sqlite3BeginBenignMalloc();
41419           if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
41420             sqlite3OsDelete(pVfs, pPager->zJournal, 0);
41421             if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
41422           }
41423           sqlite3EndBenignMalloc();
41424         }else{
41425           /* The journal file exists and no other connection has a reserved
41426           ** or greater lock on the database file. Now check that there is
41427           ** at least one non-zero bytes at the start of the journal file.
41428           ** If there is, then we consider this journal to be hot. If not, 
41429           ** it can be ignored.
41430           */
41431           if( !jrnlOpen ){
41432             int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
41433             rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
41434           }
41435           if( rc==SQLITE_OK ){
41436             u8 first = 0;
41437             rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
41438             if( rc==SQLITE_IOERR_SHORT_READ ){
41439               rc = SQLITE_OK;
41440             }
41441             if( !jrnlOpen ){
41442               sqlite3OsClose(pPager->jfd);
41443             }
41444             *pExists = (first!=0);
41445           }else if( rc==SQLITE_CANTOPEN ){
41446             /* If we cannot open the rollback journal file in order to see if
41447             ** its has a zero header, that might be due to an I/O error, or
41448             ** it might be due to the race condition described above and in
41449             ** ticket #3883.  Either way, assume that the journal is hot.
41450             ** This might be a false positive.  But if it is, then the
41451             ** automatic journal playback and recovery mechanism will deal
41452             ** with it under an EXCLUSIVE lock where we do not need to
41453             ** worry so much with race conditions.
41454             */
41455             *pExists = 1;
41456             rc = SQLITE_OK;
41457           }
41458         }
41459       }
41460     }
41461   }
41462
41463   return rc;
41464 }
41465
41466 /*
41467 ** This function is called to obtain a shared lock on the database file.
41468 ** It is illegal to call sqlite3PagerAcquire() until after this function
41469 ** has been successfully called. If a shared-lock is already held when
41470 ** this function is called, it is a no-op.
41471 **
41472 ** The following operations are also performed by this function.
41473 **
41474 **   1) If the pager is currently in PAGER_OPEN state (no lock held
41475 **      on the database file), then an attempt is made to obtain a
41476 **      SHARED lock on the database file. Immediately after obtaining
41477 **      the SHARED lock, the file-system is checked for a hot-journal,
41478 **      which is played back if present. Following any hot-journal 
41479 **      rollback, the contents of the cache are validated by checking
41480 **      the 'change-counter' field of the database file header and
41481 **      discarded if they are found to be invalid.
41482 **
41483 **   2) If the pager is running in exclusive-mode, and there are currently
41484 **      no outstanding references to any pages, and is in the error state,
41485 **      then an attempt is made to clear the error state by discarding
41486 **      the contents of the page cache and rolling back any open journal
41487 **      file.
41488 **
41489 ** If everything is successful, SQLITE_OK is returned. If an IO error 
41490 ** occurs while locking the database, checking for a hot-journal file or 
41491 ** rolling back a journal file, the IO error code is returned.
41492 */
41493 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
41494   int rc = SQLITE_OK;                /* Return code */
41495
41496   /* This routine is only called from b-tree and only when there are no
41497   ** outstanding pages. This implies that the pager state should either
41498   ** be OPEN or READER. READER is only possible if the pager is or was in 
41499   ** exclusive access mode.
41500   */
41501   assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
41502   assert( assert_pager_state(pPager) );
41503   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
41504   if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
41505
41506   if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
41507     int bHotJournal = 1;          /* True if there exists a hot journal-file */
41508
41509     assert( !MEMDB );
41510     assert( pPager->noReadlock==0 || pPager->readOnly );
41511
41512     if( pPager->noReadlock==0 ){
41513       rc = pager_wait_on_lock(pPager, SHARED_LOCK);
41514       if( rc!=SQLITE_OK ){
41515         assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
41516         goto failed;
41517       }
41518     }
41519
41520     /* If a journal file exists, and there is no RESERVED lock on the
41521     ** database file, then it either needs to be played back or deleted.
41522     */
41523     if( pPager->eLock<=SHARED_LOCK ){
41524       rc = hasHotJournal(pPager, &bHotJournal);
41525     }
41526     if( rc!=SQLITE_OK ){
41527       goto failed;
41528     }
41529     if( bHotJournal ){
41530       /* Get an EXCLUSIVE lock on the database file. At this point it is
41531       ** important that a RESERVED lock is not obtained on the way to the
41532       ** EXCLUSIVE lock. If it were, another process might open the
41533       ** database file, detect the RESERVED lock, and conclude that the
41534       ** database is safe to read while this process is still rolling the 
41535       ** hot-journal back.
41536       ** 
41537       ** Because the intermediate RESERVED lock is not requested, any
41538       ** other process attempting to access the database file will get to 
41539       ** this point in the code and fail to obtain its own EXCLUSIVE lock 
41540       ** on the database file.
41541       **
41542       ** Unless the pager is in locking_mode=exclusive mode, the lock is
41543       ** downgraded to SHARED_LOCK before this function returns.
41544       */
41545       rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
41546       if( rc!=SQLITE_OK ){
41547         goto failed;
41548       }
41549  
41550       /* If it is not already open and the file exists on disk, open the 
41551       ** journal for read/write access. Write access is required because 
41552       ** in exclusive-access mode the file descriptor will be kept open 
41553       ** and possibly used for a transaction later on. Also, write-access 
41554       ** is usually required to finalize the journal in journal_mode=persist 
41555       ** mode (and also for journal_mode=truncate on some systems).
41556       **
41557       ** If the journal does not exist, it usually means that some 
41558       ** other connection managed to get in and roll it back before 
41559       ** this connection obtained the exclusive lock above. Or, it 
41560       ** may mean that the pager was in the error-state when this
41561       ** function was called and the journal file does not exist.
41562       */
41563       if( !isOpen(pPager->jfd) ){
41564         sqlite3_vfs * const pVfs = pPager->pVfs;
41565         int bExists;              /* True if journal file exists */
41566         rc = sqlite3OsAccess(
41567             pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
41568         if( rc==SQLITE_OK && bExists ){
41569           int fout = 0;
41570           int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
41571           assert( !pPager->tempFile );
41572           rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
41573           assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
41574           if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
41575             rc = SQLITE_CANTOPEN_BKPT;
41576             sqlite3OsClose(pPager->jfd);
41577           }
41578         }
41579       }
41580  
41581       /* Playback and delete the journal.  Drop the database write
41582       ** lock and reacquire the read lock. Purge the cache before
41583       ** playing back the hot-journal so that we don't end up with
41584       ** an inconsistent cache.  Sync the hot journal before playing
41585       ** it back since the process that crashed and left the hot journal
41586       ** probably did not sync it and we are required to always sync
41587       ** the journal before playing it back.
41588       */
41589       if( isOpen(pPager->jfd) ){
41590         assert( rc==SQLITE_OK );
41591         rc = pagerSyncHotJournal(pPager);
41592         if( rc==SQLITE_OK ){
41593           rc = pager_playback(pPager, 1);
41594           pPager->eState = PAGER_OPEN;
41595         }
41596       }else if( !pPager->exclusiveMode ){
41597         pagerUnlockDb(pPager, SHARED_LOCK);
41598       }
41599
41600       if( rc!=SQLITE_OK ){
41601         /* This branch is taken if an error occurs while trying to open
41602         ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
41603         ** pager_unlock() routine will be called before returning to unlock
41604         ** the file. If the unlock attempt fails, then Pager.eLock must be
41605         ** set to UNKNOWN_LOCK (see the comment above the #define for 
41606         ** UNKNOWN_LOCK above for an explanation). 
41607         **
41608         ** In order to get pager_unlock() to do this, set Pager.eState to
41609         ** PAGER_ERROR now. This is not actually counted as a transition
41610         ** to ERROR state in the state diagram at the top of this file,
41611         ** since we know that the same call to pager_unlock() will very
41612         ** shortly transition the pager object to the OPEN state. Calling
41613         ** assert_pager_state() would fail now, as it should not be possible
41614         ** to be in ERROR state when there are zero outstanding page 
41615         ** references.
41616         */
41617         pager_error(pPager, rc);
41618         goto failed;
41619       }
41620
41621       assert( pPager->eState==PAGER_OPEN );
41622       assert( (pPager->eLock==SHARED_LOCK)
41623            || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
41624       );
41625     }
41626
41627     if( !pPager->tempFile 
41628      && (pPager->pBackup || sqlite3PcachePagecount(pPager->pPCache)>0) 
41629     ){
41630       /* The shared-lock has just been acquired on the database file
41631       ** and there are already pages in the cache (from a previous
41632       ** read or write transaction).  Check to see if the database
41633       ** has been modified.  If the database has changed, flush the
41634       ** cache.
41635       **
41636       ** Database changes is detected by looking at 15 bytes beginning
41637       ** at offset 24 into the file.  The first 4 of these 16 bytes are
41638       ** a 32-bit counter that is incremented with each change.  The
41639       ** other bytes change randomly with each file change when
41640       ** a codec is in use.
41641       ** 
41642       ** There is a vanishingly small chance that a change will not be 
41643       ** detected.  The chance of an undetected change is so small that
41644       ** it can be neglected.
41645       */
41646       Pgno nPage = 0;
41647       char dbFileVers[sizeof(pPager->dbFileVers)];
41648
41649       rc = pagerPagecount(pPager, &nPage);
41650       if( rc ) goto failed;
41651
41652       if( nPage>0 ){
41653         IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
41654         rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
41655         if( rc!=SQLITE_OK ){
41656           goto failed;
41657         }
41658       }else{
41659         memset(dbFileVers, 0, sizeof(dbFileVers));
41660       }
41661
41662       if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
41663         pager_reset(pPager);
41664       }
41665     }
41666
41667     /* If there is a WAL file in the file-system, open this database in WAL
41668     ** mode. Otherwise, the following function call is a no-op.
41669     */
41670     rc = pagerOpenWalIfPresent(pPager);
41671 #ifndef SQLITE_OMIT_WAL
41672     assert( pPager->pWal==0 || rc==SQLITE_OK );
41673 #endif
41674   }
41675
41676   if( pagerUseWal(pPager) ){
41677     assert( rc==SQLITE_OK );
41678     rc = pagerBeginReadTransaction(pPager);
41679   }
41680
41681   if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
41682     rc = pagerPagecount(pPager, &pPager->dbSize);
41683   }
41684
41685  failed:
41686   if( rc!=SQLITE_OK ){
41687     assert( !MEMDB );
41688     pager_unlock(pPager);
41689     assert( pPager->eState==PAGER_OPEN );
41690   }else{
41691     pPager->eState = PAGER_READER;
41692   }
41693   return rc;
41694 }
41695
41696 /*
41697 ** If the reference count has reached zero, rollback any active
41698 ** transaction and unlock the pager.
41699 **
41700 ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
41701 ** the rollback journal, the unlock is not performed and there is
41702 ** nothing to rollback, so this routine is a no-op.
41703 */ 
41704 static void pagerUnlockIfUnused(Pager *pPager){
41705   if( (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
41706     pagerUnlockAndRollback(pPager);
41707   }
41708 }
41709
41710 /*
41711 ** Acquire a reference to page number pgno in pager pPager (a page
41712 ** reference has type DbPage*). If the requested reference is 
41713 ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
41714 **
41715 ** If the requested page is already in the cache, it is returned. 
41716 ** Otherwise, a new page object is allocated and populated with data
41717 ** read from the database file. In some cases, the pcache module may
41718 ** choose not to allocate a new page object and may reuse an existing
41719 ** object with no outstanding references.
41720 **
41721 ** The extra data appended to a page is always initialized to zeros the 
41722 ** first time a page is loaded into memory. If the page requested is 
41723 ** already in the cache when this function is called, then the extra
41724 ** data is left as it was when the page object was last used.
41725 **
41726 ** If the database image is smaller than the requested page or if a 
41727 ** non-zero value is passed as the noContent parameter and the 
41728 ** requested page is not already stored in the cache, then no 
41729 ** actual disk read occurs. In this case the memory image of the 
41730 ** page is initialized to all zeros. 
41731 **
41732 ** If noContent is true, it means that we do not care about the contents
41733 ** of the page. This occurs in two seperate scenarios:
41734 **
41735 **   a) When reading a free-list leaf page from the database, and
41736 **
41737 **   b) When a savepoint is being rolled back and we need to load
41738 **      a new page into the cache to be filled with the data read
41739 **      from the savepoint journal.
41740 **
41741 ** If noContent is true, then the data returned is zeroed instead of
41742 ** being read from the database. Additionally, the bits corresponding
41743 ** to pgno in Pager.pInJournal (bitvec of pages already written to the
41744 ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
41745 ** savepoints are set. This means if the page is made writable at any
41746 ** point in the future, using a call to sqlite3PagerWrite(), its contents
41747 ** will not be journaled. This saves IO.
41748 **
41749 ** The acquisition might fail for several reasons.  In all cases,
41750 ** an appropriate error code is returned and *ppPage is set to NULL.
41751 **
41752 ** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
41753 ** to find a page in the in-memory cache first.  If the page is not already
41754 ** in memory, this routine goes to disk to read it in whereas Lookup()
41755 ** just returns 0.  This routine acquires a read-lock the first time it
41756 ** has to go to disk, and could also playback an old journal if necessary.
41757 ** Since Lookup() never goes to disk, it never has to deal with locks
41758 ** or journal files.
41759 */
41760 SQLITE_PRIVATE int sqlite3PagerAcquire(
41761   Pager *pPager,      /* The pager open on the database file */
41762   Pgno pgno,          /* Page number to fetch */
41763   DbPage **ppPage,    /* Write a pointer to the page here */
41764   int noContent       /* Do not bother reading content from disk if true */
41765 ){
41766   int rc;
41767   PgHdr *pPg;
41768
41769   assert( pPager->eState>=PAGER_READER );
41770   assert( assert_pager_state(pPager) );
41771
41772   if( pgno==0 ){
41773     return SQLITE_CORRUPT_BKPT;
41774   }
41775
41776   /* If the pager is in the error state, return an error immediately. 
41777   ** Otherwise, request the page from the PCache layer. */
41778   if( pPager->errCode!=SQLITE_OK ){
41779     rc = pPager->errCode;
41780   }else{
41781     rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
41782   }
41783
41784   if( rc!=SQLITE_OK ){
41785     /* Either the call to sqlite3PcacheFetch() returned an error or the
41786     ** pager was already in the error-state when this function was called.
41787     ** Set pPg to 0 and jump to the exception handler.  */
41788     pPg = 0;
41789     goto pager_acquire_err;
41790   }
41791   assert( (*ppPage)->pgno==pgno );
41792   assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
41793
41794   if( (*ppPage)->pPager && !noContent ){
41795     /* In this case the pcache already contains an initialized copy of
41796     ** the page. Return without further ado.  */
41797     assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
41798     PAGER_INCR(pPager->nHit);
41799     return SQLITE_OK;
41800
41801   }else{
41802     /* The pager cache has created a new page. Its content needs to 
41803     ** be initialized.  */
41804
41805     PAGER_INCR(pPager->nMiss);
41806     pPg = *ppPage;
41807     pPg->pPager = pPager;
41808
41809     /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
41810     ** number greater than this, or the unused locking-page, is requested. */
41811     if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
41812       rc = SQLITE_CORRUPT_BKPT;
41813       goto pager_acquire_err;
41814     }
41815
41816     if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
41817       if( pgno>pPager->mxPgno ){
41818         rc = SQLITE_FULL;
41819         goto pager_acquire_err;
41820       }
41821       if( noContent ){
41822         /* Failure to set the bits in the InJournal bit-vectors is benign.
41823         ** It merely means that we might do some extra work to journal a 
41824         ** page that does not need to be journaled.  Nevertheless, be sure 
41825         ** to test the case where a malloc error occurs while trying to set 
41826         ** a bit in a bit vector.
41827         */
41828         sqlite3BeginBenignMalloc();
41829         if( pgno<=pPager->dbOrigSize ){
41830           TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
41831           testcase( rc==SQLITE_NOMEM );
41832         }
41833         TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
41834         testcase( rc==SQLITE_NOMEM );
41835         sqlite3EndBenignMalloc();
41836       }
41837       memset(pPg->pData, 0, pPager->pageSize);
41838       IOTRACE(("ZERO %p %d\n", pPager, pgno));
41839     }else{
41840       assert( pPg->pPager==pPager );
41841       rc = readDbPage(pPg);
41842       if( rc!=SQLITE_OK ){
41843         goto pager_acquire_err;
41844       }
41845     }
41846     pager_set_pagehash(pPg);
41847   }
41848
41849   return SQLITE_OK;
41850
41851 pager_acquire_err:
41852   assert( rc!=SQLITE_OK );
41853   if( pPg ){
41854     sqlite3PcacheDrop(pPg);
41855   }
41856   pagerUnlockIfUnused(pPager);
41857
41858   *ppPage = 0;
41859   return rc;
41860 }
41861
41862 /*
41863 ** Acquire a page if it is already in the in-memory cache.  Do
41864 ** not read the page from disk.  Return a pointer to the page,
41865 ** or 0 if the page is not in cache. 
41866 **
41867 ** See also sqlite3PagerGet().  The difference between this routine
41868 ** and sqlite3PagerGet() is that _get() will go to the disk and read
41869 ** in the page if the page is not already in cache.  This routine
41870 ** returns NULL if the page is not in cache or if a disk I/O error 
41871 ** has ever happened.
41872 */
41873 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
41874   PgHdr *pPg = 0;
41875   assert( pPager!=0 );
41876   assert( pgno!=0 );
41877   assert( pPager->pPCache!=0 );
41878   assert( pPager->eState>=PAGER_READER && pPager->eState!=PAGER_ERROR );
41879   sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
41880   return pPg;
41881 }
41882
41883 /*
41884 ** Release a page reference.
41885 **
41886 ** If the number of references to the page drop to zero, then the
41887 ** page is added to the LRU list.  When all references to all pages
41888 ** are released, a rollback occurs and the lock on the database is
41889 ** removed.
41890 */
41891 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
41892   if( pPg ){
41893     Pager *pPager = pPg->pPager;
41894     sqlite3PcacheRelease(pPg);
41895     pagerUnlockIfUnused(pPager);
41896   }
41897 }
41898
41899 /*
41900 ** This function is called at the start of every write transaction.
41901 ** There must already be a RESERVED or EXCLUSIVE lock on the database 
41902 ** file when this routine is called.
41903 **
41904 ** Open the journal file for pager pPager and write a journal header
41905 ** to the start of it. If there are active savepoints, open the sub-journal
41906 ** as well. This function is only used when the journal file is being 
41907 ** opened to write a rollback log for a transaction. It is not used 
41908 ** when opening a hot journal file to roll it back.
41909 **
41910 ** If the journal file is already open (as it may be in exclusive mode),
41911 ** then this function just writes a journal header to the start of the
41912 ** already open file. 
41913 **
41914 ** Whether or not the journal file is opened by this function, the
41915 ** Pager.pInJournal bitvec structure is allocated.
41916 **
41917 ** Return SQLITE_OK if everything is successful. Otherwise, return 
41918 ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or 
41919 ** an IO error code if opening or writing the journal file fails.
41920 */
41921 static int pager_open_journal(Pager *pPager){
41922   int rc = SQLITE_OK;                        /* Return code */
41923   sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
41924
41925   assert( pPager->eState==PAGER_WRITER_LOCKED );
41926   assert( assert_pager_state(pPager) );
41927   assert( pPager->pInJournal==0 );
41928   
41929   /* If already in the error state, this function is a no-op.  But on
41930   ** the other hand, this routine is never called if we are already in
41931   ** an error state. */
41932   if( NEVER(pPager->errCode) ) return pPager->errCode;
41933
41934   if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
41935     pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
41936     if( pPager->pInJournal==0 ){
41937       return SQLITE_NOMEM;
41938     }
41939   
41940     /* Open the journal file if it is not already open. */
41941     if( !isOpen(pPager->jfd) ){
41942       if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
41943         sqlite3MemJournalOpen(pPager->jfd);
41944       }else{
41945         const int flags =                   /* VFS flags to open journal file */
41946           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
41947           (pPager->tempFile ? 
41948             (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
41949             (SQLITE_OPEN_MAIN_JOURNAL)
41950           );
41951   #ifdef SQLITE_ENABLE_ATOMIC_WRITE
41952         rc = sqlite3JournalOpen(
41953             pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
41954         );
41955   #else
41956         rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
41957   #endif
41958       }
41959       assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
41960     }
41961   
41962   
41963     /* Write the first journal header to the journal file and open 
41964     ** the sub-journal if necessary.
41965     */
41966     if( rc==SQLITE_OK ){
41967       /* TODO: Check if all of these are really required. */
41968       pPager->nRec = 0;
41969       pPager->journalOff = 0;
41970       pPager->setMaster = 0;
41971       pPager->journalHdr = 0;
41972       rc = writeJournalHdr(pPager);
41973     }
41974   }
41975
41976   if( rc!=SQLITE_OK ){
41977     sqlite3BitvecDestroy(pPager->pInJournal);
41978     pPager->pInJournal = 0;
41979   }else{
41980     assert( pPager->eState==PAGER_WRITER_LOCKED );
41981     pPager->eState = PAGER_WRITER_CACHEMOD;
41982   }
41983
41984   return rc;
41985 }
41986
41987 /*
41988 ** Begin a write-transaction on the specified pager object. If a 
41989 ** write-transaction has already been opened, this function is a no-op.
41990 **
41991 ** If the exFlag argument is false, then acquire at least a RESERVED
41992 ** lock on the database file. If exFlag is true, then acquire at least
41993 ** an EXCLUSIVE lock. If such a lock is already held, no locking 
41994 ** functions need be called.
41995 **
41996 ** If the subjInMemory argument is non-zero, then any sub-journal opened
41997 ** within this transaction will be opened as an in-memory file. This
41998 ** has no effect if the sub-journal is already opened (as it may be when
41999 ** running in exclusive mode) or if the transaction does not require a
42000 ** sub-journal. If the subjInMemory argument is zero, then any required
42001 ** sub-journal is implemented in-memory if pPager is an in-memory database, 
42002 ** or using a temporary file otherwise.
42003 */
42004 SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
42005   int rc = SQLITE_OK;
42006
42007   if( pPager->errCode ) return pPager->errCode;
42008   assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
42009   pPager->subjInMemory = (u8)subjInMemory;
42010
42011   if( ALWAYS(pPager->eState==PAGER_READER) ){
42012     assert( pPager->pInJournal==0 );
42013
42014     if( pagerUseWal(pPager) ){
42015       /* If the pager is configured to use locking_mode=exclusive, and an
42016       ** exclusive lock on the database is not already held, obtain it now.
42017       */
42018       if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
42019         rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
42020         if( rc!=SQLITE_OK ){
42021           return rc;
42022         }
42023         sqlite3WalExclusiveMode(pPager->pWal, 1);
42024       }
42025
42026       /* Grab the write lock on the log file. If successful, upgrade to
42027       ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
42028       ** The busy-handler is not invoked if another connection already
42029       ** holds the write-lock. If possible, the upper layer will call it.
42030       */
42031       rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
42032     }else{
42033       /* Obtain a RESERVED lock on the database file. If the exFlag parameter
42034       ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
42035       ** busy-handler callback can be used when upgrading to the EXCLUSIVE
42036       ** lock, but not when obtaining the RESERVED lock.
42037       */
42038       rc = pagerLockDb(pPager, RESERVED_LOCK);
42039       if( rc==SQLITE_OK && exFlag ){
42040         rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
42041       }
42042     }
42043
42044     if( rc==SQLITE_OK ){
42045       /* Change to WRITER_LOCKED state.
42046       **
42047       ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
42048       ** when it has an open transaction, but never to DBMOD or FINISHED.
42049       ** This is because in those states the code to roll back savepoint 
42050       ** transactions may copy data from the sub-journal into the database 
42051       ** file as well as into the page cache. Which would be incorrect in 
42052       ** WAL mode.
42053       */
42054       pPager->eState = PAGER_WRITER_LOCKED;
42055       pPager->dbHintSize = pPager->dbSize;
42056       pPager->dbFileSize = pPager->dbSize;
42057       pPager->dbOrigSize = pPager->dbSize;
42058       pPager->journalOff = 0;
42059     }
42060
42061     assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
42062     assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
42063     assert( assert_pager_state(pPager) );
42064   }
42065
42066   PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
42067   return rc;
42068 }
42069
42070 /*
42071 ** Mark a single data page as writeable. The page is written into the 
42072 ** main journal or sub-journal as required. If the page is written into
42073 ** one of the journals, the corresponding bit is set in the 
42074 ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
42075 ** of any open savepoints as appropriate.
42076 */
42077 static int pager_write(PgHdr *pPg){
42078   void *pData = pPg->pData;
42079   Pager *pPager = pPg->pPager;
42080   int rc = SQLITE_OK;
42081
42082   /* This routine is not called unless a write-transaction has already 
42083   ** been started. The journal file may or may not be open at this point.
42084   ** It is never called in the ERROR state.
42085   */
42086   assert( pPager->eState==PAGER_WRITER_LOCKED
42087        || pPager->eState==PAGER_WRITER_CACHEMOD
42088        || pPager->eState==PAGER_WRITER_DBMOD
42089   );
42090   assert( assert_pager_state(pPager) );
42091
42092   /* If an error has been previously detected, report the same error
42093   ** again. This should not happen, but the check provides robustness. */
42094   if( NEVER(pPager->errCode) )  return pPager->errCode;
42095
42096   /* Higher-level routines never call this function if database is not
42097   ** writable.  But check anyway, just for robustness. */
42098   if( NEVER(pPager->readOnly) ) return SQLITE_PERM;
42099
42100   CHECK_PAGE(pPg);
42101
42102   /* The journal file needs to be opened. Higher level routines have already
42103   ** obtained the necessary locks to begin the write-transaction, but the
42104   ** rollback journal might not yet be open. Open it now if this is the case.
42105   **
42106   ** This is done before calling sqlite3PcacheMakeDirty() on the page. 
42107   ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
42108   ** an error might occur and the pager would end up in WRITER_LOCKED state
42109   ** with pages marked as dirty in the cache.
42110   */
42111   if( pPager->eState==PAGER_WRITER_LOCKED ){
42112     rc = pager_open_journal(pPager);
42113     if( rc!=SQLITE_OK ) return rc;
42114   }
42115   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
42116   assert( assert_pager_state(pPager) );
42117
42118   /* Mark the page as dirty.  If the page has already been written
42119   ** to the journal then we can return right away.
42120   */
42121   sqlite3PcacheMakeDirty(pPg);
42122   if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
42123     assert( !pagerUseWal(pPager) );
42124   }else{
42125   
42126     /* The transaction journal now exists and we have a RESERVED or an
42127     ** EXCLUSIVE lock on the main database file.  Write the current page to
42128     ** the transaction journal if it is not there already.
42129     */
42130     if( !pageInJournal(pPg) && !pagerUseWal(pPager) ){
42131       assert( pagerUseWal(pPager)==0 );
42132       if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
42133         u32 cksum;
42134         char *pData2;
42135         i64 iOff = pPager->journalOff;
42136
42137         /* We should never write to the journal file the page that
42138         ** contains the database locks.  The following assert verifies
42139         ** that we do not. */
42140         assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
42141
42142         assert( pPager->journalHdr<=pPager->journalOff );
42143         CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
42144         cksum = pager_cksum(pPager, (u8*)pData2);
42145
42146         /* Even if an IO or diskfull error occurs while journalling the
42147         ** page in the block above, set the need-sync flag for the page.
42148         ** Otherwise, when the transaction is rolled back, the logic in
42149         ** playback_one_page() will think that the page needs to be restored
42150         ** in the database file. And if an IO error occurs while doing so,
42151         ** then corruption may follow.
42152         */
42153         pPg->flags |= PGHDR_NEED_SYNC;
42154
42155         rc = write32bits(pPager->jfd, iOff, pPg->pgno);
42156         if( rc!=SQLITE_OK ) return rc;
42157         rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
42158         if( rc!=SQLITE_OK ) return rc;
42159         rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
42160         if( rc!=SQLITE_OK ) return rc;
42161
42162         IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno, 
42163                  pPager->journalOff, pPager->pageSize));
42164         PAGER_INCR(sqlite3_pager_writej_count);
42165         PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
42166              PAGERID(pPager), pPg->pgno, 
42167              ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
42168
42169         pPager->journalOff += 8 + pPager->pageSize;
42170         pPager->nRec++;
42171         assert( pPager->pInJournal!=0 );
42172         rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
42173         testcase( rc==SQLITE_NOMEM );
42174         assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
42175         rc |= addToSavepointBitvecs(pPager, pPg->pgno);
42176         if( rc!=SQLITE_OK ){
42177           assert( rc==SQLITE_NOMEM );
42178           return rc;
42179         }
42180       }else{
42181         if( pPager->eState!=PAGER_WRITER_DBMOD ){
42182           pPg->flags |= PGHDR_NEED_SYNC;
42183         }
42184         PAGERTRACE(("APPEND %d page %d needSync=%d\n",
42185                 PAGERID(pPager), pPg->pgno,
42186                ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
42187       }
42188     }
42189   
42190     /* If the statement journal is open and the page is not in it,
42191     ** then write the current page to the statement journal.  Note that
42192     ** the statement journal format differs from the standard journal format
42193     ** in that it omits the checksums and the header.
42194     */
42195     if( subjRequiresPage(pPg) ){
42196       rc = subjournalPage(pPg);
42197     }
42198   }
42199
42200   /* Update the database size and return.
42201   */
42202   if( pPager->dbSize<pPg->pgno ){
42203     pPager->dbSize = pPg->pgno;
42204   }
42205   return rc;
42206 }
42207
42208 /*
42209 ** Mark a data page as writeable. This routine must be called before 
42210 ** making changes to a page. The caller must check the return value 
42211 ** of this function and be careful not to change any page data unless 
42212 ** this routine returns SQLITE_OK.
42213 **
42214 ** The difference between this function and pager_write() is that this
42215 ** function also deals with the special case where 2 or more pages
42216 ** fit on a single disk sector. In this case all co-resident pages
42217 ** must have been written to the journal file before returning.
42218 **
42219 ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
42220 ** as appropriate. Otherwise, SQLITE_OK.
42221 */
42222 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
42223   int rc = SQLITE_OK;
42224
42225   PgHdr *pPg = pDbPage;
42226   Pager *pPager = pPg->pPager;
42227   Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
42228
42229   assert( pPager->eState>=PAGER_WRITER_LOCKED );
42230   assert( pPager->eState!=PAGER_ERROR );
42231   assert( assert_pager_state(pPager) );
42232
42233   if( nPagePerSector>1 ){
42234     Pgno nPageCount;          /* Total number of pages in database file */
42235     Pgno pg1;                 /* First page of the sector pPg is located on. */
42236     int nPage = 0;            /* Number of pages starting at pg1 to journal */
42237     int ii;                   /* Loop counter */
42238     int needSync = 0;         /* True if any page has PGHDR_NEED_SYNC */
42239
42240     /* Set the doNotSyncSpill flag to 1. This is because we cannot allow
42241     ** a journal header to be written between the pages journaled by
42242     ** this function.
42243     */
42244     assert( !MEMDB );
42245     assert( pPager->doNotSyncSpill==0 );
42246     pPager->doNotSyncSpill++;
42247
42248     /* This trick assumes that both the page-size and sector-size are
42249     ** an integer power of 2. It sets variable pg1 to the identifier
42250     ** of the first page of the sector pPg is located on.
42251     */
42252     pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
42253
42254     nPageCount = pPager->dbSize;
42255     if( pPg->pgno>nPageCount ){
42256       nPage = (pPg->pgno - pg1)+1;
42257     }else if( (pg1+nPagePerSector-1)>nPageCount ){
42258       nPage = nPageCount+1-pg1;
42259     }else{
42260       nPage = nPagePerSector;
42261     }
42262     assert(nPage>0);
42263     assert(pg1<=pPg->pgno);
42264     assert((pg1+nPage)>pPg->pgno);
42265
42266     for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
42267       Pgno pg = pg1+ii;
42268       PgHdr *pPage;
42269       if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
42270         if( pg!=PAGER_MJ_PGNO(pPager) ){
42271           rc = sqlite3PagerGet(pPager, pg, &pPage);
42272           if( rc==SQLITE_OK ){
42273             rc = pager_write(pPage);
42274             if( pPage->flags&PGHDR_NEED_SYNC ){
42275               needSync = 1;
42276             }
42277             sqlite3PagerUnref(pPage);
42278           }
42279         }
42280       }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
42281         if( pPage->flags&PGHDR_NEED_SYNC ){
42282           needSync = 1;
42283         }
42284         sqlite3PagerUnref(pPage);
42285       }
42286     }
42287
42288     /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages 
42289     ** starting at pg1, then it needs to be set for all of them. Because
42290     ** writing to any of these nPage pages may damage the others, the
42291     ** journal file must contain sync()ed copies of all of them
42292     ** before any of them can be written out to the database file.
42293     */
42294     if( rc==SQLITE_OK && needSync ){
42295       assert( !MEMDB );
42296       for(ii=0; ii<nPage; ii++){
42297         PgHdr *pPage = pager_lookup(pPager, pg1+ii);
42298         if( pPage ){
42299           pPage->flags |= PGHDR_NEED_SYNC;
42300           sqlite3PagerUnref(pPage);
42301         }
42302       }
42303     }
42304
42305     assert( pPager->doNotSyncSpill==1 );
42306     pPager->doNotSyncSpill--;
42307   }else{
42308     rc = pager_write(pDbPage);
42309   }
42310   return rc;
42311 }
42312
42313 /*
42314 ** Return TRUE if the page given in the argument was previously passed
42315 ** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
42316 ** to change the content of the page.
42317 */
42318 #ifndef NDEBUG
42319 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
42320   return pPg->flags&PGHDR_DIRTY;
42321 }
42322 #endif
42323
42324 /*
42325 ** A call to this routine tells the pager that it is not necessary to
42326 ** write the information on page pPg back to the disk, even though
42327 ** that page might be marked as dirty.  This happens, for example, when
42328 ** the page has been added as a leaf of the freelist and so its
42329 ** content no longer matters.
42330 **
42331 ** The overlying software layer calls this routine when all of the data
42332 ** on the given page is unused. The pager marks the page as clean so
42333 ** that it does not get written to disk.
42334 **
42335 ** Tests show that this optimization can quadruple the speed of large 
42336 ** DELETE operations.
42337 */
42338 SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
42339   Pager *pPager = pPg->pPager;
42340   if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
42341     PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
42342     IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
42343     pPg->flags |= PGHDR_DONT_WRITE;
42344     pager_set_pagehash(pPg);
42345   }
42346 }
42347
42348 /*
42349 ** This routine is called to increment the value of the database file 
42350 ** change-counter, stored as a 4-byte big-endian integer starting at 
42351 ** byte offset 24 of the pager file.  The secondary change counter at
42352 ** 92 is also updated, as is the SQLite version number at offset 96.
42353 **
42354 ** But this only happens if the pPager->changeCountDone flag is false.
42355 ** To avoid excess churning of page 1, the update only happens once.
42356 ** See also the pager_write_changecounter() routine that does an 
42357 ** unconditional update of the change counters.
42358 **
42359 ** If the isDirectMode flag is zero, then this is done by calling 
42360 ** sqlite3PagerWrite() on page 1, then modifying the contents of the
42361 ** page data. In this case the file will be updated when the current
42362 ** transaction is committed.
42363 **
42364 ** The isDirectMode flag may only be non-zero if the library was compiled
42365 ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
42366 ** if isDirect is non-zero, then the database file is updated directly
42367 ** by writing an updated version of page 1 using a call to the 
42368 ** sqlite3OsWrite() function.
42369 */
42370 static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
42371   int rc = SQLITE_OK;
42372
42373   assert( pPager->eState==PAGER_WRITER_CACHEMOD
42374        || pPager->eState==PAGER_WRITER_DBMOD
42375   );
42376   assert( assert_pager_state(pPager) );
42377
42378   /* Declare and initialize constant integer 'isDirect'. If the
42379   ** atomic-write optimization is enabled in this build, then isDirect
42380   ** is initialized to the value passed as the isDirectMode parameter
42381   ** to this function. Otherwise, it is always set to zero.
42382   **
42383   ** The idea is that if the atomic-write optimization is not
42384   ** enabled at compile time, the compiler can omit the tests of
42385   ** 'isDirect' below, as well as the block enclosed in the
42386   ** "if( isDirect )" condition.
42387   */
42388 #ifndef SQLITE_ENABLE_ATOMIC_WRITE
42389 # define DIRECT_MODE 0
42390   assert( isDirectMode==0 );
42391   UNUSED_PARAMETER(isDirectMode);
42392 #else
42393 # define DIRECT_MODE isDirectMode
42394 #endif
42395
42396   if( !pPager->changeCountDone && pPager->dbSize>0 ){
42397     PgHdr *pPgHdr;                /* Reference to page 1 */
42398
42399     assert( !pPager->tempFile && isOpen(pPager->fd) );
42400
42401     /* Open page 1 of the file for writing. */
42402     rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
42403     assert( pPgHdr==0 || rc==SQLITE_OK );
42404
42405     /* If page one was fetched successfully, and this function is not
42406     ** operating in direct-mode, make page 1 writable.  When not in 
42407     ** direct mode, page 1 is always held in cache and hence the PagerGet()
42408     ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
42409     */
42410     if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
42411       rc = sqlite3PagerWrite(pPgHdr);
42412     }
42413
42414     if( rc==SQLITE_OK ){
42415       /* Actually do the update of the change counter */
42416       pager_write_changecounter(pPgHdr);
42417
42418       /* If running in direct mode, write the contents of page 1 to the file. */
42419       if( DIRECT_MODE ){
42420         const void *zBuf;
42421         assert( pPager->dbFileSize>0 );
42422         CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
42423         if( rc==SQLITE_OK ){
42424           rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
42425         }
42426         if( rc==SQLITE_OK ){
42427           pPager->changeCountDone = 1;
42428         }
42429       }else{
42430         pPager->changeCountDone = 1;
42431       }
42432     }
42433
42434     /* Release the page reference. */
42435     sqlite3PagerUnref(pPgHdr);
42436   }
42437   return rc;
42438 }
42439
42440 /*
42441 ** Sync the database file to disk. This is a no-op for in-memory databases
42442 ** or pages with the Pager.noSync flag set.
42443 **
42444 ** If successful, or if called on a pager for which it is a no-op, this
42445 ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
42446 */
42447 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
42448   int rc = SQLITE_OK;
42449   if( !pPager->noSync ){
42450     assert( !MEMDB );
42451     rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
42452   }else if( isOpen(pPager->fd) ){
42453     assert( !MEMDB );
42454     sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC_OMITTED, (void *)&rc);
42455   }
42456   return rc;
42457 }
42458
42459 /*
42460 ** This function may only be called while a write-transaction is active in
42461 ** rollback. If the connection is in WAL mode, this call is a no-op. 
42462 ** Otherwise, if the connection does not already have an EXCLUSIVE lock on 
42463 ** the database file, an attempt is made to obtain one.
42464 **
42465 ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
42466 ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
42467 ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is 
42468 ** returned.
42469 */
42470 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
42471   int rc = SQLITE_OK;
42472   assert( pPager->eState==PAGER_WRITER_CACHEMOD 
42473        || pPager->eState==PAGER_WRITER_DBMOD 
42474        || pPager->eState==PAGER_WRITER_LOCKED 
42475   );
42476   assert( assert_pager_state(pPager) );
42477   if( 0==pagerUseWal(pPager) ){
42478     rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
42479   }
42480   return rc;
42481 }
42482
42483 /*
42484 ** Sync the database file for the pager pPager. zMaster points to the name
42485 ** of a master journal file that should be written into the individual
42486 ** journal file. zMaster may be NULL, which is interpreted as no master
42487 ** journal (a single database transaction).
42488 **
42489 ** This routine ensures that:
42490 **
42491 **   * The database file change-counter is updated,
42492 **   * the journal is synced (unless the atomic-write optimization is used),
42493 **   * all dirty pages are written to the database file, 
42494 **   * the database file is truncated (if required), and
42495 **   * the database file synced. 
42496 **
42497 ** The only thing that remains to commit the transaction is to finalize 
42498 ** (delete, truncate or zero the first part of) the journal file (or 
42499 ** delete the master journal file if specified).
42500 **
42501 ** Note that if zMaster==NULL, this does not overwrite a previous value
42502 ** passed to an sqlite3PagerCommitPhaseOne() call.
42503 **
42504 ** If the final parameter - noSync - is true, then the database file itself
42505 ** is not synced. The caller must call sqlite3PagerSync() directly to
42506 ** sync the database file before calling CommitPhaseTwo() to delete the
42507 ** journal file in this case.
42508 */
42509 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
42510   Pager *pPager,                  /* Pager object */
42511   const char *zMaster,            /* If not NULL, the master journal name */
42512   int noSync                      /* True to omit the xSync on the db file */
42513 ){
42514   int rc = SQLITE_OK;             /* Return code */
42515
42516   assert( pPager->eState==PAGER_WRITER_LOCKED
42517        || pPager->eState==PAGER_WRITER_CACHEMOD
42518        || pPager->eState==PAGER_WRITER_DBMOD
42519        || pPager->eState==PAGER_ERROR
42520   );
42521   assert( assert_pager_state(pPager) );
42522
42523   /* If a prior error occurred, report that error again. */
42524   if( NEVER(pPager->errCode) ) return pPager->errCode;
42525
42526   PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n", 
42527       pPager->zFilename, zMaster, pPager->dbSize));
42528
42529   /* If no database changes have been made, return early. */
42530   if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
42531
42532   if( MEMDB ){
42533     /* If this is an in-memory db, or no pages have been written to, or this
42534     ** function has already been called, it is mostly a no-op.  However, any
42535     ** backup in progress needs to be restarted.
42536     */
42537     sqlite3BackupRestart(pPager->pBackup);
42538   }else{
42539     if( pagerUseWal(pPager) ){
42540       PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
42541       PgHdr *pPageOne = 0;
42542       if( pList==0 ){
42543         /* Must have at least one page for the WAL commit flag.
42544         ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
42545         rc = sqlite3PagerGet(pPager, 1, &pPageOne);
42546         pList = pPageOne;
42547         pList->pDirty = 0;
42548       }
42549       assert( rc==SQLITE_OK );
42550       if( ALWAYS(pList) ){
42551         rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1, 
42552             (pPager->fullSync ? pPager->syncFlags : 0)
42553         );
42554       }
42555       sqlite3PagerUnref(pPageOne);
42556       if( rc==SQLITE_OK ){
42557         sqlite3PcacheCleanAll(pPager->pPCache);
42558       }
42559     }else{
42560       /* The following block updates the change-counter. Exactly how it
42561       ** does this depends on whether or not the atomic-update optimization
42562       ** was enabled at compile time, and if this transaction meets the 
42563       ** runtime criteria to use the operation: 
42564       **
42565       **    * The file-system supports the atomic-write property for
42566       **      blocks of size page-size, and 
42567       **    * This commit is not part of a multi-file transaction, and
42568       **    * Exactly one page has been modified and store in the journal file.
42569       **
42570       ** If the optimization was not enabled at compile time, then the
42571       ** pager_incr_changecounter() function is called to update the change
42572       ** counter in 'indirect-mode'. If the optimization is compiled in but
42573       ** is not applicable to this transaction, call sqlite3JournalCreate()
42574       ** to make sure the journal file has actually been created, then call
42575       ** pager_incr_changecounter() to update the change-counter in indirect
42576       ** mode. 
42577       **
42578       ** Otherwise, if the optimization is both enabled and applicable,
42579       ** then call pager_incr_changecounter() to update the change-counter
42580       ** in 'direct' mode. In this case the journal file will never be
42581       ** created for this transaction.
42582       */
42583   #ifdef SQLITE_ENABLE_ATOMIC_WRITE
42584       PgHdr *pPg;
42585       assert( isOpen(pPager->jfd) 
42586            || pPager->journalMode==PAGER_JOURNALMODE_OFF 
42587            || pPager->journalMode==PAGER_JOURNALMODE_WAL 
42588       );
42589       if( !zMaster && isOpen(pPager->jfd) 
42590        && pPager->journalOff==jrnlBufferSize(pPager) 
42591        && pPager->dbSize>=pPager->dbOrigSize
42592        && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
42593       ){
42594         /* Update the db file change counter via the direct-write method. The 
42595         ** following call will modify the in-memory representation of page 1 
42596         ** to include the updated change counter and then write page 1 
42597         ** directly to the database file. Because of the atomic-write 
42598         ** property of the host file-system, this is safe.
42599         */
42600         rc = pager_incr_changecounter(pPager, 1);
42601       }else{
42602         rc = sqlite3JournalCreate(pPager->jfd);
42603         if( rc==SQLITE_OK ){
42604           rc = pager_incr_changecounter(pPager, 0);
42605         }
42606       }
42607   #else
42608       rc = pager_incr_changecounter(pPager, 0);
42609   #endif
42610       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
42611   
42612       /* If this transaction has made the database smaller, then all pages
42613       ** being discarded by the truncation must be written to the journal
42614       ** file. This can only happen in auto-vacuum mode.
42615       **
42616       ** Before reading the pages with page numbers larger than the 
42617       ** current value of Pager.dbSize, set dbSize back to the value
42618       ** that it took at the start of the transaction. Otherwise, the
42619       ** calls to sqlite3PagerGet() return zeroed pages instead of 
42620       ** reading data from the database file.
42621       */
42622   #ifndef SQLITE_OMIT_AUTOVACUUM
42623       if( pPager->dbSize<pPager->dbOrigSize 
42624        && pPager->journalMode!=PAGER_JOURNALMODE_OFF
42625       ){
42626         Pgno i;                                   /* Iterator variable */
42627         const Pgno iSkip = PAGER_MJ_PGNO(pPager); /* Pending lock page */
42628         const Pgno dbSize = pPager->dbSize;       /* Database image size */ 
42629         pPager->dbSize = pPager->dbOrigSize;
42630         for( i=dbSize+1; i<=pPager->dbOrigSize; i++ ){
42631           if( !sqlite3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){
42632             PgHdr *pPage;             /* Page to journal */
42633             rc = sqlite3PagerGet(pPager, i, &pPage);
42634             if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
42635             rc = sqlite3PagerWrite(pPage);
42636             sqlite3PagerUnref(pPage);
42637             if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
42638           }
42639         }
42640         pPager->dbSize = dbSize;
42641       } 
42642   #endif
42643   
42644       /* Write the master journal name into the journal file. If a master 
42645       ** journal file name has already been written to the journal file, 
42646       ** or if zMaster is NULL (no master journal), then this call is a no-op.
42647       */
42648       rc = writeMasterJournal(pPager, zMaster);
42649       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
42650   
42651       /* Sync the journal file and write all dirty pages to the database.
42652       ** If the atomic-update optimization is being used, this sync will not 
42653       ** create the journal file or perform any real IO.
42654       **
42655       ** Because the change-counter page was just modified, unless the
42656       ** atomic-update optimization is used it is almost certain that the
42657       ** journal requires a sync here. However, in locking_mode=exclusive
42658       ** on a system under memory pressure it is just possible that this is 
42659       ** not the case. In this case it is likely enough that the redundant
42660       ** xSync() call will be changed to a no-op by the OS anyhow. 
42661       */
42662       rc = syncJournal(pPager, 0);
42663       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
42664   
42665       rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
42666       if( rc!=SQLITE_OK ){
42667         assert( rc!=SQLITE_IOERR_BLOCKED );
42668         goto commit_phase_one_exit;
42669       }
42670       sqlite3PcacheCleanAll(pPager->pPCache);
42671   
42672       /* If the file on disk is not the same size as the database image,
42673       ** then use pager_truncate to grow or shrink the file here.
42674       */
42675       if( pPager->dbSize!=pPager->dbFileSize ){
42676         Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
42677         assert( pPager->eState==PAGER_WRITER_DBMOD );
42678         rc = pager_truncate(pPager, nNew);
42679         if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
42680       }
42681   
42682       /* Finally, sync the database file. */
42683       if( !noSync ){
42684         rc = sqlite3PagerSync(pPager);
42685       }
42686       IOTRACE(("DBSYNC %p\n", pPager))
42687     }
42688   }
42689
42690 commit_phase_one_exit:
42691   if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
42692     pPager->eState = PAGER_WRITER_FINISHED;
42693   }
42694   return rc;
42695 }
42696
42697
42698 /*
42699 ** When this function is called, the database file has been completely
42700 ** updated to reflect the changes made by the current transaction and
42701 ** synced to disk. The journal file still exists in the file-system 
42702 ** though, and if a failure occurs at this point it will eventually
42703 ** be used as a hot-journal and the current transaction rolled back.
42704 **
42705 ** This function finalizes the journal file, either by deleting, 
42706 ** truncating or partially zeroing it, so that it cannot be used 
42707 ** for hot-journal rollback. Once this is done the transaction is
42708 ** irrevocably committed.
42709 **
42710 ** If an error occurs, an IO error code is returned and the pager
42711 ** moves into the error state. Otherwise, SQLITE_OK is returned.
42712 */
42713 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
42714   int rc = SQLITE_OK;                  /* Return code */
42715
42716   /* This routine should not be called if a prior error has occurred.
42717   ** But if (due to a coding error elsewhere in the system) it does get
42718   ** called, just return the same error code without doing anything. */
42719   if( NEVER(pPager->errCode) ) return pPager->errCode;
42720
42721   assert( pPager->eState==PAGER_WRITER_LOCKED
42722        || pPager->eState==PAGER_WRITER_FINISHED
42723        || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
42724   );
42725   assert( assert_pager_state(pPager) );
42726
42727   /* An optimization. If the database was not actually modified during
42728   ** this transaction, the pager is running in exclusive-mode and is
42729   ** using persistent journals, then this function is a no-op.
42730   **
42731   ** The start of the journal file currently contains a single journal 
42732   ** header with the nRec field set to 0. If such a journal is used as
42733   ** a hot-journal during hot-journal rollback, 0 changes will be made
42734   ** to the database file. So there is no need to zero the journal 
42735   ** header. Since the pager is in exclusive mode, there is no need
42736   ** to drop any locks either.
42737   */
42738   if( pPager->eState==PAGER_WRITER_LOCKED 
42739    && pPager->exclusiveMode 
42740    && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
42741   ){
42742     assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
42743     pPager->eState = PAGER_READER;
42744     return SQLITE_OK;
42745   }
42746
42747   PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
42748   rc = pager_end_transaction(pPager, pPager->setMaster);
42749   return pager_error(pPager, rc);
42750 }
42751
42752 /*
42753 ** If a write transaction is open, then all changes made within the 
42754 ** transaction are reverted and the current write-transaction is closed.
42755 ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
42756 ** state if an error occurs.
42757 **
42758 ** If the pager is already in PAGER_ERROR state when this function is called,
42759 ** it returns Pager.errCode immediately. No work is performed in this case.
42760 **
42761 ** Otherwise, in rollback mode, this function performs two functions:
42762 **
42763 **   1) It rolls back the journal file, restoring all database file and 
42764 **      in-memory cache pages to the state they were in when the transaction
42765 **      was opened, and
42766 **
42767 **   2) It finalizes the journal file, so that it is not used for hot
42768 **      rollback at any point in the future.
42769 **
42770 ** Finalization of the journal file (task 2) is only performed if the 
42771 ** rollback is successful.
42772 **
42773 ** In WAL mode, all cache-entries containing data modified within the
42774 ** current transaction are either expelled from the cache or reverted to
42775 ** their pre-transaction state by re-reading data from the database or
42776 ** WAL files. The WAL transaction is then closed.
42777 */
42778 SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
42779   int rc = SQLITE_OK;                  /* Return code */
42780   PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
42781
42782   /* PagerRollback() is a no-op if called in READER or OPEN state. If
42783   ** the pager is already in the ERROR state, the rollback is not 
42784   ** attempted here. Instead, the error code is returned to the caller.
42785   */
42786   assert( assert_pager_state(pPager) );
42787   if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
42788   if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
42789
42790   if( pagerUseWal(pPager) ){
42791     int rc2;
42792     rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
42793     rc2 = pager_end_transaction(pPager, pPager->setMaster);
42794     if( rc==SQLITE_OK ) rc = rc2;
42795   }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
42796     int eState = pPager->eState;
42797     rc = pager_end_transaction(pPager, 0);
42798     if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
42799       /* This can happen using journal_mode=off. Move the pager to the error 
42800       ** state to indicate that the contents of the cache may not be trusted.
42801       ** Any active readers will get SQLITE_ABORT.
42802       */
42803       pPager->errCode = SQLITE_ABORT;
42804       pPager->eState = PAGER_ERROR;
42805       return rc;
42806     }
42807   }else{
42808     rc = pager_playback(pPager, 0);
42809   }
42810
42811   assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
42812   assert( rc==SQLITE_OK || rc==SQLITE_FULL || (rc&0xFF)==SQLITE_IOERR );
42813
42814   /* If an error occurs during a ROLLBACK, we can no longer trust the pager
42815   ** cache. So call pager_error() on the way out to make any error persistent.
42816   */
42817   return pager_error(pPager, rc);
42818 }
42819
42820 /*
42821 ** Return TRUE if the database file is opened read-only.  Return FALSE
42822 ** if the database is (in theory) writable.
42823 */
42824 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
42825   return pPager->readOnly;
42826 }
42827
42828 /*
42829 ** Return the number of references to the pager.
42830 */
42831 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
42832   return sqlite3PcacheRefCount(pPager->pPCache);
42833 }
42834
42835 /*
42836 ** Return the approximate number of bytes of memory currently
42837 ** used by the pager and its associated cache.
42838 */
42839 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
42840   int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
42841                                      + 5*sizeof(void*);
42842   return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
42843            + sqlite3MallocSize(pPager)
42844            + pPager->pageSize;
42845 }
42846
42847 /*
42848 ** Return the number of references to the specified page.
42849 */
42850 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
42851   return sqlite3PcachePageRefcount(pPage);
42852 }
42853
42854 #ifdef SQLITE_TEST
42855 /*
42856 ** This routine is used for testing and analysis only.
42857 */
42858 SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
42859   static int a[11];
42860   a[0] = sqlite3PcacheRefCount(pPager->pPCache);
42861   a[1] = sqlite3PcachePagecount(pPager->pPCache);
42862   a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
42863   a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
42864   a[4] = pPager->eState;
42865   a[5] = pPager->errCode;
42866   a[6] = pPager->nHit;
42867   a[7] = pPager->nMiss;
42868   a[8] = 0;  /* Used to be pPager->nOvfl */
42869   a[9] = pPager->nRead;
42870   a[10] = pPager->nWrite;
42871   return a;
42872 }
42873 #endif
42874
42875 /*
42876 ** Return true if this is an in-memory pager.
42877 */
42878 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
42879   return MEMDB;
42880 }
42881
42882 /*
42883 ** Check that there are at least nSavepoint savepoints open. If there are
42884 ** currently less than nSavepoints open, then open one or more savepoints
42885 ** to make up the difference. If the number of savepoints is already
42886 ** equal to nSavepoint, then this function is a no-op.
42887 **
42888 ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error 
42889 ** occurs while opening the sub-journal file, then an IO error code is
42890 ** returned. Otherwise, SQLITE_OK.
42891 */
42892 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
42893   int rc = SQLITE_OK;                       /* Return code */
42894   int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
42895
42896   assert( pPager->eState>=PAGER_WRITER_LOCKED );
42897   assert( assert_pager_state(pPager) );
42898
42899   if( nSavepoint>nCurrent && pPager->useJournal ){
42900     int ii;                                 /* Iterator variable */
42901     PagerSavepoint *aNew;                   /* New Pager.aSavepoint array */
42902
42903     /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
42904     ** if the allocation fails. Otherwise, zero the new portion in case a 
42905     ** malloc failure occurs while populating it in the for(...) loop below.
42906     */
42907     aNew = (PagerSavepoint *)sqlite3Realloc(
42908         pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
42909     );
42910     if( !aNew ){
42911       return SQLITE_NOMEM;
42912     }
42913     memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
42914     pPager->aSavepoint = aNew;
42915
42916     /* Populate the PagerSavepoint structures just allocated. */
42917     for(ii=nCurrent; ii<nSavepoint; ii++){
42918       aNew[ii].nOrig = pPager->dbSize;
42919       if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
42920         aNew[ii].iOffset = pPager->journalOff;
42921       }else{
42922         aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
42923       }
42924       aNew[ii].iSubRec = pPager->nSubRec;
42925       aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
42926       if( !aNew[ii].pInSavepoint ){
42927         return SQLITE_NOMEM;
42928       }
42929       if( pagerUseWal(pPager) ){
42930         sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
42931       }
42932       pPager->nSavepoint = ii+1;
42933     }
42934     assert( pPager->nSavepoint==nSavepoint );
42935     assertTruncateConstraint(pPager);
42936   }
42937
42938   return rc;
42939 }
42940
42941 /*
42942 ** This function is called to rollback or release (commit) a savepoint.
42943 ** The savepoint to release or rollback need not be the most recently 
42944 ** created savepoint.
42945 **
42946 ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
42947 ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
42948 ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
42949 ** that have occurred since the specified savepoint was created.
42950 **
42951 ** The savepoint to rollback or release is identified by parameter 
42952 ** iSavepoint. A value of 0 means to operate on the outermost savepoint
42953 ** (the first created). A value of (Pager.nSavepoint-1) means operate
42954 ** on the most recently created savepoint. If iSavepoint is greater than
42955 ** (Pager.nSavepoint-1), then this function is a no-op.
42956 **
42957 ** If a negative value is passed to this function, then the current
42958 ** transaction is rolled back. This is different to calling 
42959 ** sqlite3PagerRollback() because this function does not terminate
42960 ** the transaction or unlock the database, it just restores the 
42961 ** contents of the database to its original state. 
42962 **
42963 ** In any case, all savepoints with an index greater than iSavepoint 
42964 ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
42965 ** then savepoint iSavepoint is also destroyed.
42966 **
42967 ** This function may return SQLITE_NOMEM if a memory allocation fails,
42968 ** or an IO error code if an IO error occurs while rolling back a 
42969 ** savepoint. If no errors occur, SQLITE_OK is returned.
42970 */ 
42971 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
42972   int rc = pPager->errCode;       /* Return code */
42973
42974   assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
42975   assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
42976
42977   if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
42978     int ii;            /* Iterator variable */
42979     int nNew;          /* Number of remaining savepoints after this op. */
42980
42981     /* Figure out how many savepoints will still be active after this
42982     ** operation. Store this value in nNew. Then free resources associated 
42983     ** with any savepoints that are destroyed by this operation.
42984     */
42985     nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
42986     for(ii=nNew; ii<pPager->nSavepoint; ii++){
42987       sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
42988     }
42989     pPager->nSavepoint = nNew;
42990
42991     /* If this is a release of the outermost savepoint, truncate 
42992     ** the sub-journal to zero bytes in size. */
42993     if( op==SAVEPOINT_RELEASE ){
42994       if( nNew==0 && isOpen(pPager->sjfd) ){
42995         /* Only truncate if it is an in-memory sub-journal. */
42996         if( sqlite3IsMemJournal(pPager->sjfd) ){
42997           rc = sqlite3OsTruncate(pPager->sjfd, 0);
42998           assert( rc==SQLITE_OK );
42999         }
43000         pPager->nSubRec = 0;
43001       }
43002     }
43003     /* Else this is a rollback operation, playback the specified savepoint.
43004     ** If this is a temp-file, it is possible that the journal file has
43005     ** not yet been opened. In this case there have been no changes to
43006     ** the database file, so the playback operation can be skipped.
43007     */
43008     else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
43009       PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
43010       rc = pagerPlaybackSavepoint(pPager, pSavepoint);
43011       assert(rc!=SQLITE_DONE);
43012     }
43013   }
43014
43015   return rc;
43016 }
43017
43018 /*
43019 ** Return the full pathname of the database file.
43020 */
43021 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager){
43022   return pPager->zFilename;
43023 }
43024
43025 /*
43026 ** Return the VFS structure for the pager.
43027 */
43028 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
43029   return pPager->pVfs;
43030 }
43031
43032 /*
43033 ** Return the file handle for the database file associated
43034 ** with the pager.  This might return NULL if the file has
43035 ** not yet been opened.
43036 */
43037 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
43038   return pPager->fd;
43039 }
43040
43041 /*
43042 ** Return the full pathname of the journal file.
43043 */
43044 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
43045   return pPager->zJournal;
43046 }
43047
43048 /*
43049 ** Return true if fsync() calls are disabled for this pager.  Return FALSE
43050 ** if fsync()s are executed normally.
43051 */
43052 SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
43053   return pPager->noSync;
43054 }
43055
43056 #ifdef SQLITE_HAS_CODEC
43057 /*
43058 ** Set or retrieve the codec for this pager
43059 */
43060 SQLITE_PRIVATE void sqlite3PagerSetCodec(
43061   Pager *pPager,
43062   void *(*xCodec)(void*,void*,Pgno,int),
43063   void (*xCodecSizeChng)(void*,int,int),
43064   void (*xCodecFree)(void*),
43065   void *pCodec
43066 ){
43067   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
43068   pPager->xCodec = pPager->memDb ? 0 : xCodec;
43069   pPager->xCodecSizeChng = xCodecSizeChng;
43070   pPager->xCodecFree = xCodecFree;
43071   pPager->pCodec = pCodec;
43072   pagerReportSize(pPager);
43073 }
43074 SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
43075   return pPager->pCodec;
43076 }
43077 #endif
43078
43079 #ifndef SQLITE_OMIT_AUTOVACUUM
43080 /*
43081 ** Move the page pPg to location pgno in the file.
43082 **
43083 ** There must be no references to the page previously located at
43084 ** pgno (which we call pPgOld) though that page is allowed to be
43085 ** in cache.  If the page previously located at pgno is not already
43086 ** in the rollback journal, it is not put there by by this routine.
43087 **
43088 ** References to the page pPg remain valid. Updating any
43089 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
43090 ** allocated along with the page) is the responsibility of the caller.
43091 **
43092 ** A transaction must be active when this routine is called. It used to be
43093 ** required that a statement transaction was not active, but this restriction
43094 ** has been removed (CREATE INDEX needs to move a page when a statement
43095 ** transaction is active).
43096 **
43097 ** If the fourth argument, isCommit, is non-zero, then this page is being
43098 ** moved as part of a database reorganization just before the transaction 
43099 ** is being committed. In this case, it is guaranteed that the database page 
43100 ** pPg refers to will not be written to again within this transaction.
43101 **
43102 ** This function may return SQLITE_NOMEM or an IO error code if an error
43103 ** occurs. Otherwise, it returns SQLITE_OK.
43104 */
43105 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
43106   PgHdr *pPgOld;               /* The page being overwritten. */
43107   Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
43108   int rc;                      /* Return code */
43109   Pgno origPgno;               /* The original page number */
43110
43111   assert( pPg->nRef>0 );
43112   assert( pPager->eState==PAGER_WRITER_CACHEMOD
43113        || pPager->eState==PAGER_WRITER_DBMOD
43114   );
43115   assert( assert_pager_state(pPager) );
43116
43117   /* In order to be able to rollback, an in-memory database must journal
43118   ** the page we are moving from.
43119   */
43120   if( MEMDB ){
43121     rc = sqlite3PagerWrite(pPg);
43122     if( rc ) return rc;
43123   }
43124
43125   /* If the page being moved is dirty and has not been saved by the latest
43126   ** savepoint, then save the current contents of the page into the 
43127   ** sub-journal now. This is required to handle the following scenario:
43128   **
43129   **   BEGIN;
43130   **     <journal page X, then modify it in memory>
43131   **     SAVEPOINT one;
43132   **       <Move page X to location Y>
43133   **     ROLLBACK TO one;
43134   **
43135   ** If page X were not written to the sub-journal here, it would not
43136   ** be possible to restore its contents when the "ROLLBACK TO one"
43137   ** statement were is processed.
43138   **
43139   ** subjournalPage() may need to allocate space to store pPg->pgno into
43140   ** one or more savepoint bitvecs. This is the reason this function
43141   ** may return SQLITE_NOMEM.
43142   */
43143   if( pPg->flags&PGHDR_DIRTY
43144    && subjRequiresPage(pPg)
43145    && SQLITE_OK!=(rc = subjournalPage(pPg))
43146   ){
43147     return rc;
43148   }
43149
43150   PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n", 
43151       PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
43152   IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
43153
43154   /* If the journal needs to be sync()ed before page pPg->pgno can
43155   ** be written to, store pPg->pgno in local variable needSyncPgno.
43156   **
43157   ** If the isCommit flag is set, there is no need to remember that
43158   ** the journal needs to be sync()ed before database page pPg->pgno 
43159   ** can be written to. The caller has already promised not to write to it.
43160   */
43161   if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
43162     needSyncPgno = pPg->pgno;
43163     assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
43164     assert( pPg->flags&PGHDR_DIRTY );
43165   }
43166
43167   /* If the cache contains a page with page-number pgno, remove it
43168   ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for 
43169   ** page pgno before the 'move' operation, it needs to be retained 
43170   ** for the page moved there.
43171   */
43172   pPg->flags &= ~PGHDR_NEED_SYNC;
43173   pPgOld = pager_lookup(pPager, pgno);
43174   assert( !pPgOld || pPgOld->nRef==1 );
43175   if( pPgOld ){
43176     pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
43177     if( MEMDB ){
43178       /* Do not discard pages from an in-memory database since we might
43179       ** need to rollback later.  Just move the page out of the way. */
43180       sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
43181     }else{
43182       sqlite3PcacheDrop(pPgOld);
43183     }
43184   }
43185
43186   origPgno = pPg->pgno;
43187   sqlite3PcacheMove(pPg, pgno);
43188   sqlite3PcacheMakeDirty(pPg);
43189
43190   /* For an in-memory database, make sure the original page continues
43191   ** to exist, in case the transaction needs to roll back.  Use pPgOld
43192   ** as the original page since it has already been allocated.
43193   */
43194   if( MEMDB ){
43195     assert( pPgOld );
43196     sqlite3PcacheMove(pPgOld, origPgno);
43197     sqlite3PagerUnref(pPgOld);
43198   }
43199
43200   if( needSyncPgno ){
43201     /* If needSyncPgno is non-zero, then the journal file needs to be 
43202     ** sync()ed before any data is written to database file page needSyncPgno.
43203     ** Currently, no such page exists in the page-cache and the 
43204     ** "is journaled" bitvec flag has been set. This needs to be remedied by
43205     ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
43206     ** flag.
43207     **
43208     ** If the attempt to load the page into the page-cache fails, (due
43209     ** to a malloc() or IO failure), clear the bit in the pInJournal[]
43210     ** array. Otherwise, if the page is loaded and written again in
43211     ** this transaction, it may be written to the database file before
43212     ** it is synced into the journal file. This way, it may end up in
43213     ** the journal file twice, but that is not a problem.
43214     */
43215     PgHdr *pPgHdr;
43216     rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
43217     if( rc!=SQLITE_OK ){
43218       if( needSyncPgno<=pPager->dbOrigSize ){
43219         assert( pPager->pTmpSpace!=0 );
43220         sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
43221       }
43222       return rc;
43223     }
43224     pPgHdr->flags |= PGHDR_NEED_SYNC;
43225     sqlite3PcacheMakeDirty(pPgHdr);
43226     sqlite3PagerUnref(pPgHdr);
43227   }
43228
43229   return SQLITE_OK;
43230 }
43231 #endif
43232
43233 /*
43234 ** Return a pointer to the data for the specified page.
43235 */
43236 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
43237   assert( pPg->nRef>0 || pPg->pPager->memDb );
43238   return pPg->pData;
43239 }
43240
43241 /*
43242 ** Return a pointer to the Pager.nExtra bytes of "extra" space 
43243 ** allocated along with the specified page.
43244 */
43245 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
43246   return pPg->pExtra;
43247 }
43248
43249 /*
43250 ** Get/set the locking-mode for this pager. Parameter eMode must be one
43251 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or 
43252 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
43253 ** the locking-mode is set to the value specified.
43254 **
43255 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
43256 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
43257 ** locking-mode.
43258 */
43259 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
43260   assert( eMode==PAGER_LOCKINGMODE_QUERY
43261             || eMode==PAGER_LOCKINGMODE_NORMAL
43262             || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
43263   assert( PAGER_LOCKINGMODE_QUERY<0 );
43264   assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
43265   assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
43266   if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
43267     pPager->exclusiveMode = (u8)eMode;
43268   }
43269   return (int)pPager->exclusiveMode;
43270 }
43271
43272 /*
43273 ** Set the journal-mode for this pager. Parameter eMode must be one of:
43274 **
43275 **    PAGER_JOURNALMODE_DELETE
43276 **    PAGER_JOURNALMODE_TRUNCATE
43277 **    PAGER_JOURNALMODE_PERSIST
43278 **    PAGER_JOURNALMODE_OFF
43279 **    PAGER_JOURNALMODE_MEMORY
43280 **    PAGER_JOURNALMODE_WAL
43281 **
43282 ** The journalmode is set to the value specified if the change is allowed.
43283 ** The change may be disallowed for the following reasons:
43284 **
43285 **   *  An in-memory database can only have its journal_mode set to _OFF
43286 **      or _MEMORY.
43287 **
43288 **   *  Temporary databases cannot have _WAL journalmode.
43289 **
43290 ** The returned indicate the current (possibly updated) journal-mode.
43291 */
43292 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
43293   u8 eOld = pPager->journalMode;    /* Prior journalmode */
43294
43295 #ifdef SQLITE_DEBUG
43296   /* The print_pager_state() routine is intended to be used by the debugger
43297   ** only.  We invoke it once here to suppress a compiler warning. */
43298   print_pager_state(pPager);
43299 #endif
43300
43301
43302   /* The eMode parameter is always valid */
43303   assert(      eMode==PAGER_JOURNALMODE_DELETE
43304             || eMode==PAGER_JOURNALMODE_TRUNCATE
43305             || eMode==PAGER_JOURNALMODE_PERSIST
43306             || eMode==PAGER_JOURNALMODE_OFF 
43307             || eMode==PAGER_JOURNALMODE_WAL 
43308             || eMode==PAGER_JOURNALMODE_MEMORY );
43309
43310   /* This routine is only called from the OP_JournalMode opcode, and
43311   ** the logic there will never allow a temporary file to be changed
43312   ** to WAL mode.
43313   */
43314   assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
43315
43316   /* Do allow the journalmode of an in-memory database to be set to
43317   ** anything other than MEMORY or OFF
43318   */
43319   if( MEMDB ){
43320     assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
43321     if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
43322       eMode = eOld;
43323     }
43324   }
43325
43326   if( eMode!=eOld ){
43327
43328     /* Change the journal mode. */
43329     assert( pPager->eState!=PAGER_ERROR );
43330     pPager->journalMode = (u8)eMode;
43331
43332     /* When transistioning from TRUNCATE or PERSIST to any other journal
43333     ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
43334     ** delete the journal file.
43335     */
43336     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
43337     assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
43338     assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
43339     assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
43340     assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
43341     assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
43342
43343     assert( isOpen(pPager->fd) || pPager->exclusiveMode );
43344     if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
43345
43346       /* In this case we would like to delete the journal file. If it is
43347       ** not possible, then that is not a problem. Deleting the journal file
43348       ** here is an optimization only.
43349       **
43350       ** Before deleting the journal file, obtain a RESERVED lock on the
43351       ** database file. This ensures that the journal file is not deleted
43352       ** while it is in use by some other client.
43353       */
43354       sqlite3OsClose(pPager->jfd);
43355       if( pPager->eLock>=RESERVED_LOCK ){
43356         sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
43357       }else{
43358         int rc = SQLITE_OK;
43359         int state = pPager->eState;
43360         assert( state==PAGER_OPEN || state==PAGER_READER );
43361         if( state==PAGER_OPEN ){
43362           rc = sqlite3PagerSharedLock(pPager);
43363         }
43364         if( pPager->eState==PAGER_READER ){
43365           assert( rc==SQLITE_OK );
43366           rc = pagerLockDb(pPager, RESERVED_LOCK);
43367         }
43368         if( rc==SQLITE_OK ){
43369           sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
43370         }
43371         if( rc==SQLITE_OK && state==PAGER_READER ){
43372           pagerUnlockDb(pPager, SHARED_LOCK);
43373         }else if( state==PAGER_OPEN ){
43374           pager_unlock(pPager);
43375         }
43376         assert( state==pPager->eState );
43377       }
43378     }
43379   }
43380
43381   /* Return the new journal mode */
43382   return (int)pPager->journalMode;
43383 }
43384
43385 /*
43386 ** Return the current journal mode.
43387 */
43388 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
43389   return (int)pPager->journalMode;
43390 }
43391
43392 /*
43393 ** Return TRUE if the pager is in a state where it is OK to change the
43394 ** journalmode.  Journalmode changes can only happen when the database
43395 ** is unmodified.
43396 */
43397 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
43398   assert( assert_pager_state(pPager) );
43399   if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
43400   if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
43401   return 1;
43402 }
43403
43404 /*
43405 ** Get/set the size-limit used for persistent journal files.
43406 **
43407 ** Setting the size limit to -1 means no limit is enforced.
43408 ** An attempt to set a limit smaller than -1 is a no-op.
43409 */
43410 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
43411   if( iLimit>=-1 ){
43412     pPager->journalSizeLimit = iLimit;
43413     sqlite3WalLimit(pPager->pWal, iLimit);
43414   }
43415   return pPager->journalSizeLimit;
43416 }
43417
43418 /*
43419 ** Return a pointer to the pPager->pBackup variable. The backup module
43420 ** in backup.c maintains the content of this variable. This module
43421 ** uses it opaquely as an argument to sqlite3BackupRestart() and
43422 ** sqlite3BackupUpdate() only.
43423 */
43424 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
43425   return &pPager->pBackup;
43426 }
43427
43428 #ifndef SQLITE_OMIT_WAL
43429 /*
43430 ** This function is called when the user invokes "PRAGMA wal_checkpoint",
43431 ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
43432 ** or wal_blocking_checkpoint() API functions.
43433 **
43434 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
43435 */
43436 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
43437   int rc = SQLITE_OK;
43438   if( pPager->pWal ){
43439     rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
43440         pPager->xBusyHandler, pPager->pBusyHandlerArg,
43441         pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
43442         pnLog, pnCkpt
43443     );
43444   }
43445   return rc;
43446 }
43447
43448 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
43449   return sqlite3WalCallback(pPager->pWal);
43450 }
43451
43452 /*
43453 ** Return true if the underlying VFS for the given pager supports the
43454 ** primitives necessary for write-ahead logging.
43455 */
43456 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
43457   const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
43458   return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
43459 }
43460
43461 /*
43462 ** Attempt to take an exclusive lock on the database file. If a PENDING lock
43463 ** is obtained instead, immediately release it.
43464 */
43465 static int pagerExclusiveLock(Pager *pPager){
43466   int rc;                         /* Return code */
43467
43468   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
43469   rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
43470   if( rc!=SQLITE_OK ){
43471     /* If the attempt to grab the exclusive lock failed, release the 
43472     ** pending lock that may have been obtained instead.  */
43473     pagerUnlockDb(pPager, SHARED_LOCK);
43474   }
43475
43476   return rc;
43477 }
43478
43479 /*
43480 ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in 
43481 ** exclusive-locking mode when this function is called, take an EXCLUSIVE
43482 ** lock on the database file and use heap-memory to store the wal-index
43483 ** in. Otherwise, use the normal shared-memory.
43484 */
43485 static int pagerOpenWal(Pager *pPager){
43486   int rc = SQLITE_OK;
43487
43488   assert( pPager->pWal==0 && pPager->tempFile==0 );
43489   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK || pPager->noReadlock);
43490
43491   /* If the pager is already in exclusive-mode, the WAL module will use 
43492   ** heap-memory for the wal-index instead of the VFS shared-memory 
43493   ** implementation. Take the exclusive lock now, before opening the WAL
43494   ** file, to make sure this is safe.
43495   */
43496   if( pPager->exclusiveMode ){
43497     rc = pagerExclusiveLock(pPager);
43498   }
43499
43500   /* Open the connection to the log file. If this operation fails, 
43501   ** (e.g. due to malloc() failure), return an error code.
43502   */
43503   if( rc==SQLITE_OK ){
43504     rc = sqlite3WalOpen(pPager->pVfs, 
43505         pPager->fd, pPager->zWal, pPager->exclusiveMode,
43506         pPager->journalSizeLimit, &pPager->pWal
43507     );
43508   }
43509
43510   return rc;
43511 }
43512
43513
43514 /*
43515 ** The caller must be holding a SHARED lock on the database file to call
43516 ** this function.
43517 **
43518 ** If the pager passed as the first argument is open on a real database
43519 ** file (not a temp file or an in-memory database), and the WAL file
43520 ** is not already open, make an attempt to open it now. If successful,
43521 ** return SQLITE_OK. If an error occurs or the VFS used by the pager does 
43522 ** not support the xShmXXX() methods, return an error code. *pbOpen is
43523 ** not modified in either case.
43524 **
43525 ** If the pager is open on a temp-file (or in-memory database), or if
43526 ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
43527 ** without doing anything.
43528 */
43529 SQLITE_PRIVATE int sqlite3PagerOpenWal(
43530   Pager *pPager,                  /* Pager object */
43531   int *pbOpen                     /* OUT: Set to true if call is a no-op */
43532 ){
43533   int rc = SQLITE_OK;             /* Return code */
43534
43535   assert( assert_pager_state(pPager) );
43536   assert( pPager->eState==PAGER_OPEN   || pbOpen );
43537   assert( pPager->eState==PAGER_READER || !pbOpen );
43538   assert( pbOpen==0 || *pbOpen==0 );
43539   assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
43540
43541   if( !pPager->tempFile && !pPager->pWal ){
43542     if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
43543
43544     /* Close any rollback journal previously open */
43545     sqlite3OsClose(pPager->jfd);
43546
43547     rc = pagerOpenWal(pPager);
43548     if( rc==SQLITE_OK ){
43549       pPager->journalMode = PAGER_JOURNALMODE_WAL;
43550       pPager->eState = PAGER_OPEN;
43551     }
43552   }else{
43553     *pbOpen = 1;
43554   }
43555
43556   return rc;
43557 }
43558
43559 /*
43560 ** This function is called to close the connection to the log file prior
43561 ** to switching from WAL to rollback mode.
43562 **
43563 ** Before closing the log file, this function attempts to take an 
43564 ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
43565 ** error (SQLITE_BUSY) is returned and the log connection is not closed.
43566 ** If successful, the EXCLUSIVE lock is not released before returning.
43567 */
43568 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
43569   int rc = SQLITE_OK;
43570
43571   assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
43572
43573   /* If the log file is not already open, but does exist in the file-system,
43574   ** it may need to be checkpointed before the connection can switch to
43575   ** rollback mode. Open it now so this can happen.
43576   */
43577   if( !pPager->pWal ){
43578     int logexists = 0;
43579     rc = pagerLockDb(pPager, SHARED_LOCK);
43580     if( rc==SQLITE_OK ){
43581       rc = sqlite3OsAccess(
43582           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
43583       );
43584     }
43585     if( rc==SQLITE_OK && logexists ){
43586       rc = pagerOpenWal(pPager);
43587     }
43588   }
43589     
43590   /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
43591   ** the database file, the log and log-summary files will be deleted.
43592   */
43593   if( rc==SQLITE_OK && pPager->pWal ){
43594     rc = pagerExclusiveLock(pPager);
43595     if( rc==SQLITE_OK ){
43596       rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
43597                            pPager->pageSize, (u8*)pPager->pTmpSpace);
43598       pPager->pWal = 0;
43599     }
43600   }
43601   return rc;
43602 }
43603
43604 #ifdef SQLITE_HAS_CODEC
43605 /*
43606 ** This function is called by the wal module when writing page content
43607 ** into the log file.
43608 **
43609 ** This function returns a pointer to a buffer containing the encrypted
43610 ** page content. If a malloc fails, this function may return NULL.
43611 */
43612 SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
43613   void *aData = 0;
43614   CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
43615   return aData;
43616 }
43617 #endif /* SQLITE_HAS_CODEC */
43618
43619 #endif /* !SQLITE_OMIT_WAL */
43620
43621 #endif /* SQLITE_OMIT_DISKIO */
43622
43623 /************** End of pager.c ***********************************************/
43624 /************** Begin file wal.c *********************************************/
43625 /*
43626 ** 2010 February 1
43627 **
43628 ** The author disclaims copyright to this source code.  In place of
43629 ** a legal notice, here is a blessing:
43630 **
43631 **    May you do good and not evil.
43632 **    May you find forgiveness for yourself and forgive others.
43633 **    May you share freely, never taking more than you give.
43634 **
43635 *************************************************************************
43636 **
43637 ** This file contains the implementation of a write-ahead log (WAL) used in 
43638 ** "journal_mode=WAL" mode.
43639 **
43640 ** WRITE-AHEAD LOG (WAL) FILE FORMAT
43641 **
43642 ** A WAL file consists of a header followed by zero or more "frames".
43643 ** Each frame records the revised content of a single page from the
43644 ** database file.  All changes to the database are recorded by writing
43645 ** frames into the WAL.  Transactions commit when a frame is written that
43646 ** contains a commit marker.  A single WAL can and usually does record 
43647 ** multiple transactions.  Periodically, the content of the WAL is
43648 ** transferred back into the database file in an operation called a
43649 ** "checkpoint".
43650 **
43651 ** A single WAL file can be used multiple times.  In other words, the
43652 ** WAL can fill up with frames and then be checkpointed and then new
43653 ** frames can overwrite the old ones.  A WAL always grows from beginning
43654 ** toward the end.  Checksums and counters attached to each frame are
43655 ** used to determine which frames within the WAL are valid and which
43656 ** are leftovers from prior checkpoints.
43657 **
43658 ** The WAL header is 32 bytes in size and consists of the following eight
43659 ** big-endian 32-bit unsigned integer values:
43660 **
43661 **     0: Magic number.  0x377f0682 or 0x377f0683
43662 **     4: File format version.  Currently 3007000
43663 **     8: Database page size.  Example: 1024
43664 **    12: Checkpoint sequence number
43665 **    16: Salt-1, random integer incremented with each checkpoint
43666 **    20: Salt-2, a different random integer changing with each ckpt
43667 **    24: Checksum-1 (first part of checksum for first 24 bytes of header).
43668 **    28: Checksum-2 (second part of checksum for first 24 bytes of header).
43669 **
43670 ** Immediately following the wal-header are zero or more frames. Each
43671 ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
43672 ** of page data. The frame-header is six big-endian 32-bit unsigned 
43673 ** integer values, as follows:
43674 **
43675 **     0: Page number.
43676 **     4: For commit records, the size of the database image in pages 
43677 **        after the commit. For all other records, zero.
43678 **     8: Salt-1 (copied from the header)
43679 **    12: Salt-2 (copied from the header)
43680 **    16: Checksum-1.
43681 **    20: Checksum-2.
43682 **
43683 ** A frame is considered valid if and only if the following conditions are
43684 ** true:
43685 **
43686 **    (1) The salt-1 and salt-2 values in the frame-header match
43687 **        salt values in the wal-header
43688 **
43689 **    (2) The checksum values in the final 8 bytes of the frame-header
43690 **        exactly match the checksum computed consecutively on the
43691 **        WAL header and the first 8 bytes and the content of all frames
43692 **        up to and including the current frame.
43693 **
43694 ** The checksum is computed using 32-bit big-endian integers if the
43695 ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
43696 ** is computed using little-endian if the magic number is 0x377f0682.
43697 ** The checksum values are always stored in the frame header in a
43698 ** big-endian format regardless of which byte order is used to compute
43699 ** the checksum.  The checksum is computed by interpreting the input as
43700 ** an even number of unsigned 32-bit integers: x[0] through x[N].  The
43701 ** algorithm used for the checksum is as follows:
43702 ** 
43703 **   for i from 0 to n-1 step 2:
43704 **     s0 += x[i] + s1;
43705 **     s1 += x[i+1] + s0;
43706 **   endfor
43707 **
43708 ** Note that s0 and s1 are both weighted checksums using fibonacci weights
43709 ** in reverse order (the largest fibonacci weight occurs on the first element
43710 ** of the sequence being summed.)  The s1 value spans all 32-bit 
43711 ** terms of the sequence whereas s0 omits the final term.
43712 **
43713 ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
43714 ** WAL is transferred into the database, then the database is VFS.xSync-ed.
43715 ** The VFS.xSync operations serve as write barriers - all writes launched
43716 ** before the xSync must complete before any write that launches after the
43717 ** xSync begins.
43718 **
43719 ** After each checkpoint, the salt-1 value is incremented and the salt-2
43720 ** value is randomized.  This prevents old and new frames in the WAL from
43721 ** being considered valid at the same time and being checkpointing together
43722 ** following a crash.
43723 **
43724 ** READER ALGORITHM
43725 **
43726 ** To read a page from the database (call it page number P), a reader
43727 ** first checks the WAL to see if it contains page P.  If so, then the
43728 ** last valid instance of page P that is a followed by a commit frame
43729 ** or is a commit frame itself becomes the value read.  If the WAL
43730 ** contains no copies of page P that are valid and which are a commit
43731 ** frame or are followed by a commit frame, then page P is read from
43732 ** the database file.
43733 **
43734 ** To start a read transaction, the reader records the index of the last
43735 ** valid frame in the WAL.  The reader uses this recorded "mxFrame" value
43736 ** for all subsequent read operations.  New transactions can be appended
43737 ** to the WAL, but as long as the reader uses its original mxFrame value
43738 ** and ignores the newly appended content, it will see a consistent snapshot
43739 ** of the database from a single point in time.  This technique allows
43740 ** multiple concurrent readers to view different versions of the database
43741 ** content simultaneously.
43742 **
43743 ** The reader algorithm in the previous paragraphs works correctly, but 
43744 ** because frames for page P can appear anywhere within the WAL, the
43745 ** reader has to scan the entire WAL looking for page P frames.  If the
43746 ** WAL is large (multiple megabytes is typical) that scan can be slow,
43747 ** and read performance suffers.  To overcome this problem, a separate
43748 ** data structure called the wal-index is maintained to expedite the
43749 ** search for frames of a particular page.
43750 ** 
43751 ** WAL-INDEX FORMAT
43752 **
43753 ** Conceptually, the wal-index is shared memory, though VFS implementations
43754 ** might choose to implement the wal-index using a mmapped file.  Because
43755 ** the wal-index is shared memory, SQLite does not support journal_mode=WAL 
43756 ** on a network filesystem.  All users of the database must be able to
43757 ** share memory.
43758 **
43759 ** The wal-index is transient.  After a crash, the wal-index can (and should
43760 ** be) reconstructed from the original WAL file.  In fact, the VFS is required
43761 ** to either truncate or zero the header of the wal-index when the last
43762 ** connection to it closes.  Because the wal-index is transient, it can
43763 ** use an architecture-specific format; it does not have to be cross-platform.
43764 ** Hence, unlike the database and WAL file formats which store all values
43765 ** as big endian, the wal-index can store multi-byte values in the native
43766 ** byte order of the host computer.
43767 **
43768 ** The purpose of the wal-index is to answer this question quickly:  Given
43769 ** a page number P, return the index of the last frame for page P in the WAL,
43770 ** or return NULL if there are no frames for page P in the WAL.
43771 **
43772 ** The wal-index consists of a header region, followed by an one or
43773 ** more index blocks.  
43774 **
43775 ** The wal-index header contains the total number of frames within the WAL
43776 ** in the the mxFrame field.  
43777 **
43778 ** Each index block except for the first contains information on 
43779 ** HASHTABLE_NPAGE frames. The first index block contains information on
43780 ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and 
43781 ** HASHTABLE_NPAGE are selected so that together the wal-index header and
43782 ** first index block are the same size as all other index blocks in the
43783 ** wal-index.
43784 **
43785 ** Each index block contains two sections, a page-mapping that contains the
43786 ** database page number associated with each wal frame, and a hash-table 
43787 ** that allows readers to query an index block for a specific page number.
43788 ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
43789 ** for the first index block) 32-bit page numbers. The first entry in the 
43790 ** first index-block contains the database page number corresponding to the
43791 ** first frame in the WAL file. The first entry in the second index block
43792 ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
43793 ** the log, and so on.
43794 **
43795 ** The last index block in a wal-index usually contains less than the full
43796 ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
43797 ** depending on the contents of the WAL file. This does not change the
43798 ** allocated size of the page-mapping array - the page-mapping array merely
43799 ** contains unused entries.
43800 **
43801 ** Even without using the hash table, the last frame for page P
43802 ** can be found by scanning the page-mapping sections of each index block
43803 ** starting with the last index block and moving toward the first, and
43804 ** within each index block, starting at the end and moving toward the
43805 ** beginning.  The first entry that equals P corresponds to the frame
43806 ** holding the content for that page.
43807 **
43808 ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
43809 ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
43810 ** hash table for each page number in the mapping section, so the hash 
43811 ** table is never more than half full.  The expected number of collisions 
43812 ** prior to finding a match is 1.  Each entry of the hash table is an
43813 ** 1-based index of an entry in the mapping section of the same
43814 ** index block.   Let K be the 1-based index of the largest entry in
43815 ** the mapping section.  (For index blocks other than the last, K will
43816 ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
43817 ** K will be (mxFrame%HASHTABLE_NPAGE).)  Unused slots of the hash table
43818 ** contain a value of 0.
43819 **
43820 ** To look for page P in the hash table, first compute a hash iKey on
43821 ** P as follows:
43822 **
43823 **      iKey = (P * 383) % HASHTABLE_NSLOT
43824 **
43825 ** Then start scanning entries of the hash table, starting with iKey
43826 ** (wrapping around to the beginning when the end of the hash table is
43827 ** reached) until an unused hash slot is found. Let the first unused slot
43828 ** be at index iUnused.  (iUnused might be less than iKey if there was
43829 ** wrap-around.) Because the hash table is never more than half full,
43830 ** the search is guaranteed to eventually hit an unused entry.  Let 
43831 ** iMax be the value between iKey and iUnused, closest to iUnused,
43832 ** where aHash[iMax]==P.  If there is no iMax entry (if there exists
43833 ** no hash slot such that aHash[i]==p) then page P is not in the
43834 ** current index block.  Otherwise the iMax-th mapping entry of the
43835 ** current index block corresponds to the last entry that references 
43836 ** page P.
43837 **
43838 ** A hash search begins with the last index block and moves toward the
43839 ** first index block, looking for entries corresponding to page P.  On
43840 ** average, only two or three slots in each index block need to be
43841 ** examined in order to either find the last entry for page P, or to
43842 ** establish that no such entry exists in the block.  Each index block
43843 ** holds over 4000 entries.  So two or three index blocks are sufficient
43844 ** to cover a typical 10 megabyte WAL file, assuming 1K pages.  8 or 10
43845 ** comparisons (on average) suffice to either locate a frame in the
43846 ** WAL or to establish that the frame does not exist in the WAL.  This
43847 ** is much faster than scanning the entire 10MB WAL.
43848 **
43849 ** Note that entries are added in order of increasing K.  Hence, one
43850 ** reader might be using some value K0 and a second reader that started
43851 ** at a later time (after additional transactions were added to the WAL
43852 ** and to the wal-index) might be using a different value K1, where K1>K0.
43853 ** Both readers can use the same hash table and mapping section to get
43854 ** the correct result.  There may be entries in the hash table with
43855 ** K>K0 but to the first reader, those entries will appear to be unused
43856 ** slots in the hash table and so the first reader will get an answer as
43857 ** if no values greater than K0 had ever been inserted into the hash table
43858 ** in the first place - which is what reader one wants.  Meanwhile, the
43859 ** second reader using K1 will see additional values that were inserted
43860 ** later, which is exactly what reader two wants.  
43861 **
43862 ** When a rollback occurs, the value of K is decreased. Hash table entries
43863 ** that correspond to frames greater than the new K value are removed
43864 ** from the hash table at this point.
43865 */
43866 #ifndef SQLITE_OMIT_WAL
43867
43868
43869 /*
43870 ** Trace output macros
43871 */
43872 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
43873 SQLITE_PRIVATE int sqlite3WalTrace = 0;
43874 # define WALTRACE(X)  if(sqlite3WalTrace) sqlite3DebugPrintf X
43875 #else
43876 # define WALTRACE(X)
43877 #endif
43878
43879 /*
43880 ** The maximum (and only) versions of the wal and wal-index formats
43881 ** that may be interpreted by this version of SQLite.
43882 **
43883 ** If a client begins recovering a WAL file and finds that (a) the checksum
43884 ** values in the wal-header are correct and (b) the version field is not
43885 ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
43886 **
43887 ** Similarly, if a client successfully reads a wal-index header (i.e. the 
43888 ** checksum test is successful) and finds that the version field is not
43889 ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
43890 ** returns SQLITE_CANTOPEN.
43891 */
43892 #define WAL_MAX_VERSION      3007000
43893 #define WALINDEX_MAX_VERSION 3007000
43894
43895 /*
43896 ** Indices of various locking bytes.   WAL_NREADER is the number
43897 ** of available reader locks and should be at least 3.
43898 */
43899 #define WAL_WRITE_LOCK         0
43900 #define WAL_ALL_BUT_WRITE      1
43901 #define WAL_CKPT_LOCK          1
43902 #define WAL_RECOVER_LOCK       2
43903 #define WAL_READ_LOCK(I)       (3+(I))
43904 #define WAL_NREADER            (SQLITE_SHM_NLOCK-3)
43905
43906
43907 /* Object declarations */
43908 typedef struct WalIndexHdr WalIndexHdr;
43909 typedef struct WalIterator WalIterator;
43910 typedef struct WalCkptInfo WalCkptInfo;
43911
43912
43913 /*
43914 ** The following object holds a copy of the wal-index header content.
43915 **
43916 ** The actual header in the wal-index consists of two copies of this
43917 ** object.
43918 **
43919 ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
43920 ** Or it can be 1 to represent a 65536-byte page.  The latter case was
43921 ** added in 3.7.1 when support for 64K pages was added.  
43922 */
43923 struct WalIndexHdr {
43924   u32 iVersion;                   /* Wal-index version */
43925   u32 unused;                     /* Unused (padding) field */
43926   u32 iChange;                    /* Counter incremented each transaction */
43927   u8 isInit;                      /* 1 when initialized */
43928   u8 bigEndCksum;                 /* True if checksums in WAL are big-endian */
43929   u16 szPage;                     /* Database page size in bytes. 1==64K */
43930   u32 mxFrame;                    /* Index of last valid frame in the WAL */
43931   u32 nPage;                      /* Size of database in pages */
43932   u32 aFrameCksum[2];             /* Checksum of last frame in log */
43933   u32 aSalt[2];                   /* Two salt values copied from WAL header */
43934   u32 aCksum[2];                  /* Checksum over all prior fields */
43935 };
43936
43937 /*
43938 ** A copy of the following object occurs in the wal-index immediately
43939 ** following the second copy of the WalIndexHdr.  This object stores
43940 ** information used by checkpoint.
43941 **
43942 ** nBackfill is the number of frames in the WAL that have been written
43943 ** back into the database. (We call the act of moving content from WAL to
43944 ** database "backfilling".)  The nBackfill number is never greater than
43945 ** WalIndexHdr.mxFrame.  nBackfill can only be increased by threads
43946 ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
43947 ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
43948 ** mxFrame back to zero when the WAL is reset.
43949 **
43950 ** There is one entry in aReadMark[] for each reader lock.  If a reader
43951 ** holds read-lock K, then the value in aReadMark[K] is no greater than
43952 ** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)
43953 ** for any aReadMark[] means that entry is unused.  aReadMark[0] is 
43954 ** a special case; its value is never used and it exists as a place-holder
43955 ** to avoid having to offset aReadMark[] indexs by one.  Readers holding
43956 ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
43957 ** directly from the database.
43958 **
43959 ** The value of aReadMark[K] may only be changed by a thread that
43960 ** is holding an exclusive lock on WAL_READ_LOCK(K).  Thus, the value of
43961 ** aReadMark[K] cannot changed while there is a reader is using that mark
43962 ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
43963 **
43964 ** The checkpointer may only transfer frames from WAL to database where
43965 ** the frame numbers are less than or equal to every aReadMark[] that is
43966 ** in use (that is, every aReadMark[j] for which there is a corresponding
43967 ** WAL_READ_LOCK(j)).  New readers (usually) pick the aReadMark[] with the
43968 ** largest value and will increase an unused aReadMark[] to mxFrame if there
43969 ** is not already an aReadMark[] equal to mxFrame.  The exception to the
43970 ** previous sentence is when nBackfill equals mxFrame (meaning that everything
43971 ** in the WAL has been backfilled into the database) then new readers
43972 ** will choose aReadMark[0] which has value 0 and hence such reader will
43973 ** get all their all content directly from the database file and ignore 
43974 ** the WAL.
43975 **
43976 ** Writers normally append new frames to the end of the WAL.  However,
43977 ** if nBackfill equals mxFrame (meaning that all WAL content has been
43978 ** written back into the database) and if no readers are using the WAL
43979 ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
43980 ** the writer will first "reset" the WAL back to the beginning and start
43981 ** writing new content beginning at frame 1.
43982 **
43983 ** We assume that 32-bit loads are atomic and so no locks are needed in
43984 ** order to read from any aReadMark[] entries.
43985 */
43986 struct WalCkptInfo {
43987   u32 nBackfill;                  /* Number of WAL frames backfilled into DB */
43988   u32 aReadMark[WAL_NREADER];     /* Reader marks */
43989 };
43990 #define READMARK_NOT_USED  0xffffffff
43991
43992
43993 /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
43994 ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
43995 ** only support mandatory file-locks, we do not read or write data
43996 ** from the region of the file on which locks are applied.
43997 */
43998 #define WALINDEX_LOCK_OFFSET   (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
43999 #define WALINDEX_LOCK_RESERVED 16
44000 #define WALINDEX_HDR_SIZE      (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
44001
44002 /* Size of header before each frame in wal */
44003 #define WAL_FRAME_HDRSIZE 24
44004
44005 /* Size of write ahead log header, including checksum. */
44006 /* #define WAL_HDRSIZE 24 */
44007 #define WAL_HDRSIZE 32
44008
44009 /* WAL magic value. Either this value, or the same value with the least
44010 ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
44011 ** big-endian format in the first 4 bytes of a WAL file.
44012 **
44013 ** If the LSB is set, then the checksums for each frame within the WAL
44014 ** file are calculated by treating all data as an array of 32-bit 
44015 ** big-endian words. Otherwise, they are calculated by interpreting 
44016 ** all data as 32-bit little-endian words.
44017 */
44018 #define WAL_MAGIC 0x377f0682
44019
44020 /*
44021 ** Return the offset of frame iFrame in the write-ahead log file, 
44022 ** assuming a database page size of szPage bytes. The offset returned
44023 ** is to the start of the write-ahead log frame-header.
44024 */
44025 #define walFrameOffset(iFrame, szPage) (                               \
44026   WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE)         \
44027 )
44028
44029 /*
44030 ** An open write-ahead log file is represented by an instance of the
44031 ** following object.
44032 */
44033 struct Wal {
44034   sqlite3_vfs *pVfs;         /* The VFS used to create pDbFd */
44035   sqlite3_file *pDbFd;       /* File handle for the database file */
44036   sqlite3_file *pWalFd;      /* File handle for WAL file */
44037   u32 iCallback;             /* Value to pass to log callback (or 0) */
44038   i64 mxWalSize;             /* Truncate WAL to this size upon reset */
44039   int nWiData;               /* Size of array apWiData */
44040   volatile u32 **apWiData;   /* Pointer to wal-index content in memory */
44041   u32 szPage;                /* Database page size */
44042   i16 readLock;              /* Which read lock is being held.  -1 for none */
44043   u8 exclusiveMode;          /* Non-zero if connection is in exclusive mode */
44044   u8 writeLock;              /* True if in a write transaction */
44045   u8 ckptLock;               /* True if holding a checkpoint lock */
44046   u8 readOnly;               /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
44047   WalIndexHdr hdr;           /* Wal-index header for current transaction */
44048   const char *zWalName;      /* Name of WAL file */
44049   u32 nCkpt;                 /* Checkpoint sequence counter in the wal-header */
44050 #ifdef SQLITE_DEBUG
44051   u8 lockError;              /* True if a locking error has occurred */
44052 #endif
44053 };
44054
44055 /*
44056 ** Candidate values for Wal.exclusiveMode.
44057 */
44058 #define WAL_NORMAL_MODE     0
44059 #define WAL_EXCLUSIVE_MODE  1     
44060 #define WAL_HEAPMEMORY_MODE 2
44061
44062 /*
44063 ** Possible values for WAL.readOnly
44064 */
44065 #define WAL_RDWR        0    /* Normal read/write connection */
44066 #define WAL_RDONLY      1    /* The WAL file is readonly */
44067 #define WAL_SHM_RDONLY  2    /* The SHM file is readonly */
44068
44069 /*
44070 ** Each page of the wal-index mapping contains a hash-table made up of
44071 ** an array of HASHTABLE_NSLOT elements of the following type.
44072 */
44073 typedef u16 ht_slot;
44074
44075 /*
44076 ** This structure is used to implement an iterator that loops through
44077 ** all frames in the WAL in database page order. Where two or more frames
44078 ** correspond to the same database page, the iterator visits only the 
44079 ** frame most recently written to the WAL (in other words, the frame with
44080 ** the largest index).
44081 **
44082 ** The internals of this structure are only accessed by:
44083 **
44084 **   walIteratorInit() - Create a new iterator,
44085 **   walIteratorNext() - Step an iterator,
44086 **   walIteratorFree() - Free an iterator.
44087 **
44088 ** This functionality is used by the checkpoint code (see walCheckpoint()).
44089 */
44090 struct WalIterator {
44091   int iPrior;                     /* Last result returned from the iterator */
44092   int nSegment;                   /* Number of entries in aSegment[] */
44093   struct WalSegment {
44094     int iNext;                    /* Next slot in aIndex[] not yet returned */
44095     ht_slot *aIndex;              /* i0, i1, i2... such that aPgno[iN] ascend */
44096     u32 *aPgno;                   /* Array of page numbers. */
44097     int nEntry;                   /* Nr. of entries in aPgno[] and aIndex[] */
44098     int iZero;                    /* Frame number associated with aPgno[0] */
44099   } aSegment[1];                  /* One for every 32KB page in the wal-index */
44100 };
44101
44102 /*
44103 ** Define the parameters of the hash tables in the wal-index file. There
44104 ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
44105 ** wal-index.
44106 **
44107 ** Changing any of these constants will alter the wal-index format and
44108 ** create incompatibilities.
44109 */
44110 #define HASHTABLE_NPAGE      4096                 /* Must be power of 2 */
44111 #define HASHTABLE_HASH_1     383                  /* Should be prime */
44112 #define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */
44113
44114 /* 
44115 ** The block of page numbers associated with the first hash-table in a
44116 ** wal-index is smaller than usual. This is so that there is a complete
44117 ** hash-table on each aligned 32KB page of the wal-index.
44118 */
44119 #define HASHTABLE_NPAGE_ONE  (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
44120
44121 /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
44122 #define WALINDEX_PGSZ   (                                         \
44123     sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
44124 )
44125
44126 /*
44127 ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
44128 ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
44129 ** numbered from zero.
44130 **
44131 ** If this call is successful, *ppPage is set to point to the wal-index
44132 ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
44133 ** then an SQLite error code is returned and *ppPage is set to 0.
44134 */
44135 static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
44136   int rc = SQLITE_OK;
44137
44138   /* Enlarge the pWal->apWiData[] array if required */
44139   if( pWal->nWiData<=iPage ){
44140     int nByte = sizeof(u32*)*(iPage+1);
44141     volatile u32 **apNew;
44142     apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte);
44143     if( !apNew ){
44144       *ppPage = 0;
44145       return SQLITE_NOMEM;
44146     }
44147     memset((void*)&apNew[pWal->nWiData], 0,
44148            sizeof(u32*)*(iPage+1-pWal->nWiData));
44149     pWal->apWiData = apNew;
44150     pWal->nWiData = iPage+1;
44151   }
44152
44153   /* Request a pointer to the required page from the VFS */
44154   if( pWal->apWiData[iPage]==0 ){
44155     if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
44156       pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
44157       if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
44158     }else{
44159       rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ, 
44160           pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
44161       );
44162       if( rc==SQLITE_READONLY ){
44163         pWal->readOnly |= WAL_SHM_RDONLY;
44164         rc = SQLITE_OK;
44165       }
44166     }
44167   }
44168
44169   *ppPage = pWal->apWiData[iPage];
44170   assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
44171   return rc;
44172 }
44173
44174 /*
44175 ** Return a pointer to the WalCkptInfo structure in the wal-index.
44176 */
44177 static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
44178   assert( pWal->nWiData>0 && pWal->apWiData[0] );
44179   return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
44180 }
44181
44182 /*
44183 ** Return a pointer to the WalIndexHdr structure in the wal-index.
44184 */
44185 static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
44186   assert( pWal->nWiData>0 && pWal->apWiData[0] );
44187   return (volatile WalIndexHdr*)pWal->apWiData[0];
44188 }
44189
44190 /*
44191 ** The argument to this macro must be of type u32. On a little-endian
44192 ** architecture, it returns the u32 value that results from interpreting
44193 ** the 4 bytes as a big-endian value. On a big-endian architecture, it
44194 ** returns the value that would be produced by intepreting the 4 bytes
44195 ** of the input value as a little-endian integer.
44196 */
44197 #define BYTESWAP32(x) ( \
44198     (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8)  \
44199   + (((x)&0x00FF0000)>>8)  + (((x)&0xFF000000)>>24) \
44200 )
44201
44202 /*
44203 ** Generate or extend an 8 byte checksum based on the data in 
44204 ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
44205 ** initial values of 0 and 0 if aIn==NULL).
44206 **
44207 ** The checksum is written back into aOut[] before returning.
44208 **
44209 ** nByte must be a positive multiple of 8.
44210 */
44211 static void walChecksumBytes(
44212   int nativeCksum, /* True for native byte-order, false for non-native */
44213   u8 *a,           /* Content to be checksummed */
44214   int nByte,       /* Bytes of content in a[].  Must be a multiple of 8. */
44215   const u32 *aIn,  /* Initial checksum value input */
44216   u32 *aOut        /* OUT: Final checksum value output */
44217 ){
44218   u32 s1, s2;
44219   u32 *aData = (u32 *)a;
44220   u32 *aEnd = (u32 *)&a[nByte];
44221
44222   if( aIn ){
44223     s1 = aIn[0];
44224     s2 = aIn[1];
44225   }else{
44226     s1 = s2 = 0;
44227   }
44228
44229   assert( nByte>=8 );
44230   assert( (nByte&0x00000007)==0 );
44231
44232   if( nativeCksum ){
44233     do {
44234       s1 += *aData++ + s2;
44235       s2 += *aData++ + s1;
44236     }while( aData<aEnd );
44237   }else{
44238     do {
44239       s1 += BYTESWAP32(aData[0]) + s2;
44240       s2 += BYTESWAP32(aData[1]) + s1;
44241       aData += 2;
44242     }while( aData<aEnd );
44243   }
44244
44245   aOut[0] = s1;
44246   aOut[1] = s2;
44247 }
44248
44249 static void walShmBarrier(Wal *pWal){
44250   if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
44251     sqlite3OsShmBarrier(pWal->pDbFd);
44252   }
44253 }
44254
44255 /*
44256 ** Write the header information in pWal->hdr into the wal-index.
44257 **
44258 ** The checksum on pWal->hdr is updated before it is written.
44259 */
44260 static void walIndexWriteHdr(Wal *pWal){
44261   volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
44262   const int nCksum = offsetof(WalIndexHdr, aCksum);
44263
44264   assert( pWal->writeLock );
44265   pWal->hdr.isInit = 1;
44266   pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
44267   walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
44268   memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
44269   walShmBarrier(pWal);
44270   memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
44271 }
44272
44273 /*
44274 ** This function encodes a single frame header and writes it to a buffer
44275 ** supplied by the caller. A frame-header is made up of a series of 
44276 ** 4-byte big-endian integers, as follows:
44277 **
44278 **     0: Page number.
44279 **     4: For commit records, the size of the database image in pages 
44280 **        after the commit. For all other records, zero.
44281 **     8: Salt-1 (copied from the wal-header)
44282 **    12: Salt-2 (copied from the wal-header)
44283 **    16: Checksum-1.
44284 **    20: Checksum-2.
44285 */
44286 static void walEncodeFrame(
44287   Wal *pWal,                      /* The write-ahead log */
44288   u32 iPage,                      /* Database page number for frame */
44289   u32 nTruncate,                  /* New db size (or 0 for non-commit frames) */
44290   u8 *aData,                      /* Pointer to page data */
44291   u8 *aFrame                      /* OUT: Write encoded frame here */
44292 ){
44293   int nativeCksum;                /* True for native byte-order checksums */
44294   u32 *aCksum = pWal->hdr.aFrameCksum;
44295   assert( WAL_FRAME_HDRSIZE==24 );
44296   sqlite3Put4byte(&aFrame[0], iPage);
44297   sqlite3Put4byte(&aFrame[4], nTruncate);
44298   memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
44299
44300   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
44301   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
44302   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
44303
44304   sqlite3Put4byte(&aFrame[16], aCksum[0]);
44305   sqlite3Put4byte(&aFrame[20], aCksum[1]);
44306 }
44307
44308 /*
44309 ** Check to see if the frame with header in aFrame[] and content
44310 ** in aData[] is valid.  If it is a valid frame, fill *piPage and
44311 ** *pnTruncate and return true.  Return if the frame is not valid.
44312 */
44313 static int walDecodeFrame(
44314   Wal *pWal,                      /* The write-ahead log */
44315   u32 *piPage,                    /* OUT: Database page number for frame */
44316   u32 *pnTruncate,                /* OUT: New db size (or 0 if not commit) */
44317   u8 *aData,                      /* Pointer to page data (for checksum) */
44318   u8 *aFrame                      /* Frame data */
44319 ){
44320   int nativeCksum;                /* True for native byte-order checksums */
44321   u32 *aCksum = pWal->hdr.aFrameCksum;
44322   u32 pgno;                       /* Page number of the frame */
44323   assert( WAL_FRAME_HDRSIZE==24 );
44324
44325   /* A frame is only valid if the salt values in the frame-header
44326   ** match the salt values in the wal-header. 
44327   */
44328   if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
44329     return 0;
44330   }
44331
44332   /* A frame is only valid if the page number is creater than zero.
44333   */
44334   pgno = sqlite3Get4byte(&aFrame[0]);
44335   if( pgno==0 ){
44336     return 0;
44337   }
44338
44339   /* A frame is only valid if a checksum of the WAL header,
44340   ** all prior frams, the first 16 bytes of this frame-header, 
44341   ** and the frame-data matches the checksum in the last 8 
44342   ** bytes of this frame-header.
44343   */
44344   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
44345   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
44346   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
44347   if( aCksum[0]!=sqlite3Get4byte(&aFrame[16]) 
44348    || aCksum[1]!=sqlite3Get4byte(&aFrame[20]) 
44349   ){
44350     /* Checksum failed. */
44351     return 0;
44352   }
44353
44354   /* If we reach this point, the frame is valid.  Return the page number
44355   ** and the new database size.
44356   */
44357   *piPage = pgno;
44358   *pnTruncate = sqlite3Get4byte(&aFrame[4]);
44359   return 1;
44360 }
44361
44362
44363 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
44364 /*
44365 ** Names of locks.  This routine is used to provide debugging output and is not
44366 ** a part of an ordinary build.
44367 */
44368 static const char *walLockName(int lockIdx){
44369   if( lockIdx==WAL_WRITE_LOCK ){
44370     return "WRITE-LOCK";
44371   }else if( lockIdx==WAL_CKPT_LOCK ){
44372     return "CKPT-LOCK";
44373   }else if( lockIdx==WAL_RECOVER_LOCK ){
44374     return "RECOVER-LOCK";
44375   }else{
44376     static char zName[15];
44377     sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
44378                      lockIdx-WAL_READ_LOCK(0));
44379     return zName;
44380   }
44381 }
44382 #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
44383     
44384
44385 /*
44386 ** Set or release locks on the WAL.  Locks are either shared or exclusive.
44387 ** A lock cannot be moved directly between shared and exclusive - it must go
44388 ** through the unlocked state first.
44389 **
44390 ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
44391 */
44392 static int walLockShared(Wal *pWal, int lockIdx){
44393   int rc;
44394   if( pWal->exclusiveMode ) return SQLITE_OK;
44395   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
44396                         SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
44397   WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
44398             walLockName(lockIdx), rc ? "failed" : "ok"));
44399   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
44400   return rc;
44401 }
44402 static void walUnlockShared(Wal *pWal, int lockIdx){
44403   if( pWal->exclusiveMode ) return;
44404   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
44405                          SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
44406   WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
44407 }
44408 static int walLockExclusive(Wal *pWal, int lockIdx, int n){
44409   int rc;
44410   if( pWal->exclusiveMode ) return SQLITE_OK;
44411   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
44412                         SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
44413   WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
44414             walLockName(lockIdx), n, rc ? "failed" : "ok"));
44415   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
44416   return rc;
44417 }
44418 static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
44419   if( pWal->exclusiveMode ) return;
44420   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
44421                          SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
44422   WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
44423              walLockName(lockIdx), n));
44424 }
44425
44426 /*
44427 ** Compute a hash on a page number.  The resulting hash value must land
44428 ** between 0 and (HASHTABLE_NSLOT-1).  The walHashNext() function advances
44429 ** the hash to the next value in the event of a collision.
44430 */
44431 static int walHash(u32 iPage){
44432   assert( iPage>0 );
44433   assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
44434   return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
44435 }
44436 static int walNextHash(int iPriorHash){
44437   return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
44438 }
44439
44440 /* 
44441 ** Return pointers to the hash table and page number array stored on
44442 ** page iHash of the wal-index. The wal-index is broken into 32KB pages
44443 ** numbered starting from 0.
44444 **
44445 ** Set output variable *paHash to point to the start of the hash table
44446 ** in the wal-index file. Set *piZero to one less than the frame 
44447 ** number of the first frame indexed by this hash table. If a
44448 ** slot in the hash table is set to N, it refers to frame number 
44449 ** (*piZero+N) in the log.
44450 **
44451 ** Finally, set *paPgno so that *paPgno[1] is the page number of the
44452 ** first frame indexed by the hash table, frame (*piZero+1).
44453 */
44454 static int walHashGet(
44455   Wal *pWal,                      /* WAL handle */
44456   int iHash,                      /* Find the iHash'th table */
44457   volatile ht_slot **paHash,      /* OUT: Pointer to hash index */
44458   volatile u32 **paPgno,          /* OUT: Pointer to page number array */
44459   u32 *piZero                     /* OUT: Frame associated with *paPgno[0] */
44460 ){
44461   int rc;                         /* Return code */
44462   volatile u32 *aPgno;
44463
44464   rc = walIndexPage(pWal, iHash, &aPgno);
44465   assert( rc==SQLITE_OK || iHash>0 );
44466
44467   if( rc==SQLITE_OK ){
44468     u32 iZero;
44469     volatile ht_slot *aHash;
44470
44471     aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
44472     if( iHash==0 ){
44473       aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
44474       iZero = 0;
44475     }else{
44476       iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
44477     }
44478   
44479     *paPgno = &aPgno[-1];
44480     *paHash = aHash;
44481     *piZero = iZero;
44482   }
44483   return rc;
44484 }
44485
44486 /*
44487 ** Return the number of the wal-index page that contains the hash-table
44488 ** and page-number array that contain entries corresponding to WAL frame
44489 ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages 
44490 ** are numbered starting from 0.
44491 */
44492 static int walFramePage(u32 iFrame){
44493   int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
44494   assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
44495        && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
44496        && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
44497        && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
44498        && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
44499   );
44500   return iHash;
44501 }
44502
44503 /*
44504 ** Return the page number associated with frame iFrame in this WAL.
44505 */
44506 static u32 walFramePgno(Wal *pWal, u32 iFrame){
44507   int iHash = walFramePage(iFrame);
44508   if( iHash==0 ){
44509     return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
44510   }
44511   return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
44512 }
44513
44514 /*
44515 ** Remove entries from the hash table that point to WAL slots greater
44516 ** than pWal->hdr.mxFrame.
44517 **
44518 ** This function is called whenever pWal->hdr.mxFrame is decreased due
44519 ** to a rollback or savepoint.
44520 **
44521 ** At most only the hash table containing pWal->hdr.mxFrame needs to be
44522 ** updated.  Any later hash tables will be automatically cleared when
44523 ** pWal->hdr.mxFrame advances to the point where those hash tables are
44524 ** actually needed.
44525 */
44526 static void walCleanupHash(Wal *pWal){
44527   volatile ht_slot *aHash = 0;    /* Pointer to hash table to clear */
44528   volatile u32 *aPgno = 0;        /* Page number array for hash table */
44529   u32 iZero = 0;                  /* frame == (aHash[x]+iZero) */
44530   int iLimit = 0;                 /* Zero values greater than this */
44531   int nByte;                      /* Number of bytes to zero in aPgno[] */
44532   int i;                          /* Used to iterate through aHash[] */
44533
44534   assert( pWal->writeLock );
44535   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
44536   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
44537   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
44538
44539   if( pWal->hdr.mxFrame==0 ) return;
44540
44541   /* Obtain pointers to the hash-table and page-number array containing 
44542   ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
44543   ** that the page said hash-table and array reside on is already mapped.
44544   */
44545   assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
44546   assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
44547   walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
44548
44549   /* Zero all hash-table entries that correspond to frame numbers greater
44550   ** than pWal->hdr.mxFrame.
44551   */
44552   iLimit = pWal->hdr.mxFrame - iZero;
44553   assert( iLimit>0 );
44554   for(i=0; i<HASHTABLE_NSLOT; i++){
44555     if( aHash[i]>iLimit ){
44556       aHash[i] = 0;
44557     }
44558   }
44559   
44560   /* Zero the entries in the aPgno array that correspond to frames with
44561   ** frame numbers greater than pWal->hdr.mxFrame. 
44562   */
44563   nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
44564   memset((void *)&aPgno[iLimit+1], 0, nByte);
44565
44566 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
44567   /* Verify that the every entry in the mapping region is still reachable
44568   ** via the hash table even after the cleanup.
44569   */
44570   if( iLimit ){
44571     int i;           /* Loop counter */
44572     int iKey;        /* Hash key */
44573     for(i=1; i<=iLimit; i++){
44574       for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
44575         if( aHash[iKey]==i ) break;
44576       }
44577       assert( aHash[iKey]==i );
44578     }
44579   }
44580 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
44581 }
44582
44583
44584 /*
44585 ** Set an entry in the wal-index that will map database page number
44586 ** pPage into WAL frame iFrame.
44587 */
44588 static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
44589   int rc;                         /* Return code */
44590   u32 iZero = 0;                  /* One less than frame number of aPgno[1] */
44591   volatile u32 *aPgno = 0;        /* Page number array */
44592   volatile ht_slot *aHash = 0;    /* Hash table */
44593
44594   rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
44595
44596   /* Assuming the wal-index file was successfully mapped, populate the
44597   ** page number array and hash table entry.
44598   */
44599   if( rc==SQLITE_OK ){
44600     int iKey;                     /* Hash table key */
44601     int idx;                      /* Value to write to hash-table slot */
44602     int nCollide;                 /* Number of hash collisions */
44603
44604     idx = iFrame - iZero;
44605     assert( idx <= HASHTABLE_NSLOT/2 + 1 );
44606     
44607     /* If this is the first entry to be added to this hash-table, zero the
44608     ** entire hash table and aPgno[] array before proceding. 
44609     */
44610     if( idx==1 ){
44611       int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
44612       memset((void*)&aPgno[1], 0, nByte);
44613     }
44614
44615     /* If the entry in aPgno[] is already set, then the previous writer
44616     ** must have exited unexpectedly in the middle of a transaction (after
44617     ** writing one or more dirty pages to the WAL to free up memory). 
44618     ** Remove the remnants of that writers uncommitted transaction from 
44619     ** the hash-table before writing any new entries.
44620     */
44621     if( aPgno[idx] ){
44622       walCleanupHash(pWal);
44623       assert( !aPgno[idx] );
44624     }
44625
44626     /* Write the aPgno[] array entry and the hash-table slot. */
44627     nCollide = idx;
44628     for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
44629       if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
44630     }
44631     aPgno[idx] = iPage;
44632     aHash[iKey] = (ht_slot)idx;
44633
44634 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
44635     /* Verify that the number of entries in the hash table exactly equals
44636     ** the number of entries in the mapping region.
44637     */
44638     {
44639       int i;           /* Loop counter */
44640       int nEntry = 0;  /* Number of entries in the hash table */
44641       for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
44642       assert( nEntry==idx );
44643     }
44644
44645     /* Verify that the every entry in the mapping region is reachable
44646     ** via the hash table.  This turns out to be a really, really expensive
44647     ** thing to check, so only do this occasionally - not on every
44648     ** iteration.
44649     */
44650     if( (idx&0x3ff)==0 ){
44651       int i;           /* Loop counter */
44652       for(i=1; i<=idx; i++){
44653         for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
44654           if( aHash[iKey]==i ) break;
44655         }
44656         assert( aHash[iKey]==i );
44657       }
44658     }
44659 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
44660   }
44661
44662
44663   return rc;
44664 }
44665
44666
44667 /*
44668 ** Recover the wal-index by reading the write-ahead log file. 
44669 **
44670 ** This routine first tries to establish an exclusive lock on the
44671 ** wal-index to prevent other threads/processes from doing anything
44672 ** with the WAL or wal-index while recovery is running.  The
44673 ** WAL_RECOVER_LOCK is also held so that other threads will know
44674 ** that this thread is running recovery.  If unable to establish
44675 ** the necessary locks, this routine returns SQLITE_BUSY.
44676 */
44677 static int walIndexRecover(Wal *pWal){
44678   int rc;                         /* Return Code */
44679   i64 nSize;                      /* Size of log file */
44680   u32 aFrameCksum[2] = {0, 0};
44681   int iLock;                      /* Lock offset to lock for checkpoint */
44682   int nLock;                      /* Number of locks to hold */
44683
44684   /* Obtain an exclusive lock on all byte in the locking range not already
44685   ** locked by the caller. The caller is guaranteed to have locked the
44686   ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
44687   ** If successful, the same bytes that are locked here are unlocked before
44688   ** this function returns.
44689   */
44690   assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
44691   assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
44692   assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
44693   assert( pWal->writeLock );
44694   iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
44695   nLock = SQLITE_SHM_NLOCK - iLock;
44696   rc = walLockExclusive(pWal, iLock, nLock);
44697   if( rc ){
44698     return rc;
44699   }
44700   WALTRACE(("WAL%p: recovery begin...\n", pWal));
44701
44702   memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
44703
44704   rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
44705   if( rc!=SQLITE_OK ){
44706     goto recovery_error;
44707   }
44708
44709   if( nSize>WAL_HDRSIZE ){
44710     u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
44711     u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
44712     int szFrame;                  /* Number of bytes in buffer aFrame[] */
44713     u8 *aData;                    /* Pointer to data part of aFrame buffer */
44714     int iFrame;                   /* Index of last frame read */
44715     i64 iOffset;                  /* Next offset to read from log file */
44716     int szPage;                   /* Page size according to the log */
44717     u32 magic;                    /* Magic value read from WAL header */
44718     u32 version;                  /* Magic value read from WAL header */
44719
44720     /* Read in the WAL header. */
44721     rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
44722     if( rc!=SQLITE_OK ){
44723       goto recovery_error;
44724     }
44725
44726     /* If the database page size is not a power of two, or is greater than
44727     ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid 
44728     ** data. Similarly, if the 'magic' value is invalid, ignore the whole
44729     ** WAL file.
44730     */
44731     magic = sqlite3Get4byte(&aBuf[0]);
44732     szPage = sqlite3Get4byte(&aBuf[8]);
44733     if( (magic&0xFFFFFFFE)!=WAL_MAGIC 
44734      || szPage&(szPage-1) 
44735      || szPage>SQLITE_MAX_PAGE_SIZE 
44736      || szPage<512 
44737     ){
44738       goto finished;
44739     }
44740     pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
44741     pWal->szPage = szPage;
44742     pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
44743     memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
44744
44745     /* Verify that the WAL header checksum is correct */
44746     walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN, 
44747         aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
44748     );
44749     if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
44750      || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
44751     ){
44752       goto finished;
44753     }
44754
44755     /* Verify that the version number on the WAL format is one that
44756     ** are able to understand */
44757     version = sqlite3Get4byte(&aBuf[4]);
44758     if( version!=WAL_MAX_VERSION ){
44759       rc = SQLITE_CANTOPEN_BKPT;
44760       goto finished;
44761     }
44762
44763     /* Malloc a buffer to read frames into. */
44764     szFrame = szPage + WAL_FRAME_HDRSIZE;
44765     aFrame = (u8 *)sqlite3_malloc(szFrame);
44766     if( !aFrame ){
44767       rc = SQLITE_NOMEM;
44768       goto recovery_error;
44769     }
44770     aData = &aFrame[WAL_FRAME_HDRSIZE];
44771
44772     /* Read all frames from the log file. */
44773     iFrame = 0;
44774     for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
44775       u32 pgno;                   /* Database page number for frame */
44776       u32 nTruncate;              /* dbsize field from frame header */
44777       int isValid;                /* True if this frame is valid */
44778
44779       /* Read and decode the next log frame. */
44780       rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
44781       if( rc!=SQLITE_OK ) break;
44782       isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
44783       if( !isValid ) break;
44784       rc = walIndexAppend(pWal, ++iFrame, pgno);
44785       if( rc!=SQLITE_OK ) break;
44786
44787       /* If nTruncate is non-zero, this is a commit record. */
44788       if( nTruncate ){
44789         pWal->hdr.mxFrame = iFrame;
44790         pWal->hdr.nPage = nTruncate;
44791         pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
44792         testcase( szPage<=32768 );
44793         testcase( szPage>=65536 );
44794         aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
44795         aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
44796       }
44797     }
44798
44799     sqlite3_free(aFrame);
44800   }
44801
44802 finished:
44803   if( rc==SQLITE_OK ){
44804     volatile WalCkptInfo *pInfo;
44805     int i;
44806     pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
44807     pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
44808     walIndexWriteHdr(pWal);
44809
44810     /* Reset the checkpoint-header. This is safe because this thread is 
44811     ** currently holding locks that exclude all other readers, writers and
44812     ** checkpointers.
44813     */
44814     pInfo = walCkptInfo(pWal);
44815     pInfo->nBackfill = 0;
44816     pInfo->aReadMark[0] = 0;
44817     for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
44818
44819     /* If more than one frame was recovered from the log file, report an
44820     ** event via sqlite3_log(). This is to help with identifying performance
44821     ** problems caused by applications routinely shutting down without
44822     ** checkpointing the log file.
44823     */
44824     if( pWal->hdr.nPage ){
44825       sqlite3_log(SQLITE_OK, "Recovered %d frames from WAL file %s",
44826           pWal->hdr.nPage, pWal->zWalName
44827       );
44828     }
44829   }
44830
44831 recovery_error:
44832   WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
44833   walUnlockExclusive(pWal, iLock, nLock);
44834   return rc;
44835 }
44836
44837 /*
44838 ** Close an open wal-index.
44839 */
44840 static void walIndexClose(Wal *pWal, int isDelete){
44841   if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
44842     int i;
44843     for(i=0; i<pWal->nWiData; i++){
44844       sqlite3_free((void *)pWal->apWiData[i]);
44845       pWal->apWiData[i] = 0;
44846     }
44847   }else{
44848     sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
44849   }
44850 }
44851
44852 /* 
44853 ** Open a connection to the WAL file zWalName. The database file must 
44854 ** already be opened on connection pDbFd. The buffer that zWalName points
44855 ** to must remain valid for the lifetime of the returned Wal* handle.
44856 **
44857 ** A SHARED lock should be held on the database file when this function
44858 ** is called. The purpose of this SHARED lock is to prevent any other
44859 ** client from unlinking the WAL or wal-index file. If another process
44860 ** were to do this just after this client opened one of these files, the
44861 ** system would be badly broken.
44862 **
44863 ** If the log file is successfully opened, SQLITE_OK is returned and 
44864 ** *ppWal is set to point to a new WAL handle. If an error occurs,
44865 ** an SQLite error code is returned and *ppWal is left unmodified.
44866 */
44867 SQLITE_PRIVATE int sqlite3WalOpen(
44868   sqlite3_vfs *pVfs,              /* vfs module to open wal and wal-index */
44869   sqlite3_file *pDbFd,            /* The open database file */
44870   const char *zWalName,           /* Name of the WAL file */
44871   int bNoShm,                     /* True to run in heap-memory mode */
44872   i64 mxWalSize,                  /* Truncate WAL to this size on reset */
44873   Wal **ppWal                     /* OUT: Allocated Wal handle */
44874 ){
44875   int rc;                         /* Return Code */
44876   Wal *pRet;                      /* Object to allocate and return */
44877   int flags;                      /* Flags passed to OsOpen() */
44878
44879   assert( zWalName && zWalName[0] );
44880   assert( pDbFd );
44881
44882   /* In the amalgamation, the os_unix.c and os_win.c source files come before
44883   ** this source file.  Verify that the #defines of the locking byte offsets
44884   ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
44885   */
44886 #ifdef WIN_SHM_BASE
44887   assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
44888 #endif
44889 #ifdef UNIX_SHM_BASE
44890   assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
44891 #endif
44892
44893
44894   /* Allocate an instance of struct Wal to return. */
44895   *ppWal = 0;
44896   pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
44897   if( !pRet ){
44898     return SQLITE_NOMEM;
44899   }
44900
44901   pRet->pVfs = pVfs;
44902   pRet->pWalFd = (sqlite3_file *)&pRet[1];
44903   pRet->pDbFd = pDbFd;
44904   pRet->readLock = -1;
44905   pRet->mxWalSize = mxWalSize;
44906   pRet->zWalName = zWalName;
44907   pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
44908
44909   /* Open file handle on the write-ahead log file. */
44910   flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
44911   rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
44912   if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
44913     pRet->readOnly = WAL_RDONLY;
44914   }
44915
44916   if( rc!=SQLITE_OK ){
44917     walIndexClose(pRet, 0);
44918     sqlite3OsClose(pRet->pWalFd);
44919     sqlite3_free(pRet);
44920   }else{
44921     *ppWal = pRet;
44922     WALTRACE(("WAL%d: opened\n", pRet));
44923   }
44924   return rc;
44925 }
44926
44927 /*
44928 ** Change the size to which the WAL file is trucated on each reset.
44929 */
44930 SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
44931   if( pWal ) pWal->mxWalSize = iLimit;
44932 }
44933
44934 /*
44935 ** Find the smallest page number out of all pages held in the WAL that
44936 ** has not been returned by any prior invocation of this method on the
44937 ** same WalIterator object.   Write into *piFrame the frame index where
44938 ** that page was last written into the WAL.  Write into *piPage the page
44939 ** number.
44940 **
44941 ** Return 0 on success.  If there are no pages in the WAL with a page
44942 ** number larger than *piPage, then return 1.
44943 */
44944 static int walIteratorNext(
44945   WalIterator *p,               /* Iterator */
44946   u32 *piPage,                  /* OUT: The page number of the next page */
44947   u32 *piFrame                  /* OUT: Wal frame index of next page */
44948 ){
44949   u32 iMin;                     /* Result pgno must be greater than iMin */
44950   u32 iRet = 0xFFFFFFFF;        /* 0xffffffff is never a valid page number */
44951   int i;                        /* For looping through segments */
44952
44953   iMin = p->iPrior;
44954   assert( iMin<0xffffffff );
44955   for(i=p->nSegment-1; i>=0; i--){
44956     struct WalSegment *pSegment = &p->aSegment[i];
44957     while( pSegment->iNext<pSegment->nEntry ){
44958       u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
44959       if( iPg>iMin ){
44960         if( iPg<iRet ){
44961           iRet = iPg;
44962           *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
44963         }
44964         break;
44965       }
44966       pSegment->iNext++;
44967     }
44968   }
44969
44970   *piPage = p->iPrior = iRet;
44971   return (iRet==0xFFFFFFFF);
44972 }
44973
44974 /*
44975 ** This function merges two sorted lists into a single sorted list.
44976 **
44977 ** aLeft[] and aRight[] are arrays of indices.  The sort key is
44978 ** aContent[aLeft[]] and aContent[aRight[]].  Upon entry, the following
44979 ** is guaranteed for all J<K:
44980 **
44981 **        aContent[aLeft[J]] < aContent[aLeft[K]]
44982 **        aContent[aRight[J]] < aContent[aRight[K]]
44983 **
44984 ** This routine overwrites aRight[] with a new (probably longer) sequence
44985 ** of indices such that the aRight[] contains every index that appears in
44986 ** either aLeft[] or the old aRight[] and such that the second condition
44987 ** above is still met.
44988 **
44989 ** The aContent[aLeft[X]] values will be unique for all X.  And the
44990 ** aContent[aRight[X]] values will be unique too.  But there might be
44991 ** one or more combinations of X and Y such that
44992 **
44993 **      aLeft[X]!=aRight[Y]  &&  aContent[aLeft[X]] == aContent[aRight[Y]]
44994 **
44995 ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
44996 */
44997 static void walMerge(
44998   const u32 *aContent,            /* Pages in wal - keys for the sort */
44999   ht_slot *aLeft,                 /* IN: Left hand input list */
45000   int nLeft,                      /* IN: Elements in array *paLeft */
45001   ht_slot **paRight,              /* IN/OUT: Right hand input list */
45002   int *pnRight,                   /* IN/OUT: Elements in *paRight */
45003   ht_slot *aTmp                   /* Temporary buffer */
45004 ){
45005   int iLeft = 0;                  /* Current index in aLeft */
45006   int iRight = 0;                 /* Current index in aRight */
45007   int iOut = 0;                   /* Current index in output buffer */
45008   int nRight = *pnRight;
45009   ht_slot *aRight = *paRight;
45010
45011   assert( nLeft>0 && nRight>0 );
45012   while( iRight<nRight || iLeft<nLeft ){
45013     ht_slot logpage;
45014     Pgno dbpage;
45015
45016     if( (iLeft<nLeft) 
45017      && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
45018     ){
45019       logpage = aLeft[iLeft++];
45020     }else{
45021       logpage = aRight[iRight++];
45022     }
45023     dbpage = aContent[logpage];
45024
45025     aTmp[iOut++] = logpage;
45026     if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
45027
45028     assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
45029     assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
45030   }
45031
45032   *paRight = aLeft;
45033   *pnRight = iOut;
45034   memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
45035 }
45036
45037 /*
45038 ** Sort the elements in list aList using aContent[] as the sort key.
45039 ** Remove elements with duplicate keys, preferring to keep the
45040 ** larger aList[] values.
45041 **
45042 ** The aList[] entries are indices into aContent[].  The values in
45043 ** aList[] are to be sorted so that for all J<K:
45044 **
45045 **      aContent[aList[J]] < aContent[aList[K]]
45046 **
45047 ** For any X and Y such that
45048 **
45049 **      aContent[aList[X]] == aContent[aList[Y]]
45050 **
45051 ** Keep the larger of the two values aList[X] and aList[Y] and discard
45052 ** the smaller.
45053 */
45054 static void walMergesort(
45055   const u32 *aContent,            /* Pages in wal */
45056   ht_slot *aBuffer,               /* Buffer of at least *pnList items to use */
45057   ht_slot *aList,                 /* IN/OUT: List to sort */
45058   int *pnList                     /* IN/OUT: Number of elements in aList[] */
45059 ){
45060   struct Sublist {
45061     int nList;                    /* Number of elements in aList */
45062     ht_slot *aList;               /* Pointer to sub-list content */
45063   };
45064
45065   const int nList = *pnList;      /* Size of input list */
45066   int nMerge = 0;                 /* Number of elements in list aMerge */
45067   ht_slot *aMerge = 0;            /* List to be merged */
45068   int iList;                      /* Index into input list */
45069   int iSub = 0;                   /* Index into aSub array */
45070   struct Sublist aSub[13];        /* Array of sub-lists */
45071
45072   memset(aSub, 0, sizeof(aSub));
45073   assert( nList<=HASHTABLE_NPAGE && nList>0 );
45074   assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
45075
45076   for(iList=0; iList<nList; iList++){
45077     nMerge = 1;
45078     aMerge = &aList[iList];
45079     for(iSub=0; iList & (1<<iSub); iSub++){
45080       struct Sublist *p = &aSub[iSub];
45081       assert( p->aList && p->nList<=(1<<iSub) );
45082       assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
45083       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
45084     }
45085     aSub[iSub].aList = aMerge;
45086     aSub[iSub].nList = nMerge;
45087   }
45088
45089   for(iSub++; iSub<ArraySize(aSub); iSub++){
45090     if( nList & (1<<iSub) ){
45091       struct Sublist *p = &aSub[iSub];
45092       assert( p->nList<=(1<<iSub) );
45093       assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
45094       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
45095     }
45096   }
45097   assert( aMerge==aList );
45098   *pnList = nMerge;
45099
45100 #ifdef SQLITE_DEBUG
45101   {
45102     int i;
45103     for(i=1; i<*pnList; i++){
45104       assert( aContent[aList[i]] > aContent[aList[i-1]] );
45105     }
45106   }
45107 #endif
45108 }
45109
45110 /* 
45111 ** Free an iterator allocated by walIteratorInit().
45112 */
45113 static void walIteratorFree(WalIterator *p){
45114   sqlite3ScratchFree(p);
45115 }
45116
45117 /*
45118 ** Construct a WalInterator object that can be used to loop over all 
45119 ** pages in the WAL in ascending order. The caller must hold the checkpoint
45120 ** lock.
45121 **
45122 ** On success, make *pp point to the newly allocated WalInterator object
45123 ** return SQLITE_OK. Otherwise, return an error code. If this routine
45124 ** returns an error, the value of *pp is undefined.
45125 **
45126 ** The calling routine should invoke walIteratorFree() to destroy the
45127 ** WalIterator object when it has finished with it.
45128 */
45129 static int walIteratorInit(Wal *pWal, WalIterator **pp){
45130   WalIterator *p;                 /* Return value */
45131   int nSegment;                   /* Number of segments to merge */
45132   u32 iLast;                      /* Last frame in log */
45133   int nByte;                      /* Number of bytes to allocate */
45134   int i;                          /* Iterator variable */
45135   ht_slot *aTmp;                  /* Temp space used by merge-sort */
45136   int rc = SQLITE_OK;             /* Return Code */
45137
45138   /* This routine only runs while holding the checkpoint lock. And
45139   ** it only runs if there is actually content in the log (mxFrame>0).
45140   */
45141   assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
45142   iLast = pWal->hdr.mxFrame;
45143
45144   /* Allocate space for the WalIterator object. */
45145   nSegment = walFramePage(iLast) + 1;
45146   nByte = sizeof(WalIterator) 
45147         + (nSegment-1)*sizeof(struct WalSegment)
45148         + iLast*sizeof(ht_slot);
45149   p = (WalIterator *)sqlite3ScratchMalloc(nByte);
45150   if( !p ){
45151     return SQLITE_NOMEM;
45152   }
45153   memset(p, 0, nByte);
45154   p->nSegment = nSegment;
45155
45156   /* Allocate temporary space used by the merge-sort routine. This block
45157   ** of memory will be freed before this function returns.
45158   */
45159   aTmp = (ht_slot *)sqlite3ScratchMalloc(
45160       sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
45161   );
45162   if( !aTmp ){
45163     rc = SQLITE_NOMEM;
45164   }
45165
45166   for(i=0; rc==SQLITE_OK && i<nSegment; i++){
45167     volatile ht_slot *aHash;
45168     u32 iZero;
45169     volatile u32 *aPgno;
45170
45171     rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
45172     if( rc==SQLITE_OK ){
45173       int j;                      /* Counter variable */
45174       int nEntry;                 /* Number of entries in this segment */
45175       ht_slot *aIndex;            /* Sorted index for this segment */
45176
45177       aPgno++;
45178       if( (i+1)==nSegment ){
45179         nEntry = (int)(iLast - iZero);
45180       }else{
45181         nEntry = (int)((u32*)aHash - (u32*)aPgno);
45182       }
45183       aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
45184       iZero++;
45185   
45186       for(j=0; j<nEntry; j++){
45187         aIndex[j] = (ht_slot)j;
45188       }
45189       walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
45190       p->aSegment[i].iZero = iZero;
45191       p->aSegment[i].nEntry = nEntry;
45192       p->aSegment[i].aIndex = aIndex;
45193       p->aSegment[i].aPgno = (u32 *)aPgno;
45194     }
45195   }
45196   sqlite3ScratchFree(aTmp);
45197
45198   if( rc!=SQLITE_OK ){
45199     walIteratorFree(p);
45200   }
45201   *pp = p;
45202   return rc;
45203 }
45204
45205 /*
45206 ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
45207 ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
45208 ** busy-handler function. Invoke it and retry the lock until either the
45209 ** lock is successfully obtained or the busy-handler returns 0.
45210 */
45211 static int walBusyLock(
45212   Wal *pWal,                      /* WAL connection */
45213   int (*xBusy)(void*),            /* Function to call when busy */
45214   void *pBusyArg,                 /* Context argument for xBusyHandler */
45215   int lockIdx,                    /* Offset of first byte to lock */
45216   int n                           /* Number of bytes to lock */
45217 ){
45218   int rc;
45219   do {
45220     rc = walLockExclusive(pWal, lockIdx, n);
45221   }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
45222   return rc;
45223 }
45224
45225 /*
45226 ** The cache of the wal-index header must be valid to call this function.
45227 ** Return the page-size in bytes used by the database.
45228 */
45229 static int walPagesize(Wal *pWal){
45230   return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
45231 }
45232
45233 /*
45234 ** Copy as much content as we can from the WAL back into the database file
45235 ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
45236 **
45237 ** The amount of information copies from WAL to database might be limited
45238 ** by active readers.  This routine will never overwrite a database page
45239 ** that a concurrent reader might be using.
45240 **
45241 ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
45242 ** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if 
45243 ** checkpoints are always run by a background thread or background 
45244 ** process, foreground threads will never block on a lengthy fsync call.
45245 **
45246 ** Fsync is called on the WAL before writing content out of the WAL and
45247 ** into the database.  This ensures that if the new content is persistent
45248 ** in the WAL and can be recovered following a power-loss or hard reset.
45249 **
45250 ** Fsync is also called on the database file if (and only if) the entire
45251 ** WAL content is copied into the database file.  This second fsync makes
45252 ** it safe to delete the WAL since the new content will persist in the
45253 ** database file.
45254 **
45255 ** This routine uses and updates the nBackfill field of the wal-index header.
45256 ** This is the only routine tha will increase the value of nBackfill.  
45257 ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
45258 ** its value.)
45259 **
45260 ** The caller must be holding sufficient locks to ensure that no other
45261 ** checkpoint is running (in any other thread or process) at the same
45262 ** time.
45263 */
45264 static int walCheckpoint(
45265   Wal *pWal,                      /* Wal connection */
45266   int eMode,                      /* One of PASSIVE, FULL or RESTART */
45267   int (*xBusyCall)(void*),        /* Function to call when busy */
45268   void *pBusyArg,                 /* Context argument for xBusyHandler */
45269   int sync_flags,                 /* Flags for OsSync() (or 0) */
45270   u8 *zBuf                        /* Temporary buffer to use */
45271 ){
45272   int rc;                         /* Return code */
45273   int szPage;                     /* Database page-size */
45274   WalIterator *pIter = 0;         /* Wal iterator context */
45275   u32 iDbpage = 0;                /* Next database page to write */
45276   u32 iFrame = 0;                 /* Wal frame containing data for iDbpage */
45277   u32 mxSafeFrame;                /* Max frame that can be backfilled */
45278   u32 mxPage;                     /* Max database page to write */
45279   int i;                          /* Loop counter */
45280   volatile WalCkptInfo *pInfo;    /* The checkpoint status information */
45281   int (*xBusy)(void*) = 0;        /* Function to call when waiting for locks */
45282
45283   szPage = walPagesize(pWal);
45284   testcase( szPage<=32768 );
45285   testcase( szPage>=65536 );
45286   pInfo = walCkptInfo(pWal);
45287   if( pInfo->nBackfill>=pWal->hdr.mxFrame ) return SQLITE_OK;
45288
45289   /* Allocate the iterator */
45290   rc = walIteratorInit(pWal, &pIter);
45291   if( rc!=SQLITE_OK ){
45292     return rc;
45293   }
45294   assert( pIter );
45295
45296   if( eMode!=SQLITE_CHECKPOINT_PASSIVE ) xBusy = xBusyCall;
45297
45298   /* Compute in mxSafeFrame the index of the last frame of the WAL that is
45299   ** safe to write into the database.  Frames beyond mxSafeFrame might
45300   ** overwrite database pages that are in use by active readers and thus
45301   ** cannot be backfilled from the WAL.
45302   */
45303   mxSafeFrame = pWal->hdr.mxFrame;
45304   mxPage = pWal->hdr.nPage;
45305   for(i=1; i<WAL_NREADER; i++){
45306     u32 y = pInfo->aReadMark[i];
45307     if( mxSafeFrame>y ){
45308       assert( y<=pWal->hdr.mxFrame );
45309       rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
45310       if( rc==SQLITE_OK ){
45311         pInfo->aReadMark[i] = READMARK_NOT_USED;
45312         walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
45313       }else if( rc==SQLITE_BUSY ){
45314         mxSafeFrame = y;
45315         xBusy = 0;
45316       }else{
45317         goto walcheckpoint_out;
45318       }
45319     }
45320   }
45321
45322   if( pInfo->nBackfill<mxSafeFrame
45323    && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0), 1))==SQLITE_OK
45324   ){
45325     i64 nSize;                    /* Current size of database file */
45326     u32 nBackfill = pInfo->nBackfill;
45327
45328     /* Sync the WAL to disk */
45329     if( sync_flags ){
45330       rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
45331     }
45332
45333     /* If the database file may grow as a result of this checkpoint, hint
45334     ** about the eventual size of the db file to the VFS layer. 
45335     */
45336     if( rc==SQLITE_OK ){
45337       i64 nReq = ((i64)mxPage * szPage);
45338       rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
45339       if( rc==SQLITE_OK && nSize<nReq ){
45340         sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
45341       }
45342     }
45343
45344     /* Iterate through the contents of the WAL, copying data to the db file. */
45345     while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
45346       i64 iOffset;
45347       assert( walFramePgno(pWal, iFrame)==iDbpage );
45348       if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue;
45349       iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
45350       /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
45351       rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
45352       if( rc!=SQLITE_OK ) break;
45353       iOffset = (iDbpage-1)*(i64)szPage;
45354       testcase( IS_BIG_INT(iOffset) );
45355       rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
45356       if( rc!=SQLITE_OK ) break;
45357     }
45358
45359     /* If work was actually accomplished... */
45360     if( rc==SQLITE_OK ){
45361       if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
45362         i64 szDb = pWal->hdr.nPage*(i64)szPage;
45363         testcase( IS_BIG_INT(szDb) );
45364         rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
45365         if( rc==SQLITE_OK && sync_flags ){
45366           rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
45367         }
45368       }
45369       if( rc==SQLITE_OK ){
45370         pInfo->nBackfill = mxSafeFrame;
45371       }
45372     }
45373
45374     /* Release the reader lock held while backfilling */
45375     walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
45376   }
45377
45378   if( rc==SQLITE_BUSY ){
45379     /* Reset the return code so as not to report a checkpoint failure
45380     ** just because there are active readers.  */
45381     rc = SQLITE_OK;
45382   }
45383
45384   /* If this is an SQLITE_CHECKPOINT_RESTART operation, and the entire wal
45385   ** file has been copied into the database file, then block until all
45386   ** readers have finished using the wal file. This ensures that the next
45387   ** process to write to the database restarts the wal file.
45388   */
45389   if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
45390     assert( pWal->writeLock );
45391     if( pInfo->nBackfill<pWal->hdr.mxFrame ){
45392       rc = SQLITE_BUSY;
45393     }else if( eMode==SQLITE_CHECKPOINT_RESTART ){
45394       assert( mxSafeFrame==pWal->hdr.mxFrame );
45395       rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
45396       if( rc==SQLITE_OK ){
45397         walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
45398       }
45399     }
45400   }
45401
45402  walcheckpoint_out:
45403   walIteratorFree(pIter);
45404   return rc;
45405 }
45406
45407 /*
45408 ** Close a connection to a log file.
45409 */
45410 SQLITE_PRIVATE int sqlite3WalClose(
45411   Wal *pWal,                      /* Wal to close */
45412   int sync_flags,                 /* Flags to pass to OsSync() (or 0) */
45413   int nBuf,
45414   u8 *zBuf                        /* Buffer of at least nBuf bytes */
45415 ){
45416   int rc = SQLITE_OK;
45417   if( pWal ){
45418     int isDelete = 0;             /* True to unlink wal and wal-index files */
45419
45420     /* If an EXCLUSIVE lock can be obtained on the database file (using the
45421     ** ordinary, rollback-mode locking methods, this guarantees that the
45422     ** connection associated with this log file is the only connection to
45423     ** the database. In this case checkpoint the database and unlink both
45424     ** the wal and wal-index files.
45425     **
45426     ** The EXCLUSIVE lock is not released before returning.
45427     */
45428     rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
45429     if( rc==SQLITE_OK ){
45430       if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
45431         pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
45432       }
45433       rc = sqlite3WalCheckpoint(
45434           pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
45435       );
45436       if( rc==SQLITE_OK ){
45437         isDelete = 1;
45438       }
45439     }
45440
45441     walIndexClose(pWal, isDelete);
45442     sqlite3OsClose(pWal->pWalFd);
45443     if( isDelete ){
45444       sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
45445     }
45446     WALTRACE(("WAL%p: closed\n", pWal));
45447     sqlite3_free((void *)pWal->apWiData);
45448     sqlite3_free(pWal);
45449   }
45450   return rc;
45451 }
45452
45453 /*
45454 ** Try to read the wal-index header.  Return 0 on success and 1 if
45455 ** there is a problem.
45456 **
45457 ** The wal-index is in shared memory.  Another thread or process might
45458 ** be writing the header at the same time this procedure is trying to
45459 ** read it, which might result in inconsistency.  A dirty read is detected
45460 ** by verifying that both copies of the header are the same and also by
45461 ** a checksum on the header.
45462 **
45463 ** If and only if the read is consistent and the header is different from
45464 ** pWal->hdr, then pWal->hdr is updated to the content of the new header
45465 ** and *pChanged is set to 1.
45466 **
45467 ** If the checksum cannot be verified return non-zero. If the header
45468 ** is read successfully and the checksum verified, return zero.
45469 */
45470 static int walIndexTryHdr(Wal *pWal, int *pChanged){
45471   u32 aCksum[2];                  /* Checksum on the header content */
45472   WalIndexHdr h1, h2;             /* Two copies of the header content */
45473   WalIndexHdr volatile *aHdr;     /* Header in shared memory */
45474
45475   /* The first page of the wal-index must be mapped at this point. */
45476   assert( pWal->nWiData>0 && pWal->apWiData[0] );
45477
45478   /* Read the header. This might happen concurrently with a write to the
45479   ** same area of shared memory on a different CPU in a SMP,
45480   ** meaning it is possible that an inconsistent snapshot is read
45481   ** from the file. If this happens, return non-zero.
45482   **
45483   ** There are two copies of the header at the beginning of the wal-index.
45484   ** When reading, read [0] first then [1].  Writes are in the reverse order.
45485   ** Memory barriers are used to prevent the compiler or the hardware from
45486   ** reordering the reads and writes.
45487   */
45488   aHdr = walIndexHdr(pWal);
45489   memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
45490   walShmBarrier(pWal);
45491   memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
45492
45493   if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
45494     return 1;   /* Dirty read */
45495   }  
45496   if( h1.isInit==0 ){
45497     return 1;   /* Malformed header - probably all zeros */
45498   }
45499   walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
45500   if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
45501     return 1;   /* Checksum does not match */
45502   }
45503
45504   if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
45505     *pChanged = 1;
45506     memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
45507     pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
45508     testcase( pWal->szPage<=32768 );
45509     testcase( pWal->szPage>=65536 );
45510   }
45511
45512   /* The header was successfully read. Return zero. */
45513   return 0;
45514 }
45515
45516 /*
45517 ** Read the wal-index header from the wal-index and into pWal->hdr.
45518 ** If the wal-header appears to be corrupt, try to reconstruct the
45519 ** wal-index from the WAL before returning.
45520 **
45521 ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
45522 ** changed by this opertion.  If pWal->hdr is unchanged, set *pChanged
45523 ** to 0.
45524 **
45525 ** If the wal-index header is successfully read, return SQLITE_OK. 
45526 ** Otherwise an SQLite error code.
45527 */
45528 static int walIndexReadHdr(Wal *pWal, int *pChanged){
45529   int rc;                         /* Return code */
45530   int badHdr;                     /* True if a header read failed */
45531   volatile u32 *page0;            /* Chunk of wal-index containing header */
45532
45533   /* Ensure that page 0 of the wal-index (the page that contains the 
45534   ** wal-index header) is mapped. Return early if an error occurs here.
45535   */
45536   assert( pChanged );
45537   rc = walIndexPage(pWal, 0, &page0);
45538   if( rc!=SQLITE_OK ){
45539     return rc;
45540   };
45541   assert( page0 || pWal->writeLock==0 );
45542
45543   /* If the first page of the wal-index has been mapped, try to read the
45544   ** wal-index header immediately, without holding any lock. This usually
45545   ** works, but may fail if the wal-index header is corrupt or currently 
45546   ** being modified by another thread or process.
45547   */
45548   badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
45549
45550   /* If the first attempt failed, it might have been due to a race
45551   ** with a writer.  So get a WRITE lock and try again.
45552   */
45553   assert( badHdr==0 || pWal->writeLock==0 );
45554   if( badHdr ){
45555     if( pWal->readOnly & WAL_SHM_RDONLY ){
45556       if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
45557         walUnlockShared(pWal, WAL_WRITE_LOCK);
45558         rc = SQLITE_READONLY_RECOVERY;
45559       }
45560     }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
45561       pWal->writeLock = 1;
45562       if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
45563         badHdr = walIndexTryHdr(pWal, pChanged);
45564         if( badHdr ){
45565           /* If the wal-index header is still malformed even while holding
45566           ** a WRITE lock, it can only mean that the header is corrupted and
45567           ** needs to be reconstructed.  So run recovery to do exactly that.
45568           */
45569           rc = walIndexRecover(pWal);
45570           *pChanged = 1;
45571         }
45572       }
45573       pWal->writeLock = 0;
45574       walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
45575     }
45576   }
45577
45578   /* If the header is read successfully, check the version number to make
45579   ** sure the wal-index was not constructed with some future format that
45580   ** this version of SQLite cannot understand.
45581   */
45582   if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
45583     rc = SQLITE_CANTOPEN_BKPT;
45584   }
45585
45586   return rc;
45587 }
45588
45589 /*
45590 ** This is the value that walTryBeginRead returns when it needs to
45591 ** be retried.
45592 */
45593 #define WAL_RETRY  (-1)
45594
45595 /*
45596 ** Attempt to start a read transaction.  This might fail due to a race or
45597 ** other transient condition.  When that happens, it returns WAL_RETRY to
45598 ** indicate to the caller that it is safe to retry immediately.
45599 **
45600 ** On success return SQLITE_OK.  On a permanent failure (such an
45601 ** I/O error or an SQLITE_BUSY because another process is running
45602 ** recovery) return a positive error code.
45603 **
45604 ** The useWal parameter is true to force the use of the WAL and disable
45605 ** the case where the WAL is bypassed because it has been completely
45606 ** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr() 
45607 ** to make a copy of the wal-index header into pWal->hdr.  If the 
45608 ** wal-index header has changed, *pChanged is set to 1 (as an indication 
45609 ** to the caller that the local paget cache is obsolete and needs to be 
45610 ** flushed.)  When useWal==1, the wal-index header is assumed to already
45611 ** be loaded and the pChanged parameter is unused.
45612 **
45613 ** The caller must set the cnt parameter to the number of prior calls to
45614 ** this routine during the current read attempt that returned WAL_RETRY.
45615 ** This routine will start taking more aggressive measures to clear the
45616 ** race conditions after multiple WAL_RETRY returns, and after an excessive
45617 ** number of errors will ultimately return SQLITE_PROTOCOL.  The
45618 ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
45619 ** and is not honoring the locking protocol.  There is a vanishingly small
45620 ** chance that SQLITE_PROTOCOL could be returned because of a run of really
45621 ** bad luck when there is lots of contention for the wal-index, but that
45622 ** possibility is so small that it can be safely neglected, we believe.
45623 **
45624 ** On success, this routine obtains a read lock on 
45625 ** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is
45626 ** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)
45627 ** that means the Wal does not hold any read lock.  The reader must not
45628 ** access any database page that is modified by a WAL frame up to and
45629 ** including frame number aReadMark[pWal->readLock].  The reader will
45630 ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
45631 ** Or if pWal->readLock==0, then the reader will ignore the WAL
45632 ** completely and get all content directly from the database file.
45633 ** If the useWal parameter is 1 then the WAL will never be ignored and
45634 ** this routine will always set pWal->readLock>0 on success.
45635 ** When the read transaction is completed, the caller must release the
45636 ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
45637 **
45638 ** This routine uses the nBackfill and aReadMark[] fields of the header
45639 ** to select a particular WAL_READ_LOCK() that strives to let the
45640 ** checkpoint process do as much work as possible.  This routine might
45641 ** update values of the aReadMark[] array in the header, but if it does
45642 ** so it takes care to hold an exclusive lock on the corresponding
45643 ** WAL_READ_LOCK() while changing values.
45644 */
45645 static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
45646   volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */
45647   u32 mxReadMark;                 /* Largest aReadMark[] value */
45648   int mxI;                        /* Index of largest aReadMark[] value */
45649   int i;                          /* Loop counter */
45650   int rc = SQLITE_OK;             /* Return code  */
45651
45652   assert( pWal->readLock<0 );     /* Not currently locked */
45653
45654   /* Take steps to avoid spinning forever if there is a protocol error.
45655   **
45656   ** Circumstances that cause a RETRY should only last for the briefest
45657   ** instances of time.  No I/O or other system calls are done while the
45658   ** locks are held, so the locks should not be held for very long. But 
45659   ** if we are unlucky, another process that is holding a lock might get
45660   ** paged out or take a page-fault that is time-consuming to resolve, 
45661   ** during the few nanoseconds that it is holding the lock.  In that case,
45662   ** it might take longer than normal for the lock to free.
45663   **
45664   ** After 5 RETRYs, we begin calling sqlite3OsSleep().  The first few
45665   ** calls to sqlite3OsSleep() have a delay of 1 microsecond.  Really this
45666   ** is more of a scheduler yield than an actual delay.  But on the 10th
45667   ** an subsequent retries, the delays start becoming longer and longer, 
45668   ** so that on the 100th (and last) RETRY we delay for 21 milliseconds.
45669   ** The total delay time before giving up is less than 1 second.
45670   */
45671   if( cnt>5 ){
45672     int nDelay = 1;                      /* Pause time in microseconds */
45673     if( cnt>100 ){
45674       VVA_ONLY( pWal->lockError = 1; )
45675       return SQLITE_PROTOCOL;
45676     }
45677     if( cnt>=10 ) nDelay = (cnt-9)*238;  /* Max delay 21ms. Total delay 996ms */
45678     sqlite3OsSleep(pWal->pVfs, nDelay);
45679   }
45680
45681   if( !useWal ){
45682     rc = walIndexReadHdr(pWal, pChanged);
45683     if( rc==SQLITE_BUSY ){
45684       /* If there is not a recovery running in another thread or process
45685       ** then convert BUSY errors to WAL_RETRY.  If recovery is known to
45686       ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here
45687       ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
45688       ** would be technically correct.  But the race is benign since with
45689       ** WAL_RETRY this routine will be called again and will probably be
45690       ** right on the second iteration.
45691       */
45692       if( pWal->apWiData[0]==0 ){
45693         /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
45694         ** We assume this is a transient condition, so return WAL_RETRY. The
45695         ** xShmMap() implementation used by the default unix and win32 VFS 
45696         ** modules may return SQLITE_BUSY due to a race condition in the 
45697         ** code that determines whether or not the shared-memory region 
45698         ** must be zeroed before the requested page is returned.
45699         */
45700         rc = WAL_RETRY;
45701       }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
45702         walUnlockShared(pWal, WAL_RECOVER_LOCK);
45703         rc = WAL_RETRY;
45704       }else if( rc==SQLITE_BUSY ){
45705         rc = SQLITE_BUSY_RECOVERY;
45706       }
45707     }
45708     if( rc!=SQLITE_OK ){
45709       return rc;
45710     }
45711   }
45712
45713   pInfo = walCkptInfo(pWal);
45714   if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
45715     /* The WAL has been completely backfilled (or it is empty).
45716     ** and can be safely ignored.
45717     */
45718     rc = walLockShared(pWal, WAL_READ_LOCK(0));
45719     walShmBarrier(pWal);
45720     if( rc==SQLITE_OK ){
45721       if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
45722         /* It is not safe to allow the reader to continue here if frames
45723         ** may have been appended to the log before READ_LOCK(0) was obtained.
45724         ** When holding READ_LOCK(0), the reader ignores the entire log file,
45725         ** which implies that the database file contains a trustworthy
45726         ** snapshoT. Since holding READ_LOCK(0) prevents a checkpoint from
45727         ** happening, this is usually correct.
45728         **
45729         ** However, if frames have been appended to the log (or if the log 
45730         ** is wrapped and written for that matter) before the READ_LOCK(0)
45731         ** is obtained, that is not necessarily true. A checkpointer may
45732         ** have started to backfill the appended frames but crashed before
45733         ** it finished. Leaving a corrupt image in the database file.
45734         */
45735         walUnlockShared(pWal, WAL_READ_LOCK(0));
45736         return WAL_RETRY;
45737       }
45738       pWal->readLock = 0;
45739       return SQLITE_OK;
45740     }else if( rc!=SQLITE_BUSY ){
45741       return rc;
45742     }
45743   }
45744
45745   /* If we get this far, it means that the reader will want to use
45746   ** the WAL to get at content from recent commits.  The job now is
45747   ** to select one of the aReadMark[] entries that is closest to
45748   ** but not exceeding pWal->hdr.mxFrame and lock that entry.
45749   */
45750   mxReadMark = 0;
45751   mxI = 0;
45752   for(i=1; i<WAL_NREADER; i++){
45753     u32 thisMark = pInfo->aReadMark[i];
45754     if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
45755       assert( thisMark!=READMARK_NOT_USED );
45756       mxReadMark = thisMark;
45757       mxI = i;
45758     }
45759   }
45760   /* There was once an "if" here. The extra "{" is to preserve indentation. */
45761   {
45762     if( (pWal->readOnly & WAL_SHM_RDONLY)==0
45763      && (mxReadMark<pWal->hdr.mxFrame || mxI==0)
45764     ){
45765       for(i=1; i<WAL_NREADER; i++){
45766         rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
45767         if( rc==SQLITE_OK ){
45768           mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
45769           mxI = i;
45770           walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
45771           break;
45772         }else if( rc!=SQLITE_BUSY ){
45773           return rc;
45774         }
45775       }
45776     }
45777     if( mxI==0 ){
45778       assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
45779       return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
45780     }
45781
45782     rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
45783     if( rc ){
45784       return rc==SQLITE_BUSY ? WAL_RETRY : rc;
45785     }
45786     /* Now that the read-lock has been obtained, check that neither the
45787     ** value in the aReadMark[] array or the contents of the wal-index
45788     ** header have changed.
45789     **
45790     ** It is necessary to check that the wal-index header did not change
45791     ** between the time it was read and when the shared-lock was obtained
45792     ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
45793     ** that the log file may have been wrapped by a writer, or that frames
45794     ** that occur later in the log than pWal->hdr.mxFrame may have been
45795     ** copied into the database by a checkpointer. If either of these things
45796     ** happened, then reading the database with the current value of
45797     ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
45798     ** instead.
45799     **
45800     ** This does not guarantee that the copy of the wal-index header is up to
45801     ** date before proceeding. That would not be possible without somehow
45802     ** blocking writers. It only guarantees that a dangerous checkpoint or 
45803     ** log-wrap (either of which would require an exclusive lock on
45804     ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
45805     */
45806     walShmBarrier(pWal);
45807     if( pInfo->aReadMark[mxI]!=mxReadMark
45808      || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
45809     ){
45810       walUnlockShared(pWal, WAL_READ_LOCK(mxI));
45811       return WAL_RETRY;
45812     }else{
45813       assert( mxReadMark<=pWal->hdr.mxFrame );
45814       pWal->readLock = (i16)mxI;
45815     }
45816   }
45817   return rc;
45818 }
45819
45820 /*
45821 ** Begin a read transaction on the database.
45822 **
45823 ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
45824 ** it takes a snapshot of the state of the WAL and wal-index for the current
45825 ** instant in time.  The current thread will continue to use this snapshot.
45826 ** Other threads might append new content to the WAL and wal-index but
45827 ** that extra content is ignored by the current thread.
45828 **
45829 ** If the database contents have changes since the previous read
45830 ** transaction, then *pChanged is set to 1 before returning.  The
45831 ** Pager layer will use this to know that is cache is stale and
45832 ** needs to be flushed.
45833 */
45834 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
45835   int rc;                         /* Return code */
45836   int cnt = 0;                    /* Number of TryBeginRead attempts */
45837
45838   do{
45839     rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
45840   }while( rc==WAL_RETRY );
45841   testcase( (rc&0xff)==SQLITE_BUSY );
45842   testcase( (rc&0xff)==SQLITE_IOERR );
45843   testcase( rc==SQLITE_PROTOCOL );
45844   testcase( rc==SQLITE_OK );
45845   return rc;
45846 }
45847
45848 /*
45849 ** Finish with a read transaction.  All this does is release the
45850 ** read-lock.
45851 */
45852 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
45853   sqlite3WalEndWriteTransaction(pWal);
45854   if( pWal->readLock>=0 ){
45855     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
45856     pWal->readLock = -1;
45857   }
45858 }
45859
45860 /*
45861 ** Read a page from the WAL, if it is present in the WAL and if the 
45862 ** current read transaction is configured to use the WAL.  
45863 **
45864 ** The *pInWal is set to 1 if the requested page is in the WAL and
45865 ** has been loaded.  Or *pInWal is set to 0 if the page was not in 
45866 ** the WAL and needs to be read out of the database.
45867 */
45868 SQLITE_PRIVATE int sqlite3WalRead(
45869   Wal *pWal,                      /* WAL handle */
45870   Pgno pgno,                      /* Database page number to read data for */
45871   int *pInWal,                    /* OUT: True if data is read from WAL */
45872   int nOut,                       /* Size of buffer pOut in bytes */
45873   u8 *pOut                        /* Buffer to write page data to */
45874 ){
45875   u32 iRead = 0;                  /* If !=0, WAL frame to return data from */
45876   u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */
45877   int iHash;                      /* Used to loop through N hash tables */
45878
45879   /* This routine is only be called from within a read transaction. */
45880   assert( pWal->readLock>=0 || pWal->lockError );
45881
45882   /* If the "last page" field of the wal-index header snapshot is 0, then
45883   ** no data will be read from the wal under any circumstances. Return early
45884   ** in this case as an optimization.  Likewise, if pWal->readLock==0, 
45885   ** then the WAL is ignored by the reader so return early, as if the 
45886   ** WAL were empty.
45887   */
45888   if( iLast==0 || pWal->readLock==0 ){
45889     *pInWal = 0;
45890     return SQLITE_OK;
45891   }
45892
45893   /* Search the hash table or tables for an entry matching page number
45894   ** pgno. Each iteration of the following for() loop searches one
45895   ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
45896   **
45897   ** This code might run concurrently to the code in walIndexAppend()
45898   ** that adds entries to the wal-index (and possibly to this hash 
45899   ** table). This means the value just read from the hash 
45900   ** slot (aHash[iKey]) may have been added before or after the 
45901   ** current read transaction was opened. Values added after the
45902   ** read transaction was opened may have been written incorrectly -
45903   ** i.e. these slots may contain garbage data. However, we assume
45904   ** that any slots written before the current read transaction was
45905   ** opened remain unmodified.
45906   **
45907   ** For the reasons above, the if(...) condition featured in the inner
45908   ** loop of the following block is more stringent that would be required 
45909   ** if we had exclusive access to the hash-table:
45910   **
45911   **   (aPgno[iFrame]==pgno): 
45912   **     This condition filters out normal hash-table collisions.
45913   **
45914   **   (iFrame<=iLast): 
45915   **     This condition filters out entries that were added to the hash
45916   **     table after the current read-transaction had started.
45917   */
45918   for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
45919     volatile ht_slot *aHash;      /* Pointer to hash table */
45920     volatile u32 *aPgno;          /* Pointer to array of page numbers */
45921     u32 iZero;                    /* Frame number corresponding to aPgno[0] */
45922     int iKey;                     /* Hash slot index */
45923     int nCollide;                 /* Number of hash collisions remaining */
45924     int rc;                       /* Error code */
45925
45926     rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
45927     if( rc!=SQLITE_OK ){
45928       return rc;
45929     }
45930     nCollide = HASHTABLE_NSLOT;
45931     for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
45932       u32 iFrame = aHash[iKey] + iZero;
45933       if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
45934         assert( iFrame>iRead );
45935         iRead = iFrame;
45936       }
45937       if( (nCollide--)==0 ){
45938         return SQLITE_CORRUPT_BKPT;
45939       }
45940     }
45941   }
45942
45943 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
45944   /* If expensive assert() statements are available, do a linear search
45945   ** of the wal-index file content. Make sure the results agree with the
45946   ** result obtained using the hash indexes above.  */
45947   {
45948     u32 iRead2 = 0;
45949     u32 iTest;
45950     for(iTest=iLast; iTest>0; iTest--){
45951       if( walFramePgno(pWal, iTest)==pgno ){
45952         iRead2 = iTest;
45953         break;
45954       }
45955     }
45956     assert( iRead==iRead2 );
45957   }
45958 #endif
45959
45960   /* If iRead is non-zero, then it is the log frame number that contains the
45961   ** required page. Read and return data from the log file.
45962   */
45963   if( iRead ){
45964     int sz;
45965     i64 iOffset;
45966     sz = pWal->hdr.szPage;
45967     sz = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
45968     testcase( sz<=32768 );
45969     testcase( sz>=65536 );
45970     iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
45971     *pInWal = 1;
45972     /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
45973     return sqlite3OsRead(pWal->pWalFd, pOut, nOut, iOffset);
45974   }
45975
45976   *pInWal = 0;
45977   return SQLITE_OK;
45978 }
45979
45980
45981 /* 
45982 ** Return the size of the database in pages (or zero, if unknown).
45983 */
45984 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
45985   if( pWal && ALWAYS(pWal->readLock>=0) ){
45986     return pWal->hdr.nPage;
45987   }
45988   return 0;
45989 }
45990
45991
45992 /* 
45993 ** This function starts a write transaction on the WAL.
45994 **
45995 ** A read transaction must have already been started by a prior call
45996 ** to sqlite3WalBeginReadTransaction().
45997 **
45998 ** If another thread or process has written into the database since
45999 ** the read transaction was started, then it is not possible for this
46000 ** thread to write as doing so would cause a fork.  So this routine
46001 ** returns SQLITE_BUSY in that case and no write transaction is started.
46002 **
46003 ** There can only be a single writer active at a time.
46004 */
46005 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
46006   int rc;
46007
46008   /* Cannot start a write transaction without first holding a read
46009   ** transaction. */
46010   assert( pWal->readLock>=0 );
46011
46012   if( pWal->readOnly ){
46013     return SQLITE_READONLY;
46014   }
46015
46016   /* Only one writer allowed at a time.  Get the write lock.  Return
46017   ** SQLITE_BUSY if unable.
46018   */
46019   rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
46020   if( rc ){
46021     return rc;
46022   }
46023   pWal->writeLock = 1;
46024
46025   /* If another connection has written to the database file since the
46026   ** time the read transaction on this connection was started, then
46027   ** the write is disallowed.
46028   */
46029   if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
46030     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
46031     pWal->writeLock = 0;
46032     rc = SQLITE_BUSY;
46033   }
46034
46035   return rc;
46036 }
46037
46038 /*
46039 ** End a write transaction.  The commit has already been done.  This
46040 ** routine merely releases the lock.
46041 */
46042 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
46043   if( pWal->writeLock ){
46044     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
46045     pWal->writeLock = 0;
46046   }
46047   return SQLITE_OK;
46048 }
46049
46050 /*
46051 ** If any data has been written (but not committed) to the log file, this
46052 ** function moves the write-pointer back to the start of the transaction.
46053 **
46054 ** Additionally, the callback function is invoked for each frame written
46055 ** to the WAL since the start of the transaction. If the callback returns
46056 ** other than SQLITE_OK, it is not invoked again and the error code is
46057 ** returned to the caller.
46058 **
46059 ** Otherwise, if the callback function does not return an error, this
46060 ** function returns SQLITE_OK.
46061 */
46062 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
46063   int rc = SQLITE_OK;
46064   if( ALWAYS(pWal->writeLock) ){
46065     Pgno iMax = pWal->hdr.mxFrame;
46066     Pgno iFrame;
46067   
46068     /* Restore the clients cache of the wal-index header to the state it
46069     ** was in before the client began writing to the database. 
46070     */
46071     memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
46072
46073     for(iFrame=pWal->hdr.mxFrame+1; 
46074         ALWAYS(rc==SQLITE_OK) && iFrame<=iMax; 
46075         iFrame++
46076     ){
46077       /* This call cannot fail. Unless the page for which the page number
46078       ** is passed as the second argument is (a) in the cache and 
46079       ** (b) has an outstanding reference, then xUndo is either a no-op
46080       ** (if (a) is false) or simply expels the page from the cache (if (b)
46081       ** is false).
46082       **
46083       ** If the upper layer is doing a rollback, it is guaranteed that there
46084       ** are no outstanding references to any page other than page 1. And
46085       ** page 1 is never written to the log until the transaction is
46086       ** committed. As a result, the call to xUndo may not fail.
46087       */
46088       assert( walFramePgno(pWal, iFrame)!=1 );
46089       rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
46090     }
46091     walCleanupHash(pWal);
46092   }
46093   assert( rc==SQLITE_OK );
46094   return rc;
46095 }
46096
46097 /* 
46098 ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32 
46099 ** values. This function populates the array with values required to 
46100 ** "rollback" the write position of the WAL handle back to the current 
46101 ** point in the event of a savepoint rollback (via WalSavepointUndo()).
46102 */
46103 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
46104   assert( pWal->writeLock );
46105   aWalData[0] = pWal->hdr.mxFrame;
46106   aWalData[1] = pWal->hdr.aFrameCksum[0];
46107   aWalData[2] = pWal->hdr.aFrameCksum[1];
46108   aWalData[3] = pWal->nCkpt;
46109 }
46110
46111 /* 
46112 ** Move the write position of the WAL back to the point identified by
46113 ** the values in the aWalData[] array. aWalData must point to an array
46114 ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
46115 ** by a call to WalSavepoint().
46116 */
46117 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
46118   int rc = SQLITE_OK;
46119
46120   assert( pWal->writeLock );
46121   assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
46122
46123   if( aWalData[3]!=pWal->nCkpt ){
46124     /* This savepoint was opened immediately after the write-transaction
46125     ** was started. Right after that, the writer decided to wrap around
46126     ** to the start of the log. Update the savepoint values to match.
46127     */
46128     aWalData[0] = 0;
46129     aWalData[3] = pWal->nCkpt;
46130   }
46131
46132   if( aWalData[0]<pWal->hdr.mxFrame ){
46133     pWal->hdr.mxFrame = aWalData[0];
46134     pWal->hdr.aFrameCksum[0] = aWalData[1];
46135     pWal->hdr.aFrameCksum[1] = aWalData[2];
46136     walCleanupHash(pWal);
46137   }
46138
46139   return rc;
46140 }
46141
46142 /*
46143 ** This function is called just before writing a set of frames to the log
46144 ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
46145 ** to the current log file, it is possible to overwrite the start of the
46146 ** existing log file with the new frames (i.e. "reset" the log). If so,
46147 ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
46148 ** unchanged.
46149 **
46150 ** SQLITE_OK is returned if no error is encountered (regardless of whether
46151 ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
46152 ** if an error occurs.
46153 */
46154 static int walRestartLog(Wal *pWal){
46155   int rc = SQLITE_OK;
46156   int cnt;
46157
46158   if( pWal->readLock==0 ){
46159     volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
46160     assert( pInfo->nBackfill==pWal->hdr.mxFrame );
46161     if( pInfo->nBackfill>0 ){
46162       u32 salt1;
46163       sqlite3_randomness(4, &salt1);
46164       rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
46165       if( rc==SQLITE_OK ){
46166         /* If all readers are using WAL_READ_LOCK(0) (in other words if no
46167         ** readers are currently using the WAL), then the transactions
46168         ** frames will overwrite the start of the existing log. Update the
46169         ** wal-index header to reflect this.
46170         **
46171         ** In theory it would be Ok to update the cache of the header only
46172         ** at this point. But updating the actual wal-index header is also
46173         ** safe and means there is no special case for sqlite3WalUndo()
46174         ** to handle if this transaction is rolled back.
46175         */
46176         int i;                    /* Loop counter */
46177         u32 *aSalt = pWal->hdr.aSalt;       /* Big-endian salt values */
46178
46179         /* Limit the size of WAL file if the journal_size_limit PRAGMA is
46180         ** set to a non-negative value.  Log errors encountered
46181         ** during the truncation attempt. */
46182         if( pWal->mxWalSize>=0 ){
46183           i64 sz;
46184           int rx;
46185           sqlite3BeginBenignMalloc();
46186           rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
46187           if( rx==SQLITE_OK && (sz > pWal->mxWalSize) ){
46188             rx = sqlite3OsTruncate(pWal->pWalFd, pWal->mxWalSize);
46189           }
46190           sqlite3EndBenignMalloc();
46191           if( rx ){
46192             sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
46193           }
46194         }
46195
46196         pWal->nCkpt++;
46197         pWal->hdr.mxFrame = 0;
46198         sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
46199         aSalt[1] = salt1;
46200         walIndexWriteHdr(pWal);
46201         pInfo->nBackfill = 0;
46202         for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
46203         assert( pInfo->aReadMark[0]==0 );
46204         walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
46205       }else if( rc!=SQLITE_BUSY ){
46206         return rc;
46207       }
46208     }
46209     walUnlockShared(pWal, WAL_READ_LOCK(0));
46210     pWal->readLock = -1;
46211     cnt = 0;
46212     do{
46213       int notUsed;
46214       rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
46215     }while( rc==WAL_RETRY );
46216     assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
46217     testcase( (rc&0xff)==SQLITE_IOERR );
46218     testcase( rc==SQLITE_PROTOCOL );
46219     testcase( rc==SQLITE_OK );
46220   }
46221   return rc;
46222 }
46223
46224 /* 
46225 ** Write a set of frames to the log. The caller must hold the write-lock
46226 ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
46227 */
46228 SQLITE_PRIVATE int sqlite3WalFrames(
46229   Wal *pWal,                      /* Wal handle to write to */
46230   int szPage,                     /* Database page-size in bytes */
46231   PgHdr *pList,                   /* List of dirty pages to write */
46232   Pgno nTruncate,                 /* Database size after this commit */
46233   int isCommit,                   /* True if this is a commit */
46234   int sync_flags                  /* Flags to pass to OsSync() (or 0) */
46235 ){
46236   int rc;                         /* Used to catch return codes */
46237   u32 iFrame;                     /* Next frame address */
46238   u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */
46239   PgHdr *p;                       /* Iterator to run through pList with. */
46240   PgHdr *pLast = 0;               /* Last frame in list */
46241   int nLast = 0;                  /* Number of extra copies of last page */
46242
46243   assert( pList );
46244   assert( pWal->writeLock );
46245
46246 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
46247   { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
46248     WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
46249               pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
46250   }
46251 #endif
46252
46253   /* See if it is possible to write these frames into the start of the
46254   ** log file, instead of appending to it at pWal->hdr.mxFrame.
46255   */
46256   if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
46257     return rc;
46258   }
46259
46260   /* If this is the first frame written into the log, write the WAL
46261   ** header to the start of the WAL file. See comments at the top of
46262   ** this source file for a description of the WAL header format.
46263   */
46264   iFrame = pWal->hdr.mxFrame;
46265   if( iFrame==0 ){
46266     u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */
46267     u32 aCksum[2];                /* Checksum for wal-header */
46268
46269     sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
46270     sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
46271     sqlite3Put4byte(&aWalHdr[8], szPage);
46272     sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
46273     sqlite3_randomness(8, pWal->hdr.aSalt);
46274     memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
46275     walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
46276     sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
46277     sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
46278     
46279     pWal->szPage = szPage;
46280     pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
46281     pWal->hdr.aFrameCksum[0] = aCksum[0];
46282     pWal->hdr.aFrameCksum[1] = aCksum[1];
46283
46284     rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
46285     WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
46286     if( rc!=SQLITE_OK ){
46287       return rc;
46288     }
46289   }
46290   assert( (int)pWal->szPage==szPage );
46291
46292   /* Write the log file. */
46293   for(p=pList; p; p=p->pDirty){
46294     u32 nDbsize;                  /* Db-size field for frame header */
46295     i64 iOffset;                  /* Write offset in log file */
46296     void *pData;
46297    
46298     iOffset = walFrameOffset(++iFrame, szPage);
46299     /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
46300     
46301     /* Populate and write the frame header */
46302     nDbsize = (isCommit && p->pDirty==0) ? nTruncate : 0;
46303 #if defined(SQLITE_HAS_CODEC)
46304     if( (pData = sqlite3PagerCodec(p))==0 ) return SQLITE_NOMEM;
46305 #else
46306     pData = p->pData;
46307 #endif
46308     walEncodeFrame(pWal, p->pgno, nDbsize, pData, aFrame);
46309     rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOffset);
46310     if( rc!=SQLITE_OK ){
46311       return rc;
46312     }
46313
46314     /* Write the page data */
46315     rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOffset+sizeof(aFrame));
46316     if( rc!=SQLITE_OK ){
46317       return rc;
46318     }
46319     pLast = p;
46320   }
46321
46322   /* Sync the log file if the 'isSync' flag was specified. */
46323   if( sync_flags ){
46324     i64 iSegment = sqlite3OsSectorSize(pWal->pWalFd);
46325     i64 iOffset = walFrameOffset(iFrame+1, szPage);
46326
46327     assert( isCommit );
46328     assert( iSegment>0 );
46329
46330     iSegment = (((iOffset+iSegment-1)/iSegment) * iSegment);
46331     while( iOffset<iSegment ){
46332       void *pData;
46333 #if defined(SQLITE_HAS_CODEC)
46334       if( (pData = sqlite3PagerCodec(pLast))==0 ) return SQLITE_NOMEM;
46335 #else
46336       pData = pLast->pData;
46337 #endif
46338       walEncodeFrame(pWal, pLast->pgno, nTruncate, pData, aFrame);
46339       /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
46340       rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOffset);
46341       if( rc!=SQLITE_OK ){
46342         return rc;
46343       }
46344       iOffset += WAL_FRAME_HDRSIZE;
46345       rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOffset); 
46346       if( rc!=SQLITE_OK ){
46347         return rc;
46348       }
46349       nLast++;
46350       iOffset += szPage;
46351     }
46352
46353     rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
46354   }
46355
46356   /* Append data to the wal-index. It is not necessary to lock the 
46357   ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
46358   ** guarantees that there are no other writers, and no data that may
46359   ** be in use by existing readers is being overwritten.
46360   */
46361   iFrame = pWal->hdr.mxFrame;
46362   for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
46363     iFrame++;
46364     rc = walIndexAppend(pWal, iFrame, p->pgno);
46365   }
46366   while( nLast>0 && rc==SQLITE_OK ){
46367     iFrame++;
46368     nLast--;
46369     rc = walIndexAppend(pWal, iFrame, pLast->pgno);
46370   }
46371
46372   if( rc==SQLITE_OK ){
46373     /* Update the private copy of the header. */
46374     pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
46375     testcase( szPage<=32768 );
46376     testcase( szPage>=65536 );
46377     pWal->hdr.mxFrame = iFrame;
46378     if( isCommit ){
46379       pWal->hdr.iChange++;
46380       pWal->hdr.nPage = nTruncate;
46381     }
46382     /* If this is a commit, update the wal-index header too. */
46383     if( isCommit ){
46384       walIndexWriteHdr(pWal);
46385       pWal->iCallback = iFrame;
46386     }
46387   }
46388
46389   WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
46390   return rc;
46391 }
46392
46393 /* 
46394 ** This routine is called to implement sqlite3_wal_checkpoint() and
46395 ** related interfaces.
46396 **
46397 ** Obtain a CHECKPOINT lock and then backfill as much information as
46398 ** we can from WAL into the database.
46399 **
46400 ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
46401 ** callback. In this case this function runs a blocking checkpoint.
46402 */
46403 SQLITE_PRIVATE int sqlite3WalCheckpoint(
46404   Wal *pWal,                      /* Wal connection */
46405   int eMode,                      /* PASSIVE, FULL or RESTART */
46406   int (*xBusy)(void*),            /* Function to call when busy */
46407   void *pBusyArg,                 /* Context argument for xBusyHandler */
46408   int sync_flags,                 /* Flags to sync db file with (or 0) */
46409   int nBuf,                       /* Size of temporary buffer */
46410   u8 *zBuf,                       /* Temporary buffer to use */
46411   int *pnLog,                     /* OUT: Number of frames in WAL */
46412   int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
46413 ){
46414   int rc;                         /* Return code */
46415   int isChanged = 0;              /* True if a new wal-index header is loaded */
46416   int eMode2 = eMode;             /* Mode to pass to walCheckpoint() */
46417
46418   assert( pWal->ckptLock==0 );
46419   assert( pWal->writeLock==0 );
46420
46421   if( pWal->readOnly ) return SQLITE_READONLY;
46422   WALTRACE(("WAL%p: checkpoint begins\n", pWal));
46423   rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
46424   if( rc ){
46425     /* Usually this is SQLITE_BUSY meaning that another thread or process
46426     ** is already running a checkpoint, or maybe a recovery.  But it might
46427     ** also be SQLITE_IOERR. */
46428     return rc;
46429   }
46430   pWal->ckptLock = 1;
46431
46432   /* If this is a blocking-checkpoint, then obtain the write-lock as well
46433   ** to prevent any writers from running while the checkpoint is underway.
46434   ** This has to be done before the call to walIndexReadHdr() below.
46435   **
46436   ** If the writer lock cannot be obtained, then a passive checkpoint is
46437   ** run instead. Since the checkpointer is not holding the writer lock,
46438   ** there is no point in blocking waiting for any readers. Assuming no 
46439   ** other error occurs, this function will return SQLITE_BUSY to the caller.
46440   */
46441   if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
46442     rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
46443     if( rc==SQLITE_OK ){
46444       pWal->writeLock = 1;
46445     }else if( rc==SQLITE_BUSY ){
46446       eMode2 = SQLITE_CHECKPOINT_PASSIVE;
46447       rc = SQLITE_OK;
46448     }
46449   }
46450
46451   /* Read the wal-index header. */
46452   if( rc==SQLITE_OK ){
46453     rc = walIndexReadHdr(pWal, &isChanged);
46454   }
46455
46456   /* Copy data from the log to the database file. */
46457   if( rc==SQLITE_OK ){
46458     if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
46459       rc = SQLITE_CORRUPT_BKPT;
46460     }else{
46461       rc = walCheckpoint(pWal, eMode2, xBusy, pBusyArg, sync_flags, zBuf);
46462     }
46463
46464     /* If no error occurred, set the output variables. */
46465     if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
46466       if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
46467       if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
46468     }
46469   }
46470
46471   if( isChanged ){
46472     /* If a new wal-index header was loaded before the checkpoint was 
46473     ** performed, then the pager-cache associated with pWal is now
46474     ** out of date. So zero the cached wal-index header to ensure that
46475     ** next time the pager opens a snapshot on this database it knows that
46476     ** the cache needs to be reset.
46477     */
46478     memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
46479   }
46480
46481   /* Release the locks. */
46482   sqlite3WalEndWriteTransaction(pWal);
46483   walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
46484   pWal->ckptLock = 0;
46485   WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
46486   return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
46487 }
46488
46489 /* Return the value to pass to a sqlite3_wal_hook callback, the
46490 ** number of frames in the WAL at the point of the last commit since
46491 ** sqlite3WalCallback() was called.  If no commits have occurred since
46492 ** the last call, then return 0.
46493 */
46494 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
46495   u32 ret = 0;
46496   if( pWal ){
46497     ret = pWal->iCallback;
46498     pWal->iCallback = 0;
46499   }
46500   return (int)ret;
46501 }
46502
46503 /*
46504 ** This function is called to change the WAL subsystem into or out
46505 ** of locking_mode=EXCLUSIVE.
46506 **
46507 ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
46508 ** into locking_mode=NORMAL.  This means that we must acquire a lock
46509 ** on the pWal->readLock byte.  If the WAL is already in locking_mode=NORMAL
46510 ** or if the acquisition of the lock fails, then return 0.  If the
46511 ** transition out of exclusive-mode is successful, return 1.  This
46512 ** operation must occur while the pager is still holding the exclusive
46513 ** lock on the main database file.
46514 **
46515 ** If op is one, then change from locking_mode=NORMAL into 
46516 ** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must
46517 ** be released.  Return 1 if the transition is made and 0 if the
46518 ** WAL is already in exclusive-locking mode - meaning that this
46519 ** routine is a no-op.  The pager must already hold the exclusive lock
46520 ** on the main database file before invoking this operation.
46521 **
46522 ** If op is negative, then do a dry-run of the op==1 case but do
46523 ** not actually change anything. The pager uses this to see if it
46524 ** should acquire the database exclusive lock prior to invoking
46525 ** the op==1 case.
46526 */
46527 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
46528   int rc;
46529   assert( pWal->writeLock==0 );
46530   assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
46531
46532   /* pWal->readLock is usually set, but might be -1 if there was a 
46533   ** prior error while attempting to acquire are read-lock. This cannot 
46534   ** happen if the connection is actually in exclusive mode (as no xShmLock
46535   ** locks are taken in this case). Nor should the pager attempt to
46536   ** upgrade to exclusive-mode following such an error.
46537   */
46538   assert( pWal->readLock>=0 || pWal->lockError );
46539   assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
46540
46541   if( op==0 ){
46542     if( pWal->exclusiveMode ){
46543       pWal->exclusiveMode = 0;
46544       if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
46545         pWal->exclusiveMode = 1;
46546       }
46547       rc = pWal->exclusiveMode==0;
46548     }else{
46549       /* Already in locking_mode=NORMAL */
46550       rc = 0;
46551     }
46552   }else if( op>0 ){
46553     assert( pWal->exclusiveMode==0 );
46554     assert( pWal->readLock>=0 );
46555     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
46556     pWal->exclusiveMode = 1;
46557     rc = 1;
46558   }else{
46559     rc = pWal->exclusiveMode==0;
46560   }
46561   return rc;
46562 }
46563
46564 /* 
46565 ** Return true if the argument is non-NULL and the WAL module is using
46566 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
46567 ** WAL module is using shared-memory, return false. 
46568 */
46569 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
46570   return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
46571 }
46572
46573 #endif /* #ifndef SQLITE_OMIT_WAL */
46574
46575 /************** End of wal.c *************************************************/
46576 /************** Begin file btmutex.c *****************************************/
46577 /*
46578 ** 2007 August 27
46579 **
46580 ** The author disclaims copyright to this source code.  In place of
46581 ** a legal notice, here is a blessing:
46582 **
46583 **    May you do good and not evil.
46584 **    May you find forgiveness for yourself and forgive others.
46585 **    May you share freely, never taking more than you give.
46586 **
46587 *************************************************************************
46588 **
46589 ** This file contains code used to implement mutexes on Btree objects.
46590 ** This code really belongs in btree.c.  But btree.c is getting too
46591 ** big and we want to break it down some.  This packaged seemed like
46592 ** a good breakout.
46593 */
46594 /************** Include btreeInt.h in the middle of btmutex.c ****************/
46595 /************** Begin file btreeInt.h ****************************************/
46596 /*
46597 ** 2004 April 6
46598 **
46599 ** The author disclaims copyright to this source code.  In place of
46600 ** a legal notice, here is a blessing:
46601 **
46602 **    May you do good and not evil.
46603 **    May you find forgiveness for yourself and forgive others.
46604 **    May you share freely, never taking more than you give.
46605 **
46606 *************************************************************************
46607 ** This file implements a external (disk-based) database using BTrees.
46608 ** For a detailed discussion of BTrees, refer to
46609 **
46610 **     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
46611 **     "Sorting And Searching", pages 473-480. Addison-Wesley
46612 **     Publishing Company, Reading, Massachusetts.
46613 **
46614 ** The basic idea is that each page of the file contains N database
46615 ** entries and N+1 pointers to subpages.
46616 **
46617 **   ----------------------------------------------------------------
46618 **   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
46619 **   ----------------------------------------------------------------
46620 **
46621 ** All of the keys on the page that Ptr(0) points to have values less
46622 ** than Key(0).  All of the keys on page Ptr(1) and its subpages have
46623 ** values greater than Key(0) and less than Key(1).  All of the keys
46624 ** on Ptr(N) and its subpages have values greater than Key(N-1).  And
46625 ** so forth.
46626 **
46627 ** Finding a particular key requires reading O(log(M)) pages from the 
46628 ** disk where M is the number of entries in the tree.
46629 **
46630 ** In this implementation, a single file can hold one or more separate 
46631 ** BTrees.  Each BTree is identified by the index of its root page.  The
46632 ** key and data for any entry are combined to form the "payload".  A
46633 ** fixed amount of payload can be carried directly on the database
46634 ** page.  If the payload is larger than the preset amount then surplus
46635 ** bytes are stored on overflow pages.  The payload for an entry
46636 ** and the preceding pointer are combined to form a "Cell".  Each 
46637 ** page has a small header which contains the Ptr(N) pointer and other
46638 ** information such as the size of key and data.
46639 **
46640 ** FORMAT DETAILS
46641 **
46642 ** The file is divided into pages.  The first page is called page 1,
46643 ** the second is page 2, and so forth.  A page number of zero indicates
46644 ** "no such page".  The page size can be any power of 2 between 512 and 65536.
46645 ** Each page can be either a btree page, a freelist page, an overflow
46646 ** page, or a pointer-map page.
46647 **
46648 ** The first page is always a btree page.  The first 100 bytes of the first
46649 ** page contain a special header (the "file header") that describes the file.
46650 ** The format of the file header is as follows:
46651 **
46652 **   OFFSET   SIZE    DESCRIPTION
46653 **      0      16     Header string: "SQLite format 3\000"
46654 **     16       2     Page size in bytes.  
46655 **     18       1     File format write version
46656 **     19       1     File format read version
46657 **     20       1     Bytes of unused space at the end of each page
46658 **     21       1     Max embedded payload fraction
46659 **     22       1     Min embedded payload fraction
46660 **     23       1     Min leaf payload fraction
46661 **     24       4     File change counter
46662 **     28       4     Reserved for future use
46663 **     32       4     First freelist page
46664 **     36       4     Number of freelist pages in the file
46665 **     40      60     15 4-byte meta values passed to higher layers
46666 **
46667 **     40       4     Schema cookie
46668 **     44       4     File format of schema layer
46669 **     48       4     Size of page cache
46670 **     52       4     Largest root-page (auto/incr_vacuum)
46671 **     56       4     1=UTF-8 2=UTF16le 3=UTF16be
46672 **     60       4     User version
46673 **     64       4     Incremental vacuum mode
46674 **     68       4     unused
46675 **     72       4     unused
46676 **     76       4     unused
46677 **
46678 ** All of the integer values are big-endian (most significant byte first).
46679 **
46680 ** The file change counter is incremented when the database is changed
46681 ** This counter allows other processes to know when the file has changed
46682 ** and thus when they need to flush their cache.
46683 **
46684 ** The max embedded payload fraction is the amount of the total usable
46685 ** space in a page that can be consumed by a single cell for standard
46686 ** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
46687 ** is to limit the maximum cell size so that at least 4 cells will fit
46688 ** on one page.  Thus the default max embedded payload fraction is 64.
46689 **
46690 ** If the payload for a cell is larger than the max payload, then extra
46691 ** payload is spilled to overflow pages.  Once an overflow page is allocated,
46692 ** as many bytes as possible are moved into the overflow pages without letting
46693 ** the cell size drop below the min embedded payload fraction.
46694 **
46695 ** The min leaf payload fraction is like the min embedded payload fraction
46696 ** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
46697 ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
46698 ** not specified in the header.
46699 **
46700 ** Each btree pages is divided into three sections:  The header, the
46701 ** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
46702 ** file header that occurs before the page header.
46703 **
46704 **      |----------------|
46705 **      | file header    |   100 bytes.  Page 1 only.
46706 **      |----------------|
46707 **      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
46708 **      |----------------|
46709 **      | cell pointer   |   |  2 bytes per cell.  Sorted order.
46710 **      | array          |   |  Grows downward
46711 **      |                |   v
46712 **      |----------------|
46713 **      | unallocated    |
46714 **      | space          |
46715 **      |----------------|   ^  Grows upwards
46716 **      | cell content   |   |  Arbitrary order interspersed with freeblocks.
46717 **      | area           |   |  and free space fragments.
46718 **      |----------------|
46719 **
46720 ** The page headers looks like this:
46721 **
46722 **   OFFSET   SIZE     DESCRIPTION
46723 **      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
46724 **      1       2      byte offset to the first freeblock
46725 **      3       2      number of cells on this page
46726 **      5       2      first byte of the cell content area
46727 **      7       1      number of fragmented free bytes
46728 **      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
46729 **
46730 ** The flags define the format of this btree page.  The leaf flag means that
46731 ** this page has no children.  The zerodata flag means that this page carries
46732 ** only keys and no data.  The intkey flag means that the key is a integer
46733 ** which is stored in the key size entry of the cell header rather than in
46734 ** the payload area.
46735 **
46736 ** The cell pointer array begins on the first byte after the page header.
46737 ** The cell pointer array contains zero or more 2-byte numbers which are
46738 ** offsets from the beginning of the page to the cell content in the cell
46739 ** content area.  The cell pointers occur in sorted order.  The system strives
46740 ** to keep free space after the last cell pointer so that new cells can
46741 ** be easily added without having to defragment the page.
46742 **
46743 ** Cell content is stored at the very end of the page and grows toward the
46744 ** beginning of the page.
46745 **
46746 ** Unused space within the cell content area is collected into a linked list of
46747 ** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
46748 ** to the first freeblock is given in the header.  Freeblocks occur in
46749 ** increasing order.  Because a freeblock must be at least 4 bytes in size,
46750 ** any group of 3 or fewer unused bytes in the cell content area cannot
46751 ** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
46752 ** a fragment.  The total number of bytes in all fragments is recorded.
46753 ** in the page header at offset 7.
46754 **
46755 **    SIZE    DESCRIPTION
46756 **      2     Byte offset of the next freeblock
46757 **      2     Bytes in this freeblock
46758 **
46759 ** Cells are of variable length.  Cells are stored in the cell content area at
46760 ** the end of the page.  Pointers to the cells are in the cell pointer array
46761 ** that immediately follows the page header.  Cells is not necessarily
46762 ** contiguous or in order, but cell pointers are contiguous and in order.
46763 **
46764 ** Cell content makes use of variable length integers.  A variable
46765 ** length integer is 1 to 9 bytes where the lower 7 bits of each 
46766 ** byte are used.  The integer consists of all bytes that have bit 8 set and
46767 ** the first byte with bit 8 clear.  The most significant byte of the integer
46768 ** appears first.  A variable-length integer may not be more than 9 bytes long.
46769 ** As a special case, all 8 bytes of the 9th byte are used as data.  This
46770 ** allows a 64-bit integer to be encoded in 9 bytes.
46771 **
46772 **    0x00                      becomes  0x00000000
46773 **    0x7f                      becomes  0x0000007f
46774 **    0x81 0x00                 becomes  0x00000080
46775 **    0x82 0x00                 becomes  0x00000100
46776 **    0x80 0x7f                 becomes  0x0000007f
46777 **    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
46778 **    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
46779 **
46780 ** Variable length integers are used for rowids and to hold the number of
46781 ** bytes of key and data in a btree cell.
46782 **
46783 ** The content of a cell looks like this:
46784 **
46785 **    SIZE    DESCRIPTION
46786 **      4     Page number of the left child. Omitted if leaf flag is set.
46787 **     var    Number of bytes of data. Omitted if the zerodata flag is set.
46788 **     var    Number of bytes of key. Or the key itself if intkey flag is set.
46789 **      *     Payload
46790 **      4     First page of the overflow chain.  Omitted if no overflow
46791 **
46792 ** Overflow pages form a linked list.  Each page except the last is completely
46793 ** filled with data (pagesize - 4 bytes).  The last page can have as little
46794 ** as 1 byte of data.
46795 **
46796 **    SIZE    DESCRIPTION
46797 **      4     Page number of next overflow page
46798 **      *     Data
46799 **
46800 ** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
46801 ** file header points to the first in a linked list of trunk page.  Each trunk
46802 ** page points to multiple leaf pages.  The content of a leaf page is
46803 ** unspecified.  A trunk page looks like this:
46804 **
46805 **    SIZE    DESCRIPTION
46806 **      4     Page number of next trunk page
46807 **      4     Number of leaf pointers on this page
46808 **      *     zero or more pages numbers of leaves
46809 */
46810
46811
46812 /* The following value is the maximum cell size assuming a maximum page
46813 ** size give above.
46814 */
46815 #define MX_CELL_SIZE(pBt)  ((int)(pBt->pageSize-8))
46816
46817 /* The maximum number of cells on a single page of the database.  This
46818 ** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
46819 ** plus 2 bytes for the index to the cell in the page header).  Such
46820 ** small cells will be rare, but they are possible.
46821 */
46822 #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
46823
46824 /* Forward declarations */
46825 typedef struct MemPage MemPage;
46826 typedef struct BtLock BtLock;
46827
46828 /*
46829 ** This is a magic string that appears at the beginning of every
46830 ** SQLite database in order to identify the file as a real database.
46831 **
46832 ** You can change this value at compile-time by specifying a
46833 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
46834 ** header must be exactly 16 bytes including the zero-terminator so
46835 ** the string itself should be 15 characters long.  If you change
46836 ** the header, then your custom library will not be able to read 
46837 ** databases generated by the standard tools and the standard tools
46838 ** will not be able to read databases created by your custom library.
46839 */
46840 #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
46841 #  define SQLITE_FILE_HEADER "SQLite format 3"
46842 #endif
46843
46844 /*
46845 ** Page type flags.  An ORed combination of these flags appear as the
46846 ** first byte of on-disk image of every BTree page.
46847 */
46848 #define PTF_INTKEY    0x01
46849 #define PTF_ZERODATA  0x02
46850 #define PTF_LEAFDATA  0x04
46851 #define PTF_LEAF      0x08
46852
46853 /*
46854 ** As each page of the file is loaded into memory, an instance of the following
46855 ** structure is appended and initialized to zero.  This structure stores
46856 ** information about the page that is decoded from the raw file page.
46857 **
46858 ** The pParent field points back to the parent page.  This allows us to
46859 ** walk up the BTree from any leaf to the root.  Care must be taken to
46860 ** unref() the parent page pointer when this page is no longer referenced.
46861 ** The pageDestructor() routine handles that chore.
46862 **
46863 ** Access to all fields of this structure is controlled by the mutex
46864 ** stored in MemPage.pBt->mutex.
46865 */
46866 struct MemPage {
46867   u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
46868   u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
46869   u8 intKey;           /* True if intkey flag is set */
46870   u8 leaf;             /* True if leaf flag is set */
46871   u8 hasData;          /* True if this page stores data */
46872   u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
46873   u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
46874   u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
46875   u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
46876   u16 cellOffset;      /* Index in aData of first cell pointer */
46877   u16 nFree;           /* Number of free bytes on the page */
46878   u16 nCell;           /* Number of cells on this page, local and ovfl */
46879   u16 maskPage;        /* Mask for page offset */
46880   struct _OvflCell {   /* Cells that will not fit on aData[] */
46881     u8 *pCell;          /* Pointers to the body of the overflow cell */
46882     u16 idx;            /* Insert this cell before idx-th non-overflow cell */
46883   } aOvfl[5];
46884   BtShared *pBt;       /* Pointer to BtShared that this page is part of */
46885   u8 *aData;           /* Pointer to disk image of the page data */
46886   DbPage *pDbPage;     /* Pager page handle */
46887   Pgno pgno;           /* Page number for this page */
46888 };
46889
46890 /*
46891 ** The in-memory image of a disk page has the auxiliary information appended
46892 ** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
46893 ** that extra information.
46894 */
46895 #define EXTRA_SIZE sizeof(MemPage)
46896
46897 /*
46898 ** A linked list of the following structures is stored at BtShared.pLock.
46899 ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor 
46900 ** is opened on the table with root page BtShared.iTable. Locks are removed
46901 ** from this list when a transaction is committed or rolled back, or when
46902 ** a btree handle is closed.
46903 */
46904 struct BtLock {
46905   Btree *pBtree;        /* Btree handle holding this lock */
46906   Pgno iTable;          /* Root page of table */
46907   u8 eLock;             /* READ_LOCK or WRITE_LOCK */
46908   BtLock *pNext;        /* Next in BtShared.pLock list */
46909 };
46910
46911 /* Candidate values for BtLock.eLock */
46912 #define READ_LOCK     1
46913 #define WRITE_LOCK    2
46914
46915 /* A Btree handle
46916 **
46917 ** A database connection contains a pointer to an instance of
46918 ** this object for every database file that it has open.  This structure
46919 ** is opaque to the database connection.  The database connection cannot
46920 ** see the internals of this structure and only deals with pointers to
46921 ** this structure.
46922 **
46923 ** For some database files, the same underlying database cache might be 
46924 ** shared between multiple connections.  In that case, each connection
46925 ** has it own instance of this object.  But each instance of this object
46926 ** points to the same BtShared object.  The database cache and the
46927 ** schema associated with the database file are all contained within
46928 ** the BtShared object.
46929 **
46930 ** All fields in this structure are accessed under sqlite3.mutex.
46931 ** The pBt pointer itself may not be changed while there exists cursors 
46932 ** in the referenced BtShared that point back to this Btree since those
46933 ** cursors have to go through this Btree to find their BtShared and
46934 ** they often do so without holding sqlite3.mutex.
46935 */
46936 struct Btree {
46937   sqlite3 *db;       /* The database connection holding this btree */
46938   BtShared *pBt;     /* Sharable content of this btree */
46939   u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
46940   u8 sharable;       /* True if we can share pBt with another db */
46941   u8 locked;         /* True if db currently has pBt locked */
46942   int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
46943   int nBackup;       /* Number of backup operations reading this btree */
46944   Btree *pNext;      /* List of other sharable Btrees from the same db */
46945   Btree *pPrev;      /* Back pointer of the same list */
46946 #ifndef SQLITE_OMIT_SHARED_CACHE
46947   BtLock lock;       /* Object used to lock page 1 */
46948 #endif
46949 };
46950
46951 /*
46952 ** Btree.inTrans may take one of the following values.
46953 **
46954 ** If the shared-data extension is enabled, there may be multiple users
46955 ** of the Btree structure. At most one of these may open a write transaction,
46956 ** but any number may have active read transactions.
46957 */
46958 #define TRANS_NONE  0
46959 #define TRANS_READ  1
46960 #define TRANS_WRITE 2
46961
46962 /*
46963 ** An instance of this object represents a single database file.
46964 ** 
46965 ** A single database file can be in use as the same time by two
46966 ** or more database connections.  When two or more connections are
46967 ** sharing the same database file, each connection has it own
46968 ** private Btree object for the file and each of those Btrees points
46969 ** to this one BtShared object.  BtShared.nRef is the number of
46970 ** connections currently sharing this database file.
46971 **
46972 ** Fields in this structure are accessed under the BtShared.mutex
46973 ** mutex, except for nRef and pNext which are accessed under the
46974 ** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
46975 ** may not be modified once it is initially set as long as nRef>0.
46976 ** The pSchema field may be set once under BtShared.mutex and
46977 ** thereafter is unchanged as long as nRef>0.
46978 **
46979 ** isPending:
46980 **
46981 **   If a BtShared client fails to obtain a write-lock on a database
46982 **   table (because there exists one or more read-locks on the table),
46983 **   the shared-cache enters 'pending-lock' state and isPending is
46984 **   set to true.
46985 **
46986 **   The shared-cache leaves the 'pending lock' state when either of
46987 **   the following occur:
46988 **
46989 **     1) The current writer (BtShared.pWriter) concludes its transaction, OR
46990 **     2) The number of locks held by other connections drops to zero.
46991 **
46992 **   while in the 'pending-lock' state, no connection may start a new
46993 **   transaction.
46994 **
46995 **   This feature is included to help prevent writer-starvation.
46996 */
46997 struct BtShared {
46998   Pager *pPager;        /* The page cache */
46999   sqlite3 *db;          /* Database connection currently using this Btree */
47000   BtCursor *pCursor;    /* A list of all open cursors */
47001   MemPage *pPage1;      /* First page of the database */
47002   u8 readOnly;          /* True if the underlying file is readonly */
47003   u8 pageSizeFixed;     /* True if the page size can no longer be changed */
47004   u8 secureDelete;      /* True if secure_delete is enabled */
47005   u8 initiallyEmpty;    /* Database is empty at start of transaction */
47006   u8 openFlags;         /* Flags to sqlite3BtreeOpen() */
47007 #ifndef SQLITE_OMIT_AUTOVACUUM
47008   u8 autoVacuum;        /* True if auto-vacuum is enabled */
47009   u8 incrVacuum;        /* True if incr-vacuum is enabled */
47010 #endif
47011   u8 inTransaction;     /* Transaction state */
47012   u8 doNotUseWAL;       /* If true, do not open write-ahead-log file */
47013   u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
47014   u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
47015   u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
47016   u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
47017   u32 pageSize;         /* Total number of bytes on a page */
47018   u32 usableSize;       /* Number of usable bytes on each page */
47019   int nTransaction;     /* Number of open transactions (read + write) */
47020   u32 nPage;            /* Number of pages in the database */
47021   void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
47022   void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
47023   sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
47024   Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
47025 #ifndef SQLITE_OMIT_SHARED_CACHE
47026   int nRef;             /* Number of references to this structure */
47027   BtShared *pNext;      /* Next on a list of sharable BtShared structs */
47028   BtLock *pLock;        /* List of locks held on this shared-btree struct */
47029   Btree *pWriter;       /* Btree with currently open write transaction */
47030   u8 isExclusive;       /* True if pWriter has an EXCLUSIVE lock on the db */
47031   u8 isPending;         /* If waiting for read-locks to clear */
47032 #endif
47033   u8 *pTmpSpace;        /* BtShared.pageSize bytes of space for tmp use */
47034 };
47035
47036 /*
47037 ** An instance of the following structure is used to hold information
47038 ** about a cell.  The parseCellPtr() function fills in this structure
47039 ** based on information extract from the raw disk page.
47040 */
47041 typedef struct CellInfo CellInfo;
47042 struct CellInfo {
47043   i64 nKey;      /* The key for INTKEY tables, or number of bytes in key */
47044   u8 *pCell;     /* Pointer to the start of cell content */
47045   u32 nData;     /* Number of bytes of data */
47046   u32 nPayload;  /* Total amount of payload */
47047   u16 nHeader;   /* Size of the cell content header in bytes */
47048   u16 nLocal;    /* Amount of payload held locally */
47049   u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
47050   u16 nSize;     /* Size of the cell content on the main b-tree page */
47051 };
47052
47053 /*
47054 ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
47055 ** this will be declared corrupt. This value is calculated based on a
47056 ** maximum database size of 2^31 pages a minimum fanout of 2 for a
47057 ** root-node and 3 for all other internal nodes.
47058 **
47059 ** If a tree that appears to be taller than this is encountered, it is
47060 ** assumed that the database is corrupt.
47061 */
47062 #define BTCURSOR_MAX_DEPTH 20
47063
47064 /*
47065 ** A cursor is a pointer to a particular entry within a particular
47066 ** b-tree within a database file.
47067 **
47068 ** The entry is identified by its MemPage and the index in
47069 ** MemPage.aCell[] of the entry.
47070 **
47071 ** A single database file can shared by two more database connections,
47072 ** but cursors cannot be shared.  Each cursor is associated with a
47073 ** particular database connection identified BtCursor.pBtree.db.
47074 **
47075 ** Fields in this structure are accessed under the BtShared.mutex
47076 ** found at self->pBt->mutex. 
47077 */
47078 struct BtCursor {
47079   Btree *pBtree;            /* The Btree to which this cursor belongs */
47080   BtShared *pBt;            /* The BtShared this cursor points to */
47081   BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
47082   struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
47083   Pgno pgnoRoot;            /* The root page of this tree */
47084   sqlite3_int64 cachedRowid; /* Next rowid cache.  0 means not valid */
47085   CellInfo info;            /* A parse of the cell we are pointing at */
47086   i64 nKey;        /* Size of pKey, or last integer key */
47087   void *pKey;      /* Saved key that was cursor's last known position */
47088   int skipNext;    /* Prev() is noop if negative. Next() is noop if positive */
47089   u8 wrFlag;                /* True if writable */
47090   u8 atLast;                /* Cursor pointing to the last entry */
47091   u8 validNKey;             /* True if info.nKey is valid */
47092   u8 eState;                /* One of the CURSOR_XXX constants (see below) */
47093 #ifndef SQLITE_OMIT_INCRBLOB
47094   Pgno *aOverflow;          /* Cache of overflow page locations */
47095   u8 isIncrblobHandle;      /* True if this cursor is an incr. io handle */
47096 #endif
47097   i16 iPage;                            /* Index of current page in apPage */
47098   u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
47099   MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
47100 };
47101
47102 /*
47103 ** Potential values for BtCursor.eState.
47104 **
47105 ** CURSOR_VALID:
47106 **   Cursor points to a valid entry. getPayload() etc. may be called.
47107 **
47108 ** CURSOR_INVALID:
47109 **   Cursor does not point to a valid entry. This can happen (for example) 
47110 **   because the table is empty or because BtreeCursorFirst() has not been
47111 **   called.
47112 **
47113 ** CURSOR_REQUIRESEEK:
47114 **   The table that this cursor was opened on still exists, but has been 
47115 **   modified since the cursor was last used. The cursor position is saved
47116 **   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in 
47117 **   this state, restoreCursorPosition() can be called to attempt to
47118 **   seek the cursor to the saved position.
47119 **
47120 ** CURSOR_FAULT:
47121 **   A unrecoverable error (an I/O error or a malloc failure) has occurred
47122 **   on a different connection that shares the BtShared cache with this
47123 **   cursor.  The error has left the cache in an inconsistent state.
47124 **   Do nothing else with this cursor.  Any attempt to use the cursor
47125 **   should return the error code stored in BtCursor.skip
47126 */
47127 #define CURSOR_INVALID           0
47128 #define CURSOR_VALID             1
47129 #define CURSOR_REQUIRESEEK       2
47130 #define CURSOR_FAULT             3
47131
47132 /* 
47133 ** The database page the PENDING_BYTE occupies. This page is never used.
47134 */
47135 # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
47136
47137 /*
47138 ** These macros define the location of the pointer-map entry for a 
47139 ** database page. The first argument to each is the number of usable
47140 ** bytes on each page of the database (often 1024). The second is the
47141 ** page number to look up in the pointer map.
47142 **
47143 ** PTRMAP_PAGENO returns the database page number of the pointer-map
47144 ** page that stores the required pointer. PTRMAP_PTROFFSET returns
47145 ** the offset of the requested map entry.
47146 **
47147 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
47148 ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
47149 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
47150 ** this test.
47151 */
47152 #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
47153 #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
47154 #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
47155
47156 /*
47157 ** The pointer map is a lookup table that identifies the parent page for
47158 ** each child page in the database file.  The parent page is the page that
47159 ** contains a pointer to the child.  Every page in the database contains
47160 ** 0 or 1 parent pages.  (In this context 'database page' refers
47161 ** to any page that is not part of the pointer map itself.)  Each pointer map
47162 ** entry consists of a single byte 'type' and a 4 byte parent page number.
47163 ** The PTRMAP_XXX identifiers below are the valid types.
47164 **
47165 ** The purpose of the pointer map is to facility moving pages from one
47166 ** position in the file to another as part of autovacuum.  When a page
47167 ** is moved, the pointer in its parent must be updated to point to the
47168 ** new location.  The pointer map is used to locate the parent page quickly.
47169 **
47170 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
47171 **                  used in this case.
47172 **
47173 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number 
47174 **                  is not used in this case.
47175 **
47176 ** PTRMAP_OVERFLOW1: The database page is the first page in a list of 
47177 **                   overflow pages. The page number identifies the page that
47178 **                   contains the cell with a pointer to this overflow page.
47179 **
47180 ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
47181 **                   overflow pages. The page-number identifies the previous
47182 **                   page in the overflow page list.
47183 **
47184 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
47185 **               identifies the parent page in the btree.
47186 */
47187 #define PTRMAP_ROOTPAGE 1
47188 #define PTRMAP_FREEPAGE 2
47189 #define PTRMAP_OVERFLOW1 3
47190 #define PTRMAP_OVERFLOW2 4
47191 #define PTRMAP_BTREE 5
47192
47193 /* A bunch of assert() statements to check the transaction state variables
47194 ** of handle p (type Btree*) are internally consistent.
47195 */
47196 #define btreeIntegrity(p) \
47197   assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
47198   assert( p->pBt->inTransaction>=p->inTrans ); 
47199
47200
47201 /*
47202 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
47203 ** if the database supports auto-vacuum or not. Because it is used
47204 ** within an expression that is an argument to another macro 
47205 ** (sqliteMallocRaw), it is not possible to use conditional compilation.
47206 ** So, this macro is defined instead.
47207 */
47208 #ifndef SQLITE_OMIT_AUTOVACUUM
47209 #define ISAUTOVACUUM (pBt->autoVacuum)
47210 #else
47211 #define ISAUTOVACUUM 0
47212 #endif
47213
47214
47215 /*
47216 ** This structure is passed around through all the sanity checking routines
47217 ** in order to keep track of some global state information.
47218 */
47219 typedef struct IntegrityCk IntegrityCk;
47220 struct IntegrityCk {
47221   BtShared *pBt;    /* The tree being checked out */
47222   Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
47223   Pgno nPage;       /* Number of pages in the database */
47224   int *anRef;       /* Number of times each page is referenced */
47225   int mxErr;        /* Stop accumulating errors when this reaches zero */
47226   int nErr;         /* Number of messages written to zErrMsg so far */
47227   int mallocFailed; /* A memory allocation error has occurred */
47228   StrAccum errMsg;  /* Accumulate the error message text here */
47229 };
47230
47231 /*
47232 ** Read or write a two- and four-byte big-endian integer values.
47233 */
47234 #define get2byte(x)   ((x)[0]<<8 | (x)[1])
47235 #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
47236 #define get4byte sqlite3Get4byte
47237 #define put4byte sqlite3Put4byte
47238
47239 /************** End of btreeInt.h ********************************************/
47240 /************** Continuing where we left off in btmutex.c ********************/
47241 #ifndef SQLITE_OMIT_SHARED_CACHE
47242 #if SQLITE_THREADSAFE
47243
47244 /*
47245 ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
47246 ** set BtShared.db to the database handle associated with p and the
47247 ** p->locked boolean to true.
47248 */
47249 static void lockBtreeMutex(Btree *p){
47250   assert( p->locked==0 );
47251   assert( sqlite3_mutex_notheld(p->pBt->mutex) );
47252   assert( sqlite3_mutex_held(p->db->mutex) );
47253
47254   sqlite3_mutex_enter(p->pBt->mutex);
47255   p->pBt->db = p->db;
47256   p->locked = 1;
47257 }
47258
47259 /*
47260 ** Release the BtShared mutex associated with B-Tree handle p and
47261 ** clear the p->locked boolean.
47262 */
47263 static void unlockBtreeMutex(Btree *p){
47264   BtShared *pBt = p->pBt;
47265   assert( p->locked==1 );
47266   assert( sqlite3_mutex_held(pBt->mutex) );
47267   assert( sqlite3_mutex_held(p->db->mutex) );
47268   assert( p->db==pBt->db );
47269
47270   sqlite3_mutex_leave(pBt->mutex);
47271   p->locked = 0;
47272 }
47273
47274 /*
47275 ** Enter a mutex on the given BTree object.
47276 **
47277 ** If the object is not sharable, then no mutex is ever required
47278 ** and this routine is a no-op.  The underlying mutex is non-recursive.
47279 ** But we keep a reference count in Btree.wantToLock so the behavior
47280 ** of this interface is recursive.
47281 **
47282 ** To avoid deadlocks, multiple Btrees are locked in the same order
47283 ** by all database connections.  The p->pNext is a list of other
47284 ** Btrees belonging to the same database connection as the p Btree
47285 ** which need to be locked after p.  If we cannot get a lock on
47286 ** p, then first unlock all of the others on p->pNext, then wait
47287 ** for the lock to become available on p, then relock all of the
47288 ** subsequent Btrees that desire a lock.
47289 */
47290 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
47291   Btree *pLater;
47292
47293   /* Some basic sanity checking on the Btree.  The list of Btrees
47294   ** connected by pNext and pPrev should be in sorted order by
47295   ** Btree.pBt value. All elements of the list should belong to
47296   ** the same connection. Only shared Btrees are on the list. */
47297   assert( p->pNext==0 || p->pNext->pBt>p->pBt );
47298   assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
47299   assert( p->pNext==0 || p->pNext->db==p->db );
47300   assert( p->pPrev==0 || p->pPrev->db==p->db );
47301   assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
47302
47303   /* Check for locking consistency */
47304   assert( !p->locked || p->wantToLock>0 );
47305   assert( p->sharable || p->wantToLock==0 );
47306
47307   /* We should already hold a lock on the database connection */
47308   assert( sqlite3_mutex_held(p->db->mutex) );
47309
47310   /* Unless the database is sharable and unlocked, then BtShared.db
47311   ** should already be set correctly. */
47312   assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
47313
47314   if( !p->sharable ) return;
47315   p->wantToLock++;
47316   if( p->locked ) return;
47317
47318   /* In most cases, we should be able to acquire the lock we
47319   ** want without having to go throught the ascending lock
47320   ** procedure that follows.  Just be sure not to block.
47321   */
47322   if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
47323     p->pBt->db = p->db;
47324     p->locked = 1;
47325     return;
47326   }
47327
47328   /* To avoid deadlock, first release all locks with a larger
47329   ** BtShared address.  Then acquire our lock.  Then reacquire
47330   ** the other BtShared locks that we used to hold in ascending
47331   ** order.
47332   */
47333   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
47334     assert( pLater->sharable );
47335     assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
47336     assert( !pLater->locked || pLater->wantToLock>0 );
47337     if( pLater->locked ){
47338       unlockBtreeMutex(pLater);
47339     }
47340   }
47341   lockBtreeMutex(p);
47342   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
47343     if( pLater->wantToLock ){
47344       lockBtreeMutex(pLater);
47345     }
47346   }
47347 }
47348
47349 /*
47350 ** Exit the recursive mutex on a Btree.
47351 */
47352 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
47353   if( p->sharable ){
47354     assert( p->wantToLock>0 );
47355     p->wantToLock--;
47356     if( p->wantToLock==0 ){
47357       unlockBtreeMutex(p);
47358     }
47359   }
47360 }
47361
47362 #ifndef NDEBUG
47363 /*
47364 ** Return true if the BtShared mutex is held on the btree, or if the
47365 ** B-Tree is not marked as sharable.
47366 **
47367 ** This routine is used only from within assert() statements.
47368 */
47369 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
47370   assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
47371   assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
47372   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
47373   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
47374
47375   return (p->sharable==0 || p->locked);
47376 }
47377 #endif
47378
47379
47380 #ifndef SQLITE_OMIT_INCRBLOB
47381 /*
47382 ** Enter and leave a mutex on a Btree given a cursor owned by that
47383 ** Btree.  These entry points are used by incremental I/O and can be
47384 ** omitted if that module is not used.
47385 */
47386 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
47387   sqlite3BtreeEnter(pCur->pBtree);
47388 }
47389 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
47390   sqlite3BtreeLeave(pCur->pBtree);
47391 }
47392 #endif /* SQLITE_OMIT_INCRBLOB */
47393
47394
47395 /*
47396 ** Enter the mutex on every Btree associated with a database
47397 ** connection.  This is needed (for example) prior to parsing
47398 ** a statement since we will be comparing table and column names
47399 ** against all schemas and we do not want those schemas being
47400 ** reset out from under us.
47401 **
47402 ** There is a corresponding leave-all procedures.
47403 **
47404 ** Enter the mutexes in accending order by BtShared pointer address
47405 ** to avoid the possibility of deadlock when two threads with
47406 ** two or more btrees in common both try to lock all their btrees
47407 ** at the same instant.
47408 */
47409 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
47410   int i;
47411   Btree *p;
47412   assert( sqlite3_mutex_held(db->mutex) );
47413   for(i=0; i<db->nDb; i++){
47414     p = db->aDb[i].pBt;
47415     if( p ) sqlite3BtreeEnter(p);
47416   }
47417 }
47418 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
47419   int i;
47420   Btree *p;
47421   assert( sqlite3_mutex_held(db->mutex) );
47422   for(i=0; i<db->nDb; i++){
47423     p = db->aDb[i].pBt;
47424     if( p ) sqlite3BtreeLeave(p);
47425   }
47426 }
47427
47428 /*
47429 ** Return true if a particular Btree requires a lock.  Return FALSE if
47430 ** no lock is ever required since it is not sharable.
47431 */
47432 SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
47433   return p->sharable;
47434 }
47435
47436 #ifndef NDEBUG
47437 /*
47438 ** Return true if the current thread holds the database connection
47439 ** mutex and all required BtShared mutexes.
47440 **
47441 ** This routine is used inside assert() statements only.
47442 */
47443 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
47444   int i;
47445   if( !sqlite3_mutex_held(db->mutex) ){
47446     return 0;
47447   }
47448   for(i=0; i<db->nDb; i++){
47449     Btree *p;
47450     p = db->aDb[i].pBt;
47451     if( p && p->sharable &&
47452          (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
47453       return 0;
47454     }
47455   }
47456   return 1;
47457 }
47458 #endif /* NDEBUG */
47459
47460 #ifndef NDEBUG
47461 /*
47462 ** Return true if the correct mutexes are held for accessing the
47463 ** db->aDb[iDb].pSchema structure.  The mutexes required for schema
47464 ** access are:
47465 **
47466 **   (1) The mutex on db
47467 **   (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
47468 **
47469 ** If pSchema is not NULL, then iDb is computed from pSchema and
47470 ** db using sqlite3SchemaToIndex().
47471 */
47472 SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
47473   Btree *p;
47474   assert( db!=0 );
47475   if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
47476   assert( iDb>=0 && iDb<db->nDb );
47477   if( !sqlite3_mutex_held(db->mutex) ) return 0;
47478   if( iDb==1 ) return 1;
47479   p = db->aDb[iDb].pBt;
47480   assert( p!=0 );
47481   return p->sharable==0 || p->locked==1;
47482 }
47483 #endif /* NDEBUG */
47484
47485 #else /* SQLITE_THREADSAFE>0 above.  SQLITE_THREADSAFE==0 below */
47486 /*
47487 ** The following are special cases for mutex enter routines for use
47488 ** in single threaded applications that use shared cache.  Except for
47489 ** these two routines, all mutex operations are no-ops in that case and
47490 ** are null #defines in btree.h.
47491 **
47492 ** If shared cache is disabled, then all btree mutex routines, including
47493 ** the ones below, are no-ops and are null #defines in btree.h.
47494 */
47495
47496 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
47497   p->pBt->db = p->db;
47498 }
47499 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
47500   int i;
47501   for(i=0; i<db->nDb; i++){
47502     Btree *p = db->aDb[i].pBt;
47503     if( p ){
47504       p->pBt->db = p->db;
47505     }
47506   }
47507 }
47508 #endif /* if SQLITE_THREADSAFE */
47509 #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
47510
47511 /************** End of btmutex.c *********************************************/
47512 /************** Begin file btree.c *******************************************/
47513 /*
47514 ** 2004 April 6
47515 **
47516 ** The author disclaims copyright to this source code.  In place of
47517 ** a legal notice, here is a blessing:
47518 **
47519 **    May you do good and not evil.
47520 **    May you find forgiveness for yourself and forgive others.
47521 **    May you share freely, never taking more than you give.
47522 **
47523 *************************************************************************
47524 ** This file implements a external (disk-based) database using BTrees.
47525 ** See the header comment on "btreeInt.h" for additional information.
47526 ** Including a description of file format and an overview of operation.
47527 */
47528
47529 /*
47530 ** The header string that appears at the beginning of every
47531 ** SQLite database.
47532 */
47533 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
47534
47535 /*
47536 ** Set this global variable to 1 to enable tracing using the TRACE
47537 ** macro.
47538 */
47539 #if 0
47540 int sqlite3BtreeTrace=1;  /* True to enable tracing */
47541 # define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
47542 #else
47543 # define TRACE(X)
47544 #endif
47545
47546 /*
47547 ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
47548 ** But if the value is zero, make it 65536.
47549 **
47550 ** This routine is used to extract the "offset to cell content area" value
47551 ** from the header of a btree page.  If the page size is 65536 and the page
47552 ** is empty, the offset should be 65536, but the 2-byte value stores zero.
47553 ** This routine makes the necessary adjustment to 65536.
47554 */
47555 #define get2byteNotZero(X)  (((((int)get2byte(X))-1)&0xffff)+1)
47556
47557 #ifndef SQLITE_OMIT_SHARED_CACHE
47558 /*
47559 ** A list of BtShared objects that are eligible for participation
47560 ** in shared cache.  This variable has file scope during normal builds,
47561 ** but the test harness needs to access it so we make it global for 
47562 ** test builds.
47563 **
47564 ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
47565 */
47566 #ifdef SQLITE_TEST
47567 SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
47568 #else
47569 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
47570 #endif
47571 #endif /* SQLITE_OMIT_SHARED_CACHE */
47572
47573 #ifndef SQLITE_OMIT_SHARED_CACHE
47574 /*
47575 ** Enable or disable the shared pager and schema features.
47576 **
47577 ** This routine has no effect on existing database connections.
47578 ** The shared cache setting effects only future calls to
47579 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
47580 */
47581 SQLITE_API int sqlite3_enable_shared_cache(int enable){
47582   sqlite3GlobalConfig.sharedCacheEnabled = enable;
47583   return SQLITE_OK;
47584 }
47585 #endif
47586
47587
47588
47589 #ifdef SQLITE_OMIT_SHARED_CACHE
47590   /*
47591   ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
47592   ** and clearAllSharedCacheTableLocks()
47593   ** manipulate entries in the BtShared.pLock linked list used to store
47594   ** shared-cache table level locks. If the library is compiled with the
47595   ** shared-cache feature disabled, then there is only ever one user
47596   ** of each BtShared structure and so this locking is not necessary. 
47597   ** So define the lock related functions as no-ops.
47598   */
47599   #define querySharedCacheTableLock(a,b,c) SQLITE_OK
47600   #define setSharedCacheTableLock(a,b,c) SQLITE_OK
47601   #define clearAllSharedCacheTableLocks(a)
47602   #define downgradeAllSharedCacheTableLocks(a)
47603   #define hasSharedCacheTableLock(a,b,c,d) 1
47604   #define hasReadConflicts(a, b) 0
47605 #endif
47606
47607 #ifndef SQLITE_OMIT_SHARED_CACHE
47608
47609 #ifdef SQLITE_DEBUG
47610 /*
47611 **** This function is only used as part of an assert() statement. ***
47612 **
47613 ** Check to see if pBtree holds the required locks to read or write to the 
47614 ** table with root page iRoot.   Return 1 if it does and 0 if not.
47615 **
47616 ** For example, when writing to a table with root-page iRoot via 
47617 ** Btree connection pBtree:
47618 **
47619 **    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
47620 **
47621 ** When writing to an index that resides in a sharable database, the 
47622 ** caller should have first obtained a lock specifying the root page of
47623 ** the corresponding table. This makes things a bit more complicated,
47624 ** as this module treats each table as a separate structure. To determine
47625 ** the table corresponding to the index being written, this
47626 ** function has to search through the database schema.
47627 **
47628 ** Instead of a lock on the table/index rooted at page iRoot, the caller may
47629 ** hold a write-lock on the schema table (root page 1). This is also
47630 ** acceptable.
47631 */
47632 static int hasSharedCacheTableLock(
47633   Btree *pBtree,         /* Handle that must hold lock */
47634   Pgno iRoot,            /* Root page of b-tree */
47635   int isIndex,           /* True if iRoot is the root of an index b-tree */
47636   int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
47637 ){
47638   Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
47639   Pgno iTab = 0;
47640   BtLock *pLock;
47641
47642   /* If this database is not shareable, or if the client is reading
47643   ** and has the read-uncommitted flag set, then no lock is required. 
47644   ** Return true immediately.
47645   */
47646   if( (pBtree->sharable==0)
47647    || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
47648   ){
47649     return 1;
47650   }
47651
47652   /* If the client is reading  or writing an index and the schema is
47653   ** not loaded, then it is too difficult to actually check to see if
47654   ** the correct locks are held.  So do not bother - just return true.
47655   ** This case does not come up very often anyhow.
47656   */
47657   if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
47658     return 1;
47659   }
47660
47661   /* Figure out the root-page that the lock should be held on. For table
47662   ** b-trees, this is just the root page of the b-tree being read or
47663   ** written. For index b-trees, it is the root page of the associated
47664   ** table.  */
47665   if( isIndex ){
47666     HashElem *p;
47667     for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
47668       Index *pIdx = (Index *)sqliteHashData(p);
47669       if( pIdx->tnum==(int)iRoot ){
47670         iTab = pIdx->pTable->tnum;
47671       }
47672     }
47673   }else{
47674     iTab = iRoot;
47675   }
47676
47677   /* Search for the required lock. Either a write-lock on root-page iTab, a 
47678   ** write-lock on the schema table, or (if the client is reading) a
47679   ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
47680   for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
47681     if( pLock->pBtree==pBtree 
47682      && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
47683      && pLock->eLock>=eLockType 
47684     ){
47685       return 1;
47686     }
47687   }
47688
47689   /* Failed to find the required lock. */
47690   return 0;
47691 }
47692 #endif /* SQLITE_DEBUG */
47693
47694 #ifdef SQLITE_DEBUG
47695 /*
47696 **** This function may be used as part of assert() statements only. ****
47697 **
47698 ** Return true if it would be illegal for pBtree to write into the
47699 ** table or index rooted at iRoot because other shared connections are
47700 ** simultaneously reading that same table or index.
47701 **
47702 ** It is illegal for pBtree to write if some other Btree object that
47703 ** shares the same BtShared object is currently reading or writing
47704 ** the iRoot table.  Except, if the other Btree object has the
47705 ** read-uncommitted flag set, then it is OK for the other object to
47706 ** have a read cursor.
47707 **
47708 ** For example, before writing to any part of the table or index
47709 ** rooted at page iRoot, one should call:
47710 **
47711 **    assert( !hasReadConflicts(pBtree, iRoot) );
47712 */
47713 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
47714   BtCursor *p;
47715   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
47716     if( p->pgnoRoot==iRoot 
47717      && p->pBtree!=pBtree
47718      && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
47719     ){
47720       return 1;
47721     }
47722   }
47723   return 0;
47724 }
47725 #endif    /* #ifdef SQLITE_DEBUG */
47726
47727 /*
47728 ** Query to see if Btree handle p may obtain a lock of type eLock 
47729 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
47730 ** SQLITE_OK if the lock may be obtained (by calling
47731 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
47732 */
47733 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
47734   BtShared *pBt = p->pBt;
47735   BtLock *pIter;
47736
47737   assert( sqlite3BtreeHoldsMutex(p) );
47738   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
47739   assert( p->db!=0 );
47740   assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
47741   
47742   /* If requesting a write-lock, then the Btree must have an open write
47743   ** transaction on this file. And, obviously, for this to be so there 
47744   ** must be an open write transaction on the file itself.
47745   */
47746   assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
47747   assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
47748   
47749   /* This routine is a no-op if the shared-cache is not enabled */
47750   if( !p->sharable ){
47751     return SQLITE_OK;
47752   }
47753
47754   /* If some other connection is holding an exclusive lock, the
47755   ** requested lock may not be obtained.
47756   */
47757   if( pBt->pWriter!=p && pBt->isExclusive ){
47758     sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
47759     return SQLITE_LOCKED_SHAREDCACHE;
47760   }
47761
47762   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
47763     /* The condition (pIter->eLock!=eLock) in the following if(...) 
47764     ** statement is a simplification of:
47765     **
47766     **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
47767     **
47768     ** since we know that if eLock==WRITE_LOCK, then no other connection
47769     ** may hold a WRITE_LOCK on any table in this file (since there can
47770     ** only be a single writer).
47771     */
47772     assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
47773     assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
47774     if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
47775       sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
47776       if( eLock==WRITE_LOCK ){
47777         assert( p==pBt->pWriter );
47778         pBt->isPending = 1;
47779       }
47780       return SQLITE_LOCKED_SHAREDCACHE;
47781     }
47782   }
47783   return SQLITE_OK;
47784 }
47785 #endif /* !SQLITE_OMIT_SHARED_CACHE */
47786
47787 #ifndef SQLITE_OMIT_SHARED_CACHE
47788 /*
47789 ** Add a lock on the table with root-page iTable to the shared-btree used
47790 ** by Btree handle p. Parameter eLock must be either READ_LOCK or 
47791 ** WRITE_LOCK.
47792 **
47793 ** This function assumes the following:
47794 **
47795 **   (a) The specified Btree object p is connected to a sharable
47796 **       database (one with the BtShared.sharable flag set), and
47797 **
47798 **   (b) No other Btree objects hold a lock that conflicts
47799 **       with the requested lock (i.e. querySharedCacheTableLock() has
47800 **       already been called and returned SQLITE_OK).
47801 **
47802 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM 
47803 ** is returned if a malloc attempt fails.
47804 */
47805 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
47806   BtShared *pBt = p->pBt;
47807   BtLock *pLock = 0;
47808   BtLock *pIter;
47809
47810   assert( sqlite3BtreeHoldsMutex(p) );
47811   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
47812   assert( p->db!=0 );
47813
47814   /* A connection with the read-uncommitted flag set will never try to
47815   ** obtain a read-lock using this function. The only read-lock obtained
47816   ** by a connection in read-uncommitted mode is on the sqlite_master 
47817   ** table, and that lock is obtained in BtreeBeginTrans().  */
47818   assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
47819
47820   /* This function should only be called on a sharable b-tree after it 
47821   ** has been determined that no other b-tree holds a conflicting lock.  */
47822   assert( p->sharable );
47823   assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
47824
47825   /* First search the list for an existing lock on this table. */
47826   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
47827     if( pIter->iTable==iTable && pIter->pBtree==p ){
47828       pLock = pIter;
47829       break;
47830     }
47831   }
47832
47833   /* If the above search did not find a BtLock struct associating Btree p
47834   ** with table iTable, allocate one and link it into the list.
47835   */
47836   if( !pLock ){
47837     pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
47838     if( !pLock ){
47839       return SQLITE_NOMEM;
47840     }
47841     pLock->iTable = iTable;
47842     pLock->pBtree = p;
47843     pLock->pNext = pBt->pLock;
47844     pBt->pLock = pLock;
47845   }
47846
47847   /* Set the BtLock.eLock variable to the maximum of the current lock
47848   ** and the requested lock. This means if a write-lock was already held
47849   ** and a read-lock requested, we don't incorrectly downgrade the lock.
47850   */
47851   assert( WRITE_LOCK>READ_LOCK );
47852   if( eLock>pLock->eLock ){
47853     pLock->eLock = eLock;
47854   }
47855
47856   return SQLITE_OK;
47857 }
47858 #endif /* !SQLITE_OMIT_SHARED_CACHE */
47859
47860 #ifndef SQLITE_OMIT_SHARED_CACHE
47861 /*
47862 ** Release all the table locks (locks obtained via calls to
47863 ** the setSharedCacheTableLock() procedure) held by Btree object p.
47864 **
47865 ** This function assumes that Btree p has an open read or write 
47866 ** transaction. If it does not, then the BtShared.isPending variable
47867 ** may be incorrectly cleared.
47868 */
47869 static void clearAllSharedCacheTableLocks(Btree *p){
47870   BtShared *pBt = p->pBt;
47871   BtLock **ppIter = &pBt->pLock;
47872
47873   assert( sqlite3BtreeHoldsMutex(p) );
47874   assert( p->sharable || 0==*ppIter );
47875   assert( p->inTrans>0 );
47876
47877   while( *ppIter ){
47878     BtLock *pLock = *ppIter;
47879     assert( pBt->isExclusive==0 || pBt->pWriter==pLock->pBtree );
47880     assert( pLock->pBtree->inTrans>=pLock->eLock );
47881     if( pLock->pBtree==p ){
47882       *ppIter = pLock->pNext;
47883       assert( pLock->iTable!=1 || pLock==&p->lock );
47884       if( pLock->iTable!=1 ){
47885         sqlite3_free(pLock);
47886       }
47887     }else{
47888       ppIter = &pLock->pNext;
47889     }
47890   }
47891
47892   assert( pBt->isPending==0 || pBt->pWriter );
47893   if( pBt->pWriter==p ){
47894     pBt->pWriter = 0;
47895     pBt->isExclusive = 0;
47896     pBt->isPending = 0;
47897   }else if( pBt->nTransaction==2 ){
47898     /* This function is called when Btree p is concluding its 
47899     ** transaction. If there currently exists a writer, and p is not
47900     ** that writer, then the number of locks held by connections other
47901     ** than the writer must be about to drop to zero. In this case
47902     ** set the isPending flag to 0.
47903     **
47904     ** If there is not currently a writer, then BtShared.isPending must
47905     ** be zero already. So this next line is harmless in that case.
47906     */
47907     pBt->isPending = 0;
47908   }
47909 }
47910
47911 /*
47912 ** This function changes all write-locks held by Btree p into read-locks.
47913 */
47914 static void downgradeAllSharedCacheTableLocks(Btree *p){
47915   BtShared *pBt = p->pBt;
47916   if( pBt->pWriter==p ){
47917     BtLock *pLock;
47918     pBt->pWriter = 0;
47919     pBt->isExclusive = 0;
47920     pBt->isPending = 0;
47921     for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
47922       assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
47923       pLock->eLock = READ_LOCK;
47924     }
47925   }
47926 }
47927
47928 #endif /* SQLITE_OMIT_SHARED_CACHE */
47929
47930 static void releasePage(MemPage *pPage);  /* Forward reference */
47931
47932 /*
47933 ***** This routine is used inside of assert() only ****
47934 **
47935 ** Verify that the cursor holds the mutex on its BtShared
47936 */
47937 #ifdef SQLITE_DEBUG
47938 static int cursorHoldsMutex(BtCursor *p){
47939   return sqlite3_mutex_held(p->pBt->mutex);
47940 }
47941 #endif
47942
47943
47944 #ifndef SQLITE_OMIT_INCRBLOB
47945 /*
47946 ** Invalidate the overflow page-list cache for cursor pCur, if any.
47947 */
47948 static void invalidateOverflowCache(BtCursor *pCur){
47949   assert( cursorHoldsMutex(pCur) );
47950   sqlite3_free(pCur->aOverflow);
47951   pCur->aOverflow = 0;
47952 }
47953
47954 /*
47955 ** Invalidate the overflow page-list cache for all cursors opened
47956 ** on the shared btree structure pBt.
47957 */
47958 static void invalidateAllOverflowCache(BtShared *pBt){
47959   BtCursor *p;
47960   assert( sqlite3_mutex_held(pBt->mutex) );
47961   for(p=pBt->pCursor; p; p=p->pNext){
47962     invalidateOverflowCache(p);
47963   }
47964 }
47965
47966 /*
47967 ** This function is called before modifying the contents of a table
47968 ** to invalidate any incrblob cursors that are open on the
47969 ** row or one of the rows being modified.
47970 **
47971 ** If argument isClearTable is true, then the entire contents of the
47972 ** table is about to be deleted. In this case invalidate all incrblob
47973 ** cursors open on any row within the table with root-page pgnoRoot.
47974 **
47975 ** Otherwise, if argument isClearTable is false, then the row with
47976 ** rowid iRow is being replaced or deleted. In this case invalidate
47977 ** only those incrblob cursors open on that specific row.
47978 */
47979 static void invalidateIncrblobCursors(
47980   Btree *pBtree,          /* The database file to check */
47981   i64 iRow,               /* The rowid that might be changing */
47982   int isClearTable        /* True if all rows are being deleted */
47983 ){
47984   BtCursor *p;
47985   BtShared *pBt = pBtree->pBt;
47986   assert( sqlite3BtreeHoldsMutex(pBtree) );
47987   for(p=pBt->pCursor; p; p=p->pNext){
47988     if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
47989       p->eState = CURSOR_INVALID;
47990     }
47991   }
47992 }
47993
47994 #else
47995   /* Stub functions when INCRBLOB is omitted */
47996   #define invalidateOverflowCache(x)
47997   #define invalidateAllOverflowCache(x)
47998   #define invalidateIncrblobCursors(x,y,z)
47999 #endif /* SQLITE_OMIT_INCRBLOB */
48000
48001 /*
48002 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called 
48003 ** when a page that previously contained data becomes a free-list leaf 
48004 ** page.
48005 **
48006 ** The BtShared.pHasContent bitvec exists to work around an obscure
48007 ** bug caused by the interaction of two useful IO optimizations surrounding
48008 ** free-list leaf pages:
48009 **
48010 **   1) When all data is deleted from a page and the page becomes
48011 **      a free-list leaf page, the page is not written to the database
48012 **      (as free-list leaf pages contain no meaningful data). Sometimes
48013 **      such a page is not even journalled (as it will not be modified,
48014 **      why bother journalling it?).
48015 **
48016 **   2) When a free-list leaf page is reused, its content is not read
48017 **      from the database or written to the journal file (why should it
48018 **      be, if it is not at all meaningful?).
48019 **
48020 ** By themselves, these optimizations work fine and provide a handy
48021 ** performance boost to bulk delete or insert operations. However, if
48022 ** a page is moved to the free-list and then reused within the same
48023 ** transaction, a problem comes up. If the page is not journalled when
48024 ** it is moved to the free-list and it is also not journalled when it
48025 ** is extracted from the free-list and reused, then the original data
48026 ** may be lost. In the event of a rollback, it may not be possible
48027 ** to restore the database to its original configuration.
48028 **
48029 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is 
48030 ** moved to become a free-list leaf page, the corresponding bit is
48031 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
48032 ** optimization 2 above is omitted if the corresponding bit is already
48033 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
48034 ** at the end of every transaction.
48035 */
48036 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
48037   int rc = SQLITE_OK;
48038   if( !pBt->pHasContent ){
48039     assert( pgno<=pBt->nPage );
48040     pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
48041     if( !pBt->pHasContent ){
48042       rc = SQLITE_NOMEM;
48043     }
48044   }
48045   if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
48046     rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
48047   }
48048   return rc;
48049 }
48050
48051 /*
48052 ** Query the BtShared.pHasContent vector.
48053 **
48054 ** This function is called when a free-list leaf page is removed from the
48055 ** free-list for reuse. It returns false if it is safe to retrieve the
48056 ** page from the pager layer with the 'no-content' flag set. True otherwise.
48057 */
48058 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
48059   Bitvec *p = pBt->pHasContent;
48060   return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
48061 }
48062
48063 /*
48064 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
48065 ** invoked at the conclusion of each write-transaction.
48066 */
48067 static void btreeClearHasContent(BtShared *pBt){
48068   sqlite3BitvecDestroy(pBt->pHasContent);
48069   pBt->pHasContent = 0;
48070 }
48071
48072 /*
48073 ** Save the current cursor position in the variables BtCursor.nKey 
48074 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
48075 **
48076 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
48077 ** prior to calling this routine.  
48078 */
48079 static int saveCursorPosition(BtCursor *pCur){
48080   int rc;
48081
48082   assert( CURSOR_VALID==pCur->eState );
48083   assert( 0==pCur->pKey );
48084   assert( cursorHoldsMutex(pCur) );
48085
48086   rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
48087   assert( rc==SQLITE_OK );  /* KeySize() cannot fail */
48088
48089   /* If this is an intKey table, then the above call to BtreeKeySize()
48090   ** stores the integer key in pCur->nKey. In this case this value is
48091   ** all that is required. Otherwise, if pCur is not open on an intKey
48092   ** table, then malloc space for and store the pCur->nKey bytes of key 
48093   ** data.
48094   */
48095   if( 0==pCur->apPage[0]->intKey ){
48096     void *pKey = sqlite3Malloc( (int)pCur->nKey );
48097     if( pKey ){
48098       rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
48099       if( rc==SQLITE_OK ){
48100         pCur->pKey = pKey;
48101       }else{
48102         sqlite3_free(pKey);
48103       }
48104     }else{
48105       rc = SQLITE_NOMEM;
48106     }
48107   }
48108   assert( !pCur->apPage[0]->intKey || !pCur->pKey );
48109
48110   if( rc==SQLITE_OK ){
48111     int i;
48112     for(i=0; i<=pCur->iPage; i++){
48113       releasePage(pCur->apPage[i]);
48114       pCur->apPage[i] = 0;
48115     }
48116     pCur->iPage = -1;
48117     pCur->eState = CURSOR_REQUIRESEEK;
48118   }
48119
48120   invalidateOverflowCache(pCur);
48121   return rc;
48122 }
48123
48124 /*
48125 ** Save the positions of all cursors (except pExcept) that are open on
48126 ** the table  with root-page iRoot. Usually, this is called just before cursor
48127 ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
48128 */
48129 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
48130   BtCursor *p;
48131   assert( sqlite3_mutex_held(pBt->mutex) );
48132   assert( pExcept==0 || pExcept->pBt==pBt );
48133   for(p=pBt->pCursor; p; p=p->pNext){
48134     if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) && 
48135         p->eState==CURSOR_VALID ){
48136       int rc = saveCursorPosition(p);
48137       if( SQLITE_OK!=rc ){
48138         return rc;
48139       }
48140     }
48141   }
48142   return SQLITE_OK;
48143 }
48144
48145 /*
48146 ** Clear the current cursor position.
48147 */
48148 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
48149   assert( cursorHoldsMutex(pCur) );
48150   sqlite3_free(pCur->pKey);
48151   pCur->pKey = 0;
48152   pCur->eState = CURSOR_INVALID;
48153 }
48154
48155 /*
48156 ** In this version of BtreeMoveto, pKey is a packed index record
48157 ** such as is generated by the OP_MakeRecord opcode.  Unpack the
48158 ** record and then call BtreeMovetoUnpacked() to do the work.
48159 */
48160 static int btreeMoveto(
48161   BtCursor *pCur,     /* Cursor open on the btree to be searched */
48162   const void *pKey,   /* Packed key if the btree is an index */
48163   i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
48164   int bias,           /* Bias search to the high end */
48165   int *pRes           /* Write search results here */
48166 ){
48167   int rc;                    /* Status code */
48168   UnpackedRecord *pIdxKey;   /* Unpacked index key */
48169   char aSpace[150];          /* Temp space for pIdxKey - to avoid a malloc */
48170
48171   if( pKey ){
48172     assert( nKey==(i64)(int)nKey );
48173     pIdxKey = sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey,
48174                                       aSpace, sizeof(aSpace));
48175     if( pIdxKey==0 ) return SQLITE_NOMEM;
48176   }else{
48177     pIdxKey = 0;
48178   }
48179   rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
48180   if( pKey ){
48181     sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
48182   }
48183   return rc;
48184 }
48185
48186 /*
48187 ** Restore the cursor to the position it was in (or as close to as possible)
48188 ** when saveCursorPosition() was called. Note that this call deletes the 
48189 ** saved position info stored by saveCursorPosition(), so there can be
48190 ** at most one effective restoreCursorPosition() call after each 
48191 ** saveCursorPosition().
48192 */
48193 static int btreeRestoreCursorPosition(BtCursor *pCur){
48194   int rc;
48195   assert( cursorHoldsMutex(pCur) );
48196   assert( pCur->eState>=CURSOR_REQUIRESEEK );
48197   if( pCur->eState==CURSOR_FAULT ){
48198     return pCur->skipNext;
48199   }
48200   pCur->eState = CURSOR_INVALID;
48201   rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
48202   if( rc==SQLITE_OK ){
48203     sqlite3_free(pCur->pKey);
48204     pCur->pKey = 0;
48205     assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
48206   }
48207   return rc;
48208 }
48209
48210 #define restoreCursorPosition(p) \
48211   (p->eState>=CURSOR_REQUIRESEEK ? \
48212          btreeRestoreCursorPosition(p) : \
48213          SQLITE_OK)
48214
48215 /*
48216 ** Determine whether or not a cursor has moved from the position it
48217 ** was last placed at.  Cursors can move when the row they are pointing
48218 ** at is deleted out from under them.
48219 **
48220 ** This routine returns an error code if something goes wrong.  The
48221 ** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
48222 */
48223 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
48224   int rc;
48225
48226   rc = restoreCursorPosition(pCur);
48227   if( rc ){
48228     *pHasMoved = 1;
48229     return rc;
48230   }
48231   if( pCur->eState!=CURSOR_VALID || pCur->skipNext!=0 ){
48232     *pHasMoved = 1;
48233   }else{
48234     *pHasMoved = 0;
48235   }
48236   return SQLITE_OK;
48237 }
48238
48239 #ifndef SQLITE_OMIT_AUTOVACUUM
48240 /*
48241 ** Given a page number of a regular database page, return the page
48242 ** number for the pointer-map page that contains the entry for the
48243 ** input page number.
48244 **
48245 ** Return 0 (not a valid page) for pgno==1 since there is
48246 ** no pointer map associated with page 1.  The integrity_check logic
48247 ** requires that ptrmapPageno(*,1)!=1.
48248 */
48249 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
48250   int nPagesPerMapPage;
48251   Pgno iPtrMap, ret;
48252   assert( sqlite3_mutex_held(pBt->mutex) );
48253   if( pgno<2 ) return 0;
48254   nPagesPerMapPage = (pBt->usableSize/5)+1;
48255   iPtrMap = (pgno-2)/nPagesPerMapPage;
48256   ret = (iPtrMap*nPagesPerMapPage) + 2; 
48257   if( ret==PENDING_BYTE_PAGE(pBt) ){
48258     ret++;
48259   }
48260   return ret;
48261 }
48262
48263 /*
48264 ** Write an entry into the pointer map.
48265 **
48266 ** This routine updates the pointer map entry for page number 'key'
48267 ** so that it maps to type 'eType' and parent page number 'pgno'.
48268 **
48269 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
48270 ** a no-op.  If an error occurs, the appropriate error code is written
48271 ** into *pRC.
48272 */
48273 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
48274   DbPage *pDbPage;  /* The pointer map page */
48275   u8 *pPtrmap;      /* The pointer map data */
48276   Pgno iPtrmap;     /* The pointer map page number */
48277   int offset;       /* Offset in pointer map page */
48278   int rc;           /* Return code from subfunctions */
48279
48280   if( *pRC ) return;
48281
48282   assert( sqlite3_mutex_held(pBt->mutex) );
48283   /* The master-journal page number must never be used as a pointer map page */
48284   assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
48285
48286   assert( pBt->autoVacuum );
48287   if( key==0 ){
48288     *pRC = SQLITE_CORRUPT_BKPT;
48289     return;
48290   }
48291   iPtrmap = PTRMAP_PAGENO(pBt, key);
48292   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
48293   if( rc!=SQLITE_OK ){
48294     *pRC = rc;
48295     return;
48296   }
48297   offset = PTRMAP_PTROFFSET(iPtrmap, key);
48298   if( offset<0 ){
48299     *pRC = SQLITE_CORRUPT_BKPT;
48300     goto ptrmap_exit;
48301   }
48302   assert( offset <= (int)pBt->usableSize-5 );
48303   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
48304
48305   if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
48306     TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
48307     *pRC= rc = sqlite3PagerWrite(pDbPage);
48308     if( rc==SQLITE_OK ){
48309       pPtrmap[offset] = eType;
48310       put4byte(&pPtrmap[offset+1], parent);
48311     }
48312   }
48313
48314 ptrmap_exit:
48315   sqlite3PagerUnref(pDbPage);
48316 }
48317
48318 /*
48319 ** Read an entry from the pointer map.
48320 **
48321 ** This routine retrieves the pointer map entry for page 'key', writing
48322 ** the type and parent page number to *pEType and *pPgno respectively.
48323 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
48324 */
48325 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
48326   DbPage *pDbPage;   /* The pointer map page */
48327   int iPtrmap;       /* Pointer map page index */
48328   u8 *pPtrmap;       /* Pointer map page data */
48329   int offset;        /* Offset of entry in pointer map */
48330   int rc;
48331
48332   assert( sqlite3_mutex_held(pBt->mutex) );
48333
48334   iPtrmap = PTRMAP_PAGENO(pBt, key);
48335   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
48336   if( rc!=0 ){
48337     return rc;
48338   }
48339   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
48340
48341   offset = PTRMAP_PTROFFSET(iPtrmap, key);
48342   if( offset<0 ){
48343     sqlite3PagerUnref(pDbPage);
48344     return SQLITE_CORRUPT_BKPT;
48345   }
48346   assert( offset <= (int)pBt->usableSize-5 );
48347   assert( pEType!=0 );
48348   *pEType = pPtrmap[offset];
48349   if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
48350
48351   sqlite3PagerUnref(pDbPage);
48352   if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
48353   return SQLITE_OK;
48354 }
48355
48356 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
48357   #define ptrmapPut(w,x,y,z,rc)
48358   #define ptrmapGet(w,x,y,z) SQLITE_OK
48359   #define ptrmapPutOvflPtr(x, y, rc)
48360 #endif
48361
48362 /*
48363 ** Given a btree page and a cell index (0 means the first cell on
48364 ** the page, 1 means the second cell, and so forth) return a pointer
48365 ** to the cell content.
48366 **
48367 ** This routine works only for pages that do not contain overflow cells.
48368 */
48369 #define findCell(P,I) \
48370   ((P)->aData + ((P)->maskPage & get2byte(&(P)->aData[(P)->cellOffset+2*(I)])))
48371 #define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I)))))
48372
48373
48374 /*
48375 ** This a more complex version of findCell() that works for
48376 ** pages that do contain overflow cells.
48377 */
48378 static u8 *findOverflowCell(MemPage *pPage, int iCell){
48379   int i;
48380   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48381   for(i=pPage->nOverflow-1; i>=0; i--){
48382     int k;
48383     struct _OvflCell *pOvfl;
48384     pOvfl = &pPage->aOvfl[i];
48385     k = pOvfl->idx;
48386     if( k<=iCell ){
48387       if( k==iCell ){
48388         return pOvfl->pCell;
48389       }
48390       iCell--;
48391     }
48392   }
48393   return findCell(pPage, iCell);
48394 }
48395
48396 /*
48397 ** Parse a cell content block and fill in the CellInfo structure.  There
48398 ** are two versions of this function.  btreeParseCell() takes a 
48399 ** cell index as the second argument and btreeParseCellPtr() 
48400 ** takes a pointer to the body of the cell as its second argument.
48401 **
48402 ** Within this file, the parseCell() macro can be called instead of
48403 ** btreeParseCellPtr(). Using some compilers, this will be faster.
48404 */
48405 static void btreeParseCellPtr(
48406   MemPage *pPage,         /* Page containing the cell */
48407   u8 *pCell,              /* Pointer to the cell text. */
48408   CellInfo *pInfo         /* Fill in this structure */
48409 ){
48410   u16 n;                  /* Number bytes in cell content header */
48411   u32 nPayload;           /* Number of bytes of cell payload */
48412
48413   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48414
48415   pInfo->pCell = pCell;
48416   assert( pPage->leaf==0 || pPage->leaf==1 );
48417   n = pPage->childPtrSize;
48418   assert( n==4-4*pPage->leaf );
48419   if( pPage->intKey ){
48420     if( pPage->hasData ){
48421       n += getVarint32(&pCell[n], nPayload);
48422     }else{
48423       nPayload = 0;
48424     }
48425     n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
48426     pInfo->nData = nPayload;
48427   }else{
48428     pInfo->nData = 0;
48429     n += getVarint32(&pCell[n], nPayload);
48430     pInfo->nKey = nPayload;
48431   }
48432   pInfo->nPayload = nPayload;
48433   pInfo->nHeader = n;
48434   testcase( nPayload==pPage->maxLocal );
48435   testcase( nPayload==pPage->maxLocal+1 );
48436   if( likely(nPayload<=pPage->maxLocal) ){
48437     /* This is the (easy) common case where the entire payload fits
48438     ** on the local page.  No overflow is required.
48439     */
48440     if( (pInfo->nSize = (u16)(n+nPayload))<4 ) pInfo->nSize = 4;
48441     pInfo->nLocal = (u16)nPayload;
48442     pInfo->iOverflow = 0;
48443   }else{
48444     /* If the payload will not fit completely on the local page, we have
48445     ** to decide how much to store locally and how much to spill onto
48446     ** overflow pages.  The strategy is to minimize the amount of unused
48447     ** space on overflow pages while keeping the amount of local storage
48448     ** in between minLocal and maxLocal.
48449     **
48450     ** Warning:  changing the way overflow payload is distributed in any
48451     ** way will result in an incompatible file format.
48452     */
48453     int minLocal;  /* Minimum amount of payload held locally */
48454     int maxLocal;  /* Maximum amount of payload held locally */
48455     int surplus;   /* Overflow payload available for local storage */
48456
48457     minLocal = pPage->minLocal;
48458     maxLocal = pPage->maxLocal;
48459     surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
48460     testcase( surplus==maxLocal );
48461     testcase( surplus==maxLocal+1 );
48462     if( surplus <= maxLocal ){
48463       pInfo->nLocal = (u16)surplus;
48464     }else{
48465       pInfo->nLocal = (u16)minLocal;
48466     }
48467     pInfo->iOverflow = (u16)(pInfo->nLocal + n);
48468     pInfo->nSize = pInfo->iOverflow + 4;
48469   }
48470 }
48471 #define parseCell(pPage, iCell, pInfo) \
48472   btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
48473 static void btreeParseCell(
48474   MemPage *pPage,         /* Page containing the cell */
48475   int iCell,              /* The cell index.  First cell is 0 */
48476   CellInfo *pInfo         /* Fill in this structure */
48477 ){
48478   parseCell(pPage, iCell, pInfo);
48479 }
48480
48481 /*
48482 ** Compute the total number of bytes that a Cell needs in the cell
48483 ** data area of the btree-page.  The return number includes the cell
48484 ** data header and the local payload, but not any overflow page or
48485 ** the space used by the cell pointer.
48486 */
48487 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
48488   u8 *pIter = &pCell[pPage->childPtrSize];
48489   u32 nSize;
48490
48491 #ifdef SQLITE_DEBUG
48492   /* The value returned by this function should always be the same as
48493   ** the (CellInfo.nSize) value found by doing a full parse of the
48494   ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
48495   ** this function verifies that this invariant is not violated. */
48496   CellInfo debuginfo;
48497   btreeParseCellPtr(pPage, pCell, &debuginfo);
48498 #endif
48499
48500   if( pPage->intKey ){
48501     u8 *pEnd;
48502     if( pPage->hasData ){
48503       pIter += getVarint32(pIter, nSize);
48504     }else{
48505       nSize = 0;
48506     }
48507
48508     /* pIter now points at the 64-bit integer key value, a variable length 
48509     ** integer. The following block moves pIter to point at the first byte
48510     ** past the end of the key value. */
48511     pEnd = &pIter[9];
48512     while( (*pIter++)&0x80 && pIter<pEnd );
48513   }else{
48514     pIter += getVarint32(pIter, nSize);
48515   }
48516
48517   testcase( nSize==pPage->maxLocal );
48518   testcase( nSize==pPage->maxLocal+1 );
48519   if( nSize>pPage->maxLocal ){
48520     int minLocal = pPage->minLocal;
48521     nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
48522     testcase( nSize==pPage->maxLocal );
48523     testcase( nSize==pPage->maxLocal+1 );
48524     if( nSize>pPage->maxLocal ){
48525       nSize = minLocal;
48526     }
48527     nSize += 4;
48528   }
48529   nSize += (u32)(pIter - pCell);
48530
48531   /* The minimum size of any cell is 4 bytes. */
48532   if( nSize<4 ){
48533     nSize = 4;
48534   }
48535
48536   assert( nSize==debuginfo.nSize );
48537   return (u16)nSize;
48538 }
48539
48540 #ifdef SQLITE_DEBUG
48541 /* This variation on cellSizePtr() is used inside of assert() statements
48542 ** only. */
48543 static u16 cellSize(MemPage *pPage, int iCell){
48544   return cellSizePtr(pPage, findCell(pPage, iCell));
48545 }
48546 #endif
48547
48548 #ifndef SQLITE_OMIT_AUTOVACUUM
48549 /*
48550 ** If the cell pCell, part of page pPage contains a pointer
48551 ** to an overflow page, insert an entry into the pointer-map
48552 ** for the overflow page.
48553 */
48554 static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
48555   CellInfo info;
48556   if( *pRC ) return;
48557   assert( pCell!=0 );
48558   btreeParseCellPtr(pPage, pCell, &info);
48559   assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
48560   if( info.iOverflow ){
48561     Pgno ovfl = get4byte(&pCell[info.iOverflow]);
48562     ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
48563   }
48564 }
48565 #endif
48566
48567
48568 /*
48569 ** Defragment the page given.  All Cells are moved to the
48570 ** end of the page and all free space is collected into one
48571 ** big FreeBlk that occurs in between the header and cell
48572 ** pointer array and the cell content area.
48573 */
48574 static int defragmentPage(MemPage *pPage){
48575   int i;                     /* Loop counter */
48576   int pc;                    /* Address of a i-th cell */
48577   int hdr;                   /* Offset to the page header */
48578   int size;                  /* Size of a cell */
48579   int usableSize;            /* Number of usable bytes on a page */
48580   int cellOffset;            /* Offset to the cell pointer array */
48581   int cbrk;                  /* Offset to the cell content area */
48582   int nCell;                 /* Number of cells on the page */
48583   unsigned char *data;       /* The page data */
48584   unsigned char *temp;       /* Temp area for cell content */
48585   int iCellFirst;            /* First allowable cell index */
48586   int iCellLast;             /* Last possible cell index */
48587
48588
48589   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
48590   assert( pPage->pBt!=0 );
48591   assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
48592   assert( pPage->nOverflow==0 );
48593   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48594   temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
48595   data = pPage->aData;
48596   hdr = pPage->hdrOffset;
48597   cellOffset = pPage->cellOffset;
48598   nCell = pPage->nCell;
48599   assert( nCell==get2byte(&data[hdr+3]) );
48600   usableSize = pPage->pBt->usableSize;
48601   cbrk = get2byte(&data[hdr+5]);
48602   memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
48603   cbrk = usableSize;
48604   iCellFirst = cellOffset + 2*nCell;
48605   iCellLast = usableSize - 4;
48606   for(i=0; i<nCell; i++){
48607     u8 *pAddr;     /* The i-th cell pointer */
48608     pAddr = &data[cellOffset + i*2];
48609     pc = get2byte(pAddr);
48610     testcase( pc==iCellFirst );
48611     testcase( pc==iCellLast );
48612 #if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
48613     /* These conditions have already been verified in btreeInitPage()
48614     ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined 
48615     */
48616     if( pc<iCellFirst || pc>iCellLast ){
48617       return SQLITE_CORRUPT_BKPT;
48618     }
48619 #endif
48620     assert( pc>=iCellFirst && pc<=iCellLast );
48621     size = cellSizePtr(pPage, &temp[pc]);
48622     cbrk -= size;
48623 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
48624     if( cbrk<iCellFirst ){
48625       return SQLITE_CORRUPT_BKPT;
48626     }
48627 #else
48628     if( cbrk<iCellFirst || pc+size>usableSize ){
48629       return SQLITE_CORRUPT_BKPT;
48630     }
48631 #endif
48632     assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
48633     testcase( cbrk+size==usableSize );
48634     testcase( pc+size==usableSize );
48635     memcpy(&data[cbrk], &temp[pc], size);
48636     put2byte(pAddr, cbrk);
48637   }
48638   assert( cbrk>=iCellFirst );
48639   put2byte(&data[hdr+5], cbrk);
48640   data[hdr+1] = 0;
48641   data[hdr+2] = 0;
48642   data[hdr+7] = 0;
48643   memset(&data[iCellFirst], 0, cbrk-iCellFirst);
48644   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
48645   if( cbrk-iCellFirst!=pPage->nFree ){
48646     return SQLITE_CORRUPT_BKPT;
48647   }
48648   return SQLITE_OK;
48649 }
48650
48651 /*
48652 ** Allocate nByte bytes of space from within the B-Tree page passed
48653 ** as the first argument. Write into *pIdx the index into pPage->aData[]
48654 ** of the first byte of allocated space. Return either SQLITE_OK or
48655 ** an error code (usually SQLITE_CORRUPT).
48656 **
48657 ** The caller guarantees that there is sufficient space to make the
48658 ** allocation.  This routine might need to defragment in order to bring
48659 ** all the space together, however.  This routine will avoid using
48660 ** the first two bytes past the cell pointer area since presumably this
48661 ** allocation is being made in order to insert a new cell, so we will
48662 ** also end up needing a new cell pointer.
48663 */
48664 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
48665   const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
48666   u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
48667   int nFrag;                           /* Number of fragmented bytes on pPage */
48668   int top;                             /* First byte of cell content area */
48669   int gap;        /* First byte of gap between cell pointers and cell content */
48670   int rc;         /* Integer return code */
48671   int usableSize; /* Usable size of the page */
48672   
48673   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
48674   assert( pPage->pBt );
48675   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48676   assert( nByte>=0 );  /* Minimum cell size is 4 */
48677   assert( pPage->nFree>=nByte );
48678   assert( pPage->nOverflow==0 );
48679   usableSize = pPage->pBt->usableSize;
48680   assert( nByte < usableSize-8 );
48681
48682   nFrag = data[hdr+7];
48683   assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
48684   gap = pPage->cellOffset + 2*pPage->nCell;
48685   top = get2byteNotZero(&data[hdr+5]);
48686   if( gap>top ) return SQLITE_CORRUPT_BKPT;
48687   testcase( gap+2==top );
48688   testcase( gap+1==top );
48689   testcase( gap==top );
48690
48691   if( nFrag>=60 ){
48692     /* Always defragment highly fragmented pages */
48693     rc = defragmentPage(pPage);
48694     if( rc ) return rc;
48695     top = get2byteNotZero(&data[hdr+5]);
48696   }else if( gap+2<=top ){
48697     /* Search the freelist looking for a free slot big enough to satisfy 
48698     ** the request. The allocation is made from the first free slot in 
48699     ** the list that is large enough to accomadate it.
48700     */
48701     int pc, addr;
48702     for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
48703       int size;            /* Size of the free slot */
48704       if( pc>usableSize-4 || pc<addr+4 ){
48705         return SQLITE_CORRUPT_BKPT;
48706       }
48707       size = get2byte(&data[pc+2]);
48708       if( size>=nByte ){
48709         int x = size - nByte;
48710         testcase( x==4 );
48711         testcase( x==3 );
48712         if( x<4 ){
48713           /* Remove the slot from the free-list. Update the number of
48714           ** fragmented bytes within the page. */
48715           memcpy(&data[addr], &data[pc], 2);
48716           data[hdr+7] = (u8)(nFrag + x);
48717         }else if( size+pc > usableSize ){
48718           return SQLITE_CORRUPT_BKPT;
48719         }else{
48720           /* The slot remains on the free-list. Reduce its size to account
48721           ** for the portion used by the new allocation. */
48722           put2byte(&data[pc+2], x);
48723         }
48724         *pIdx = pc + x;
48725         return SQLITE_OK;
48726       }
48727     }
48728   }
48729
48730   /* Check to make sure there is enough space in the gap to satisfy
48731   ** the allocation.  If not, defragment.
48732   */
48733   testcase( gap+2+nByte==top );
48734   if( gap+2+nByte>top ){
48735     rc = defragmentPage(pPage);
48736     if( rc ) return rc;
48737     top = get2byteNotZero(&data[hdr+5]);
48738     assert( gap+nByte<=top );
48739   }
48740
48741
48742   /* Allocate memory from the gap in between the cell pointer array
48743   ** and the cell content area.  The btreeInitPage() call has already
48744   ** validated the freelist.  Given that the freelist is valid, there
48745   ** is no way that the allocation can extend off the end of the page.
48746   ** The assert() below verifies the previous sentence.
48747   */
48748   top -= nByte;
48749   put2byte(&data[hdr+5], top);
48750   assert( top+nByte <= (int)pPage->pBt->usableSize );
48751   *pIdx = top;
48752   return SQLITE_OK;
48753 }
48754
48755 /*
48756 ** Return a section of the pPage->aData to the freelist.
48757 ** The first byte of the new free block is pPage->aDisk[start]
48758 ** and the size of the block is "size" bytes.
48759 **
48760 ** Most of the effort here is involved in coalesing adjacent
48761 ** free blocks into a single big free block.
48762 */
48763 static int freeSpace(MemPage *pPage, int start, int size){
48764   int addr, pbegin, hdr;
48765   int iLast;                        /* Largest possible freeblock offset */
48766   unsigned char *data = pPage->aData;
48767
48768   assert( pPage->pBt!=0 );
48769   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
48770   assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
48771   assert( (start + size) <= (int)pPage->pBt->usableSize );
48772   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48773   assert( size>=0 );   /* Minimum cell size is 4 */
48774
48775   if( pPage->pBt->secureDelete ){
48776     /* Overwrite deleted information with zeros when the secure_delete
48777     ** option is enabled */
48778     memset(&data[start], 0, size);
48779   }
48780
48781   /* Add the space back into the linked list of freeblocks.  Note that
48782   ** even though the freeblock list was checked by btreeInitPage(),
48783   ** btreeInitPage() did not detect overlapping cells or
48784   ** freeblocks that overlapped cells.   Nor does it detect when the
48785   ** cell content area exceeds the value in the page header.  If these
48786   ** situations arise, then subsequent insert operations might corrupt
48787   ** the freelist.  So we do need to check for corruption while scanning
48788   ** the freelist.
48789   */
48790   hdr = pPage->hdrOffset;
48791   addr = hdr + 1;
48792   iLast = pPage->pBt->usableSize - 4;
48793   assert( start<=iLast );
48794   while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
48795     if( pbegin<addr+4 ){
48796       return SQLITE_CORRUPT_BKPT;
48797     }
48798     addr = pbegin;
48799   }
48800   if( pbegin>iLast ){
48801     return SQLITE_CORRUPT_BKPT;
48802   }
48803   assert( pbegin>addr || pbegin==0 );
48804   put2byte(&data[addr], start);
48805   put2byte(&data[start], pbegin);
48806   put2byte(&data[start+2], size);
48807   pPage->nFree = pPage->nFree + (u16)size;
48808
48809   /* Coalesce adjacent free blocks */
48810   addr = hdr + 1;
48811   while( (pbegin = get2byte(&data[addr]))>0 ){
48812     int pnext, psize, x;
48813     assert( pbegin>addr );
48814     assert( pbegin <= (int)pPage->pBt->usableSize-4 );
48815     pnext = get2byte(&data[pbegin]);
48816     psize = get2byte(&data[pbegin+2]);
48817     if( pbegin + psize + 3 >= pnext && pnext>0 ){
48818       int frag = pnext - (pbegin+psize);
48819       if( (frag<0) || (frag>(int)data[hdr+7]) ){
48820         return SQLITE_CORRUPT_BKPT;
48821       }
48822       data[hdr+7] -= (u8)frag;
48823       x = get2byte(&data[pnext]);
48824       put2byte(&data[pbegin], x);
48825       x = pnext + get2byte(&data[pnext+2]) - pbegin;
48826       put2byte(&data[pbegin+2], x);
48827     }else{
48828       addr = pbegin;
48829     }
48830   }
48831
48832   /* If the cell content area begins with a freeblock, remove it. */
48833   if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
48834     int top;
48835     pbegin = get2byte(&data[hdr+1]);
48836     memcpy(&data[hdr+1], &data[pbegin], 2);
48837     top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
48838     put2byte(&data[hdr+5], top);
48839   }
48840   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
48841   return SQLITE_OK;
48842 }
48843
48844 /*
48845 ** Decode the flags byte (the first byte of the header) for a page
48846 ** and initialize fields of the MemPage structure accordingly.
48847 **
48848 ** Only the following combinations are supported.  Anything different
48849 ** indicates a corrupt database files:
48850 **
48851 **         PTF_ZERODATA
48852 **         PTF_ZERODATA | PTF_LEAF
48853 **         PTF_LEAFDATA | PTF_INTKEY
48854 **         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
48855 */
48856 static int decodeFlags(MemPage *pPage, int flagByte){
48857   BtShared *pBt;     /* A copy of pPage->pBt */
48858
48859   assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
48860   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48861   pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
48862   flagByte &= ~PTF_LEAF;
48863   pPage->childPtrSize = 4-4*pPage->leaf;
48864   pBt = pPage->pBt;
48865   if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
48866     pPage->intKey = 1;
48867     pPage->hasData = pPage->leaf;
48868     pPage->maxLocal = pBt->maxLeaf;
48869     pPage->minLocal = pBt->minLeaf;
48870   }else if( flagByte==PTF_ZERODATA ){
48871     pPage->intKey = 0;
48872     pPage->hasData = 0;
48873     pPage->maxLocal = pBt->maxLocal;
48874     pPage->minLocal = pBt->minLocal;
48875   }else{
48876     return SQLITE_CORRUPT_BKPT;
48877   }
48878   return SQLITE_OK;
48879 }
48880
48881 /*
48882 ** Initialize the auxiliary information for a disk block.
48883 **
48884 ** Return SQLITE_OK on success.  If we see that the page does
48885 ** not contain a well-formed database page, then return 
48886 ** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
48887 ** guarantee that the page is well-formed.  It only shows that
48888 ** we failed to detect any corruption.
48889 */
48890 static int btreeInitPage(MemPage *pPage){
48891
48892   assert( pPage->pBt!=0 );
48893   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
48894   assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
48895   assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
48896   assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
48897
48898   if( !pPage->isInit ){
48899     u16 pc;            /* Address of a freeblock within pPage->aData[] */
48900     u8 hdr;            /* Offset to beginning of page header */
48901     u8 *data;          /* Equal to pPage->aData */
48902     BtShared *pBt;        /* The main btree structure */
48903     int usableSize;    /* Amount of usable space on each page */
48904     u16 cellOffset;    /* Offset from start of page to first cell pointer */
48905     int nFree;         /* Number of unused bytes on the page */
48906     int top;           /* First byte of the cell content area */
48907     int iCellFirst;    /* First allowable cell or freeblock offset */
48908     int iCellLast;     /* Last possible cell or freeblock offset */
48909
48910     pBt = pPage->pBt;
48911
48912     hdr = pPage->hdrOffset;
48913     data = pPage->aData;
48914     if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
48915     assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
48916     pPage->maskPage = (u16)(pBt->pageSize - 1);
48917     pPage->nOverflow = 0;
48918     usableSize = pBt->usableSize;
48919     pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
48920     top = get2byteNotZero(&data[hdr+5]);
48921     pPage->nCell = get2byte(&data[hdr+3]);
48922     if( pPage->nCell>MX_CELL(pBt) ){
48923       /* To many cells for a single page.  The page must be corrupt */
48924       return SQLITE_CORRUPT_BKPT;
48925     }
48926     testcase( pPage->nCell==MX_CELL(pBt) );
48927
48928     /* A malformed database page might cause us to read past the end
48929     ** of page when parsing a cell.  
48930     **
48931     ** The following block of code checks early to see if a cell extends
48932     ** past the end of a page boundary and causes SQLITE_CORRUPT to be 
48933     ** returned if it does.
48934     */
48935     iCellFirst = cellOffset + 2*pPage->nCell;
48936     iCellLast = usableSize - 4;
48937 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
48938     {
48939       int i;            /* Index into the cell pointer array */
48940       int sz;           /* Size of a cell */
48941
48942       if( !pPage->leaf ) iCellLast--;
48943       for(i=0; i<pPage->nCell; i++){
48944         pc = get2byte(&data[cellOffset+i*2]);
48945         testcase( pc==iCellFirst );
48946         testcase( pc==iCellLast );
48947         if( pc<iCellFirst || pc>iCellLast ){
48948           return SQLITE_CORRUPT_BKPT;
48949         }
48950         sz = cellSizePtr(pPage, &data[pc]);
48951         testcase( pc+sz==usableSize );
48952         if( pc+sz>usableSize ){
48953           return SQLITE_CORRUPT_BKPT;
48954         }
48955       }
48956       if( !pPage->leaf ) iCellLast++;
48957     }  
48958 #endif
48959
48960     /* Compute the total free space on the page */
48961     pc = get2byte(&data[hdr+1]);
48962     nFree = data[hdr+7] + top;
48963     while( pc>0 ){
48964       u16 next, size;
48965       if( pc<iCellFirst || pc>iCellLast ){
48966         /* Start of free block is off the page */
48967         return SQLITE_CORRUPT_BKPT; 
48968       }
48969       next = get2byte(&data[pc]);
48970       size = get2byte(&data[pc+2]);
48971       if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
48972         /* Free blocks must be in ascending order. And the last byte of
48973         ** the free-block must lie on the database page.  */
48974         return SQLITE_CORRUPT_BKPT; 
48975       }
48976       nFree = nFree + size;
48977       pc = next;
48978     }
48979
48980     /* At this point, nFree contains the sum of the offset to the start
48981     ** of the cell-content area plus the number of free bytes within
48982     ** the cell-content area. If this is greater than the usable-size
48983     ** of the page, then the page must be corrupted. This check also
48984     ** serves to verify that the offset to the start of the cell-content
48985     ** area, according to the page header, lies within the page.
48986     */
48987     if( nFree>usableSize ){
48988       return SQLITE_CORRUPT_BKPT; 
48989     }
48990     pPage->nFree = (u16)(nFree - iCellFirst);
48991     pPage->isInit = 1;
48992   }
48993   return SQLITE_OK;
48994 }
48995
48996 /*
48997 ** Set up a raw page so that it looks like a database page holding
48998 ** no entries.
48999 */
49000 static void zeroPage(MemPage *pPage, int flags){
49001   unsigned char *data = pPage->aData;
49002   BtShared *pBt = pPage->pBt;
49003   u8 hdr = pPage->hdrOffset;
49004   u16 first;
49005
49006   assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
49007   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
49008   assert( sqlite3PagerGetData(pPage->pDbPage) == data );
49009   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
49010   assert( sqlite3_mutex_held(pBt->mutex) );
49011   if( pBt->secureDelete ){
49012     memset(&data[hdr], 0, pBt->usableSize - hdr);
49013   }
49014   data[hdr] = (char)flags;
49015   first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
49016   memset(&data[hdr+1], 0, 4);
49017   data[hdr+7] = 0;
49018   put2byte(&data[hdr+5], pBt->usableSize);
49019   pPage->nFree = (u16)(pBt->usableSize - first);
49020   decodeFlags(pPage, flags);
49021   pPage->hdrOffset = hdr;
49022   pPage->cellOffset = first;
49023   pPage->nOverflow = 0;
49024   assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
49025   pPage->maskPage = (u16)(pBt->pageSize - 1);
49026   pPage->nCell = 0;
49027   pPage->isInit = 1;
49028 }
49029
49030
49031 /*
49032 ** Convert a DbPage obtained from the pager into a MemPage used by
49033 ** the btree layer.
49034 */
49035 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
49036   MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
49037   pPage->aData = sqlite3PagerGetData(pDbPage);
49038   pPage->pDbPage = pDbPage;
49039   pPage->pBt = pBt;
49040   pPage->pgno = pgno;
49041   pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
49042   return pPage; 
49043 }
49044
49045 /*
49046 ** Get a page from the pager.  Initialize the MemPage.pBt and
49047 ** MemPage.aData elements if needed.
49048 **
49049 ** If the noContent flag is set, it means that we do not care about
49050 ** the content of the page at this time.  So do not go to the disk
49051 ** to fetch the content.  Just fill in the content with zeros for now.
49052 ** If in the future we call sqlite3PagerWrite() on this page, that
49053 ** means we have started to be concerned about content and the disk
49054 ** read should occur at that point.
49055 */
49056 static int btreeGetPage(
49057   BtShared *pBt,       /* The btree */
49058   Pgno pgno,           /* Number of the page to fetch */
49059   MemPage **ppPage,    /* Return the page in this parameter */
49060   int noContent        /* Do not load page content if true */
49061 ){
49062   int rc;
49063   DbPage *pDbPage;
49064
49065   assert( sqlite3_mutex_held(pBt->mutex) );
49066   rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
49067   if( rc ) return rc;
49068   *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
49069   return SQLITE_OK;
49070 }
49071
49072 /*
49073 ** Retrieve a page from the pager cache. If the requested page is not
49074 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
49075 ** MemPage.aData elements if needed.
49076 */
49077 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
49078   DbPage *pDbPage;
49079   assert( sqlite3_mutex_held(pBt->mutex) );
49080   pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
49081   if( pDbPage ){
49082     return btreePageFromDbPage(pDbPage, pgno, pBt);
49083   }
49084   return 0;
49085 }
49086
49087 /*
49088 ** Return the size of the database file in pages. If there is any kind of
49089 ** error, return ((unsigned int)-1).
49090 */
49091 static Pgno btreePagecount(BtShared *pBt){
49092   return pBt->nPage;
49093 }
49094 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
49095   assert( sqlite3BtreeHoldsMutex(p) );
49096   assert( ((p->pBt->nPage)&0x8000000)==0 );
49097   return (int)btreePagecount(p->pBt);
49098 }
49099
49100 /*
49101 ** Get a page from the pager and initialize it.  This routine is just a
49102 ** convenience wrapper around separate calls to btreeGetPage() and 
49103 ** btreeInitPage().
49104 **
49105 ** If an error occurs, then the value *ppPage is set to is undefined. It
49106 ** may remain unchanged, or it may be set to an invalid value.
49107 */
49108 static int getAndInitPage(
49109   BtShared *pBt,          /* The database file */
49110   Pgno pgno,           /* Number of the page to get */
49111   MemPage **ppPage     /* Write the page pointer here */
49112 ){
49113   int rc;
49114   assert( sqlite3_mutex_held(pBt->mutex) );
49115
49116   if( pgno>btreePagecount(pBt) ){
49117     rc = SQLITE_CORRUPT_BKPT;
49118   }else{
49119     rc = btreeGetPage(pBt, pgno, ppPage, 0);
49120     if( rc==SQLITE_OK ){
49121       rc = btreeInitPage(*ppPage);
49122       if( rc!=SQLITE_OK ){
49123         releasePage(*ppPage);
49124       }
49125     }
49126   }
49127
49128   testcase( pgno==0 );
49129   assert( pgno!=0 || rc==SQLITE_CORRUPT );
49130   return rc;
49131 }
49132
49133 /*
49134 ** Release a MemPage.  This should be called once for each prior
49135 ** call to btreeGetPage.
49136 */
49137 static void releasePage(MemPage *pPage){
49138   if( pPage ){
49139     assert( pPage->aData );
49140     assert( pPage->pBt );
49141     assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
49142     assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
49143     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49144     sqlite3PagerUnref(pPage->pDbPage);
49145   }
49146 }
49147
49148 /*
49149 ** During a rollback, when the pager reloads information into the cache
49150 ** so that the cache is restored to its original state at the start of
49151 ** the transaction, for each page restored this routine is called.
49152 **
49153 ** This routine needs to reset the extra data section at the end of the
49154 ** page to agree with the restored data.
49155 */
49156 static void pageReinit(DbPage *pData){
49157   MemPage *pPage;
49158   pPage = (MemPage *)sqlite3PagerGetExtra(pData);
49159   assert( sqlite3PagerPageRefcount(pData)>0 );
49160   if( pPage->isInit ){
49161     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49162     pPage->isInit = 0;
49163     if( sqlite3PagerPageRefcount(pData)>1 ){
49164       /* pPage might not be a btree page;  it might be an overflow page
49165       ** or ptrmap page or a free page.  In those cases, the following
49166       ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
49167       ** But no harm is done by this.  And it is very important that
49168       ** btreeInitPage() be called on every btree page so we make
49169       ** the call for every page that comes in for re-initing. */
49170       btreeInitPage(pPage);
49171     }
49172   }
49173 }
49174
49175 /*
49176 ** Invoke the busy handler for a btree.
49177 */
49178 static int btreeInvokeBusyHandler(void *pArg){
49179   BtShared *pBt = (BtShared*)pArg;
49180   assert( pBt->db );
49181   assert( sqlite3_mutex_held(pBt->db->mutex) );
49182   return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
49183 }
49184
49185 /*
49186 ** Open a database file.
49187 ** 
49188 ** zFilename is the name of the database file.  If zFilename is NULL
49189 ** then an ephemeral database is created.  The ephemeral database might
49190 ** be exclusively in memory, or it might use a disk-based memory cache.
49191 ** Either way, the ephemeral database will be automatically deleted 
49192 ** when sqlite3BtreeClose() is called.
49193 **
49194 ** If zFilename is ":memory:" then an in-memory database is created
49195 ** that is automatically destroyed when it is closed.
49196 **
49197 ** The "flags" parameter is a bitmask that might contain bits
49198 ** BTREE_OMIT_JOURNAL and/or BTREE_NO_READLOCK.  The BTREE_NO_READLOCK
49199 ** bit is also set if the SQLITE_NoReadlock flags is set in db->flags.
49200 ** These flags are passed through into sqlite3PagerOpen() and must
49201 ** be the same values as PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK.
49202 **
49203 ** If the database is already opened in the same database connection
49204 ** and we are in shared cache mode, then the open will fail with an
49205 ** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
49206 ** objects in the same database connection since doing so will lead
49207 ** to problems with locking.
49208 */
49209 SQLITE_PRIVATE int sqlite3BtreeOpen(
49210   sqlite3_vfs *pVfs,      /* VFS to use for this b-tree */
49211   const char *zFilename,  /* Name of the file containing the BTree database */
49212   sqlite3 *db,            /* Associated database handle */
49213   Btree **ppBtree,        /* Pointer to new Btree object written here */
49214   int flags,              /* Options */
49215   int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
49216 ){
49217   BtShared *pBt = 0;             /* Shared part of btree structure */
49218   Btree *p;                      /* Handle to return */
49219   sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
49220   int rc = SQLITE_OK;            /* Result code from this function */
49221   u8 nReserve;                   /* Byte of unused space on each page */
49222   unsigned char zDbHeader[100];  /* Database header content */
49223
49224   /* True if opening an ephemeral, temporary database */
49225   const int isTempDb = zFilename==0 || zFilename[0]==0;
49226
49227   /* Set the variable isMemdb to true for an in-memory database, or 
49228   ** false for a file-based database.
49229   */
49230 #ifdef SQLITE_OMIT_MEMORYDB
49231   const int isMemdb = 0;
49232 #else
49233   const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
49234                        || (isTempDb && sqlite3TempInMemory(db));
49235 #endif
49236
49237   assert( db!=0 );
49238   assert( pVfs!=0 );
49239   assert( sqlite3_mutex_held(db->mutex) );
49240   assert( (flags&0xff)==flags );   /* flags fit in 8 bits */
49241
49242   /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
49243   assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
49244
49245   /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
49246   assert( (flags & BTREE_SINGLE)==0 || isTempDb );
49247
49248   if( db->flags & SQLITE_NoReadlock ){
49249     flags |= BTREE_NO_READLOCK;
49250   }
49251   if( isMemdb ){
49252     flags |= BTREE_MEMORY;
49253   }
49254   if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
49255     vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
49256   }
49257   p = sqlite3MallocZero(sizeof(Btree));
49258   if( !p ){
49259     return SQLITE_NOMEM;
49260   }
49261   p->inTrans = TRANS_NONE;
49262   p->db = db;
49263 #ifndef SQLITE_OMIT_SHARED_CACHE
49264   p->lock.pBtree = p;
49265   p->lock.iTable = 1;
49266 #endif
49267
49268 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
49269   /*
49270   ** If this Btree is a candidate for shared cache, try to find an
49271   ** existing BtShared object that we can share with
49272   */
49273   if( isMemdb==0 && isTempDb==0 ){
49274     if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
49275       int nFullPathname = pVfs->mxPathname+1;
49276       char *zFullPathname = sqlite3Malloc(nFullPathname);
49277       sqlite3_mutex *mutexShared;
49278       p->sharable = 1;
49279       if( !zFullPathname ){
49280         sqlite3_free(p);
49281         return SQLITE_NOMEM;
49282       }
49283       sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
49284       mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
49285       sqlite3_mutex_enter(mutexOpen);
49286       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
49287       sqlite3_mutex_enter(mutexShared);
49288       for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
49289         assert( pBt->nRef>0 );
49290         if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
49291                  && sqlite3PagerVfs(pBt->pPager)==pVfs ){
49292           int iDb;
49293           for(iDb=db->nDb-1; iDb>=0; iDb--){
49294             Btree *pExisting = db->aDb[iDb].pBt;
49295             if( pExisting && pExisting->pBt==pBt ){
49296               sqlite3_mutex_leave(mutexShared);
49297               sqlite3_mutex_leave(mutexOpen);
49298               sqlite3_free(zFullPathname);
49299               sqlite3_free(p);
49300               return SQLITE_CONSTRAINT;
49301             }
49302           }
49303           p->pBt = pBt;
49304           pBt->nRef++;
49305           break;
49306         }
49307       }
49308       sqlite3_mutex_leave(mutexShared);
49309       sqlite3_free(zFullPathname);
49310     }
49311 #ifdef SQLITE_DEBUG
49312     else{
49313       /* In debug mode, we mark all persistent databases as sharable
49314       ** even when they are not.  This exercises the locking code and
49315       ** gives more opportunity for asserts(sqlite3_mutex_held())
49316       ** statements to find locking problems.
49317       */
49318       p->sharable = 1;
49319     }
49320 #endif
49321   }
49322 #endif
49323   if( pBt==0 ){
49324     /*
49325     ** The following asserts make sure that structures used by the btree are
49326     ** the right size.  This is to guard against size changes that result
49327     ** when compiling on a different architecture.
49328     */
49329     assert( sizeof(i64)==8 || sizeof(i64)==4 );
49330     assert( sizeof(u64)==8 || sizeof(u64)==4 );
49331     assert( sizeof(u32)==4 );
49332     assert( sizeof(u16)==2 );
49333     assert( sizeof(Pgno)==4 );
49334   
49335     pBt = sqlite3MallocZero( sizeof(*pBt) );
49336     if( pBt==0 ){
49337       rc = SQLITE_NOMEM;
49338       goto btree_open_out;
49339     }
49340     rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
49341                           EXTRA_SIZE, flags, vfsFlags, pageReinit);
49342     if( rc==SQLITE_OK ){
49343       rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
49344     }
49345     if( rc!=SQLITE_OK ){
49346       goto btree_open_out;
49347     }
49348     pBt->openFlags = (u8)flags;
49349     pBt->db = db;
49350     sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
49351     p->pBt = pBt;
49352   
49353     pBt->pCursor = 0;
49354     pBt->pPage1 = 0;
49355     pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
49356 #ifdef SQLITE_SECURE_DELETE
49357     pBt->secureDelete = 1;
49358 #endif
49359     pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
49360     if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
49361          || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
49362       pBt->pageSize = 0;
49363 #ifndef SQLITE_OMIT_AUTOVACUUM
49364       /* If the magic name ":memory:" will create an in-memory database, then
49365       ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
49366       ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
49367       ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
49368       ** regular file-name. In this case the auto-vacuum applies as per normal.
49369       */
49370       if( zFilename && !isMemdb ){
49371         pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
49372         pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
49373       }
49374 #endif
49375       nReserve = 0;
49376     }else{
49377       nReserve = zDbHeader[20];
49378       pBt->pageSizeFixed = 1;
49379 #ifndef SQLITE_OMIT_AUTOVACUUM
49380       pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
49381       pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
49382 #endif
49383     }
49384     rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
49385     if( rc ) goto btree_open_out;
49386     pBt->usableSize = pBt->pageSize - nReserve;
49387     assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
49388    
49389 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
49390     /* Add the new BtShared object to the linked list sharable BtShareds.
49391     */
49392     if( p->sharable ){
49393       sqlite3_mutex *mutexShared;
49394       pBt->nRef = 1;
49395       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
49396       if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
49397         pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
49398         if( pBt->mutex==0 ){
49399           rc = SQLITE_NOMEM;
49400           db->mallocFailed = 0;
49401           goto btree_open_out;
49402         }
49403       }
49404       sqlite3_mutex_enter(mutexShared);
49405       pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
49406       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
49407       sqlite3_mutex_leave(mutexShared);
49408     }
49409 #endif
49410   }
49411
49412 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
49413   /* If the new Btree uses a sharable pBtShared, then link the new
49414   ** Btree into the list of all sharable Btrees for the same connection.
49415   ** The list is kept in ascending order by pBt address.
49416   */
49417   if( p->sharable ){
49418     int i;
49419     Btree *pSib;
49420     for(i=0; i<db->nDb; i++){
49421       if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
49422         while( pSib->pPrev ){ pSib = pSib->pPrev; }
49423         if( p->pBt<pSib->pBt ){
49424           p->pNext = pSib;
49425           p->pPrev = 0;
49426           pSib->pPrev = p;
49427         }else{
49428           while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
49429             pSib = pSib->pNext;
49430           }
49431           p->pNext = pSib->pNext;
49432           p->pPrev = pSib;
49433           if( p->pNext ){
49434             p->pNext->pPrev = p;
49435           }
49436           pSib->pNext = p;
49437         }
49438         break;
49439       }
49440     }
49441   }
49442 #endif
49443   *ppBtree = p;
49444
49445 btree_open_out:
49446   if( rc!=SQLITE_OK ){
49447     if( pBt && pBt->pPager ){
49448       sqlite3PagerClose(pBt->pPager);
49449     }
49450     sqlite3_free(pBt);
49451     sqlite3_free(p);
49452     *ppBtree = 0;
49453   }else{
49454     /* If the B-Tree was successfully opened, set the pager-cache size to the
49455     ** default value. Except, when opening on an existing shared pager-cache,
49456     ** do not change the pager-cache size.
49457     */
49458     if( sqlite3BtreeSchema(p, 0, 0)==0 ){
49459       sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
49460     }
49461   }
49462   if( mutexOpen ){
49463     assert( sqlite3_mutex_held(mutexOpen) );
49464     sqlite3_mutex_leave(mutexOpen);
49465   }
49466   return rc;
49467 }
49468
49469 /*
49470 ** Decrement the BtShared.nRef counter.  When it reaches zero,
49471 ** remove the BtShared structure from the sharing list.  Return
49472 ** true if the BtShared.nRef counter reaches zero and return
49473 ** false if it is still positive.
49474 */
49475 static int removeFromSharingList(BtShared *pBt){
49476 #ifndef SQLITE_OMIT_SHARED_CACHE
49477   sqlite3_mutex *pMaster;
49478   BtShared *pList;
49479   int removed = 0;
49480
49481   assert( sqlite3_mutex_notheld(pBt->mutex) );
49482   pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
49483   sqlite3_mutex_enter(pMaster);
49484   pBt->nRef--;
49485   if( pBt->nRef<=0 ){
49486     if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
49487       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
49488     }else{
49489       pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
49490       while( ALWAYS(pList) && pList->pNext!=pBt ){
49491         pList=pList->pNext;
49492       }
49493       if( ALWAYS(pList) ){
49494         pList->pNext = pBt->pNext;
49495       }
49496     }
49497     if( SQLITE_THREADSAFE ){
49498       sqlite3_mutex_free(pBt->mutex);
49499     }
49500     removed = 1;
49501   }
49502   sqlite3_mutex_leave(pMaster);
49503   return removed;
49504 #else
49505   return 1;
49506 #endif
49507 }
49508
49509 /*
49510 ** Make sure pBt->pTmpSpace points to an allocation of 
49511 ** MX_CELL_SIZE(pBt) bytes.
49512 */
49513 static void allocateTempSpace(BtShared *pBt){
49514   if( !pBt->pTmpSpace ){
49515     pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
49516   }
49517 }
49518
49519 /*
49520 ** Free the pBt->pTmpSpace allocation
49521 */
49522 static void freeTempSpace(BtShared *pBt){
49523   sqlite3PageFree( pBt->pTmpSpace);
49524   pBt->pTmpSpace = 0;
49525 }
49526
49527 /*
49528 ** Close an open database and invalidate all cursors.
49529 */
49530 SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
49531   BtShared *pBt = p->pBt;
49532   BtCursor *pCur;
49533
49534   /* Close all cursors opened via this handle.  */
49535   assert( sqlite3_mutex_held(p->db->mutex) );
49536   sqlite3BtreeEnter(p);
49537   pCur = pBt->pCursor;
49538   while( pCur ){
49539     BtCursor *pTmp = pCur;
49540     pCur = pCur->pNext;
49541     if( pTmp->pBtree==p ){
49542       sqlite3BtreeCloseCursor(pTmp);
49543     }
49544   }
49545
49546   /* Rollback any active transaction and free the handle structure.
49547   ** The call to sqlite3BtreeRollback() drops any table-locks held by
49548   ** this handle.
49549   */
49550   sqlite3BtreeRollback(p);
49551   sqlite3BtreeLeave(p);
49552
49553   /* If there are still other outstanding references to the shared-btree
49554   ** structure, return now. The remainder of this procedure cleans 
49555   ** up the shared-btree.
49556   */
49557   assert( p->wantToLock==0 && p->locked==0 );
49558   if( !p->sharable || removeFromSharingList(pBt) ){
49559     /* The pBt is no longer on the sharing list, so we can access
49560     ** it without having to hold the mutex.
49561     **
49562     ** Clean out and delete the BtShared object.
49563     */
49564     assert( !pBt->pCursor );
49565     sqlite3PagerClose(pBt->pPager);
49566     if( pBt->xFreeSchema && pBt->pSchema ){
49567       pBt->xFreeSchema(pBt->pSchema);
49568     }
49569     sqlite3DbFree(0, pBt->pSchema);
49570     freeTempSpace(pBt);
49571     sqlite3_free(pBt);
49572   }
49573
49574 #ifndef SQLITE_OMIT_SHARED_CACHE
49575   assert( p->wantToLock==0 );
49576   assert( p->locked==0 );
49577   if( p->pPrev ) p->pPrev->pNext = p->pNext;
49578   if( p->pNext ) p->pNext->pPrev = p->pPrev;
49579 #endif
49580
49581   sqlite3_free(p);
49582   return SQLITE_OK;
49583 }
49584
49585 /*
49586 ** Change the limit on the number of pages allowed in the cache.
49587 **
49588 ** The maximum number of cache pages is set to the absolute
49589 ** value of mxPage.  If mxPage is negative, the pager will
49590 ** operate asynchronously - it will not stop to do fsync()s
49591 ** to insure data is written to the disk surface before
49592 ** continuing.  Transactions still work if synchronous is off,
49593 ** and the database cannot be corrupted if this program
49594 ** crashes.  But if the operating system crashes or there is
49595 ** an abrupt power failure when synchronous is off, the database
49596 ** could be left in an inconsistent and unrecoverable state.
49597 ** Synchronous is on by default so database corruption is not
49598 ** normally a worry.
49599 */
49600 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
49601   BtShared *pBt = p->pBt;
49602   assert( sqlite3_mutex_held(p->db->mutex) );
49603   sqlite3BtreeEnter(p);
49604   sqlite3PagerSetCachesize(pBt->pPager, mxPage);
49605   sqlite3BtreeLeave(p);
49606   return SQLITE_OK;
49607 }
49608
49609 /*
49610 ** Change the way data is synced to disk in order to increase or decrease
49611 ** how well the database resists damage due to OS crashes and power
49612 ** failures.  Level 1 is the same as asynchronous (no syncs() occur and
49613 ** there is a high probability of damage)  Level 2 is the default.  There
49614 ** is a very low but non-zero probability of damage.  Level 3 reduces the
49615 ** probability of damage to near zero but with a write performance reduction.
49616 */
49617 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
49618 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(
49619   Btree *p,              /* The btree to set the safety level on */
49620   int level,             /* PRAGMA synchronous.  1=OFF, 2=NORMAL, 3=FULL */
49621   int fullSync,          /* PRAGMA fullfsync. */
49622   int ckptFullSync       /* PRAGMA checkpoint_fullfync */
49623 ){
49624   BtShared *pBt = p->pBt;
49625   assert( sqlite3_mutex_held(p->db->mutex) );
49626   assert( level>=1 && level<=3 );
49627   sqlite3BtreeEnter(p);
49628   sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync, ckptFullSync);
49629   sqlite3BtreeLeave(p);
49630   return SQLITE_OK;
49631 }
49632 #endif
49633
49634 /*
49635 ** Return TRUE if the given btree is set to safety level 1.  In other
49636 ** words, return TRUE if no sync() occurs on the disk files.
49637 */
49638 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
49639   BtShared *pBt = p->pBt;
49640   int rc;
49641   assert( sqlite3_mutex_held(p->db->mutex) );  
49642   sqlite3BtreeEnter(p);
49643   assert( pBt && pBt->pPager );
49644   rc = sqlite3PagerNosync(pBt->pPager);
49645   sqlite3BtreeLeave(p);
49646   return rc;
49647 }
49648
49649 /*
49650 ** Change the default pages size and the number of reserved bytes per page.
49651 ** Or, if the page size has already been fixed, return SQLITE_READONLY 
49652 ** without changing anything.
49653 **
49654 ** The page size must be a power of 2 between 512 and 65536.  If the page
49655 ** size supplied does not meet this constraint then the page size is not
49656 ** changed.
49657 **
49658 ** Page sizes are constrained to be a power of two so that the region
49659 ** of the database file used for locking (beginning at PENDING_BYTE,
49660 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
49661 ** at the beginning of a page.
49662 **
49663 ** If parameter nReserve is less than zero, then the number of reserved
49664 ** bytes per page is left unchanged.
49665 **
49666 ** If the iFix!=0 then the pageSizeFixed flag is set so that the page size
49667 ** and autovacuum mode can no longer be changed.
49668 */
49669 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
49670   int rc = SQLITE_OK;
49671   BtShared *pBt = p->pBt;
49672   assert( nReserve>=-1 && nReserve<=255 );
49673   sqlite3BtreeEnter(p);
49674   if( pBt->pageSizeFixed ){
49675     sqlite3BtreeLeave(p);
49676     return SQLITE_READONLY;
49677   }
49678   if( nReserve<0 ){
49679     nReserve = pBt->pageSize - pBt->usableSize;
49680   }
49681   assert( nReserve>=0 && nReserve<=255 );
49682   if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
49683         ((pageSize-1)&pageSize)==0 ){
49684     assert( (pageSize & 7)==0 );
49685     assert( !pBt->pPage1 && !pBt->pCursor );
49686     pBt->pageSize = (u32)pageSize;
49687     freeTempSpace(pBt);
49688   }
49689   rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
49690   pBt->usableSize = pBt->pageSize - (u16)nReserve;
49691   if( iFix ) pBt->pageSizeFixed = 1;
49692   sqlite3BtreeLeave(p);
49693   return rc;
49694 }
49695
49696 /*
49697 ** Return the currently defined page size
49698 */
49699 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
49700   return p->pBt->pageSize;
49701 }
49702
49703 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
49704 /*
49705 ** Return the number of bytes of space at the end of every page that
49706 ** are intentually left unused.  This is the "reserved" space that is
49707 ** sometimes used by extensions.
49708 */
49709 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
49710   int n;
49711   sqlite3BtreeEnter(p);
49712   n = p->pBt->pageSize - p->pBt->usableSize;
49713   sqlite3BtreeLeave(p);
49714   return n;
49715 }
49716
49717 /*
49718 ** Set the maximum page count for a database if mxPage is positive.
49719 ** No changes are made if mxPage is 0 or negative.
49720 ** Regardless of the value of mxPage, return the maximum page count.
49721 */
49722 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
49723   int n;
49724   sqlite3BtreeEnter(p);
49725   n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
49726   sqlite3BtreeLeave(p);
49727   return n;
49728 }
49729
49730 /*
49731 ** Set the secureDelete flag if newFlag is 0 or 1.  If newFlag is -1,
49732 ** then make no changes.  Always return the value of the secureDelete
49733 ** setting after the change.
49734 */
49735 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
49736   int b;
49737   if( p==0 ) return 0;
49738   sqlite3BtreeEnter(p);
49739   if( newFlag>=0 ){
49740     p->pBt->secureDelete = (newFlag!=0) ? 1 : 0;
49741   } 
49742   b = p->pBt->secureDelete;
49743   sqlite3BtreeLeave(p);
49744   return b;
49745 }
49746 #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
49747
49748 /*
49749 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
49750 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
49751 ** is disabled. The default value for the auto-vacuum property is 
49752 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
49753 */
49754 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
49755 #ifdef SQLITE_OMIT_AUTOVACUUM
49756   return SQLITE_READONLY;
49757 #else
49758   BtShared *pBt = p->pBt;
49759   int rc = SQLITE_OK;
49760   u8 av = (u8)autoVacuum;
49761
49762   sqlite3BtreeEnter(p);
49763   if( pBt->pageSizeFixed && (av ?1:0)!=pBt->autoVacuum ){
49764     rc = SQLITE_READONLY;
49765   }else{
49766     pBt->autoVacuum = av ?1:0;
49767     pBt->incrVacuum = av==2 ?1:0;
49768   }
49769   sqlite3BtreeLeave(p);
49770   return rc;
49771 #endif
49772 }
49773
49774 /*
49775 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is 
49776 ** enabled 1 is returned. Otherwise 0.
49777 */
49778 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
49779 #ifdef SQLITE_OMIT_AUTOVACUUM
49780   return BTREE_AUTOVACUUM_NONE;
49781 #else
49782   int rc;
49783   sqlite3BtreeEnter(p);
49784   rc = (
49785     (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
49786     (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
49787     BTREE_AUTOVACUUM_INCR
49788   );
49789   sqlite3BtreeLeave(p);
49790   return rc;
49791 #endif
49792 }
49793
49794
49795 /*
49796 ** Get a reference to pPage1 of the database file.  This will
49797 ** also acquire a readlock on that file.
49798 **
49799 ** SQLITE_OK is returned on success.  If the file is not a
49800 ** well-formed database file, then SQLITE_CORRUPT is returned.
49801 ** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
49802 ** is returned if we run out of memory. 
49803 */
49804 static int lockBtree(BtShared *pBt){
49805   int rc;              /* Result code from subfunctions */
49806   MemPage *pPage1;     /* Page 1 of the database file */
49807   int nPage;           /* Number of pages in the database */
49808   int nPageFile = 0;   /* Number of pages in the database file */
49809   int nPageHeader;     /* Number of pages in the database according to hdr */
49810
49811   assert( sqlite3_mutex_held(pBt->mutex) );
49812   assert( pBt->pPage1==0 );
49813   rc = sqlite3PagerSharedLock(pBt->pPager);
49814   if( rc!=SQLITE_OK ) return rc;
49815   rc = btreeGetPage(pBt, 1, &pPage1, 0);
49816   if( rc!=SQLITE_OK ) return rc;
49817
49818   /* Do some checking to help insure the file we opened really is
49819   ** a valid database file. 
49820   */
49821   nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
49822   sqlite3PagerPagecount(pBt->pPager, &nPageFile);
49823   if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
49824     nPage = nPageFile;
49825   }
49826   if( nPage>0 ){
49827     u32 pageSize;
49828     u32 usableSize;
49829     u8 *page1 = pPage1->aData;
49830     rc = SQLITE_NOTADB;
49831     if( memcmp(page1, zMagicHeader, 16)!=0 ){
49832       goto page1_init_failed;
49833     }
49834
49835 #ifdef SQLITE_OMIT_WAL
49836     if( page1[18]>1 ){
49837       pBt->readOnly = 1;
49838     }
49839     if( page1[19]>1 ){
49840       goto page1_init_failed;
49841     }
49842 #else
49843     if( page1[18]>2 ){
49844       pBt->readOnly = 1;
49845     }
49846     if( page1[19]>2 ){
49847       goto page1_init_failed;
49848     }
49849
49850     /* If the write version is set to 2, this database should be accessed
49851     ** in WAL mode. If the log is not already open, open it now. Then 
49852     ** return SQLITE_OK and return without populating BtShared.pPage1.
49853     ** The caller detects this and calls this function again. This is
49854     ** required as the version of page 1 currently in the page1 buffer
49855     ** may not be the latest version - there may be a newer one in the log
49856     ** file.
49857     */
49858     if( page1[19]==2 && pBt->doNotUseWAL==0 ){
49859       int isOpen = 0;
49860       rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
49861       if( rc!=SQLITE_OK ){
49862         goto page1_init_failed;
49863       }else if( isOpen==0 ){
49864         releasePage(pPage1);
49865         return SQLITE_OK;
49866       }
49867       rc = SQLITE_NOTADB;
49868     }
49869 #endif
49870
49871     /* The maximum embedded fraction must be exactly 25%.  And the minimum
49872     ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
49873     ** The original design allowed these amounts to vary, but as of
49874     ** version 3.6.0, we require them to be fixed.
49875     */
49876     if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
49877       goto page1_init_failed;
49878     }
49879     pageSize = (page1[16]<<8) | (page1[17]<<16);
49880     if( ((pageSize-1)&pageSize)!=0
49881      || pageSize>SQLITE_MAX_PAGE_SIZE 
49882      || pageSize<=256 
49883     ){
49884       goto page1_init_failed;
49885     }
49886     assert( (pageSize & 7)==0 );
49887     usableSize = pageSize - page1[20];
49888     if( (u32)pageSize!=pBt->pageSize ){
49889       /* After reading the first page of the database assuming a page size
49890       ** of BtShared.pageSize, we have discovered that the page-size is
49891       ** actually pageSize. Unlock the database, leave pBt->pPage1 at
49892       ** zero and return SQLITE_OK. The caller will call this function
49893       ** again with the correct page-size.
49894       */
49895       releasePage(pPage1);
49896       pBt->usableSize = usableSize;
49897       pBt->pageSize = pageSize;
49898       freeTempSpace(pBt);
49899       rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
49900                                    pageSize-usableSize);
49901       return rc;
49902     }
49903     if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
49904       rc = SQLITE_CORRUPT_BKPT;
49905       goto page1_init_failed;
49906     }
49907     if( usableSize<480 ){
49908       goto page1_init_failed;
49909     }
49910     pBt->pageSize = pageSize;
49911     pBt->usableSize = usableSize;
49912 #ifndef SQLITE_OMIT_AUTOVACUUM
49913     pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
49914     pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
49915 #endif
49916   }
49917
49918   /* maxLocal is the maximum amount of payload to store locally for
49919   ** a cell.  Make sure it is small enough so that at least minFanout
49920   ** cells can will fit on one page.  We assume a 10-byte page header.
49921   ** Besides the payload, the cell must store:
49922   **     2-byte pointer to the cell
49923   **     4-byte child pointer
49924   **     9-byte nKey value
49925   **     4-byte nData value
49926   **     4-byte overflow page pointer
49927   ** So a cell consists of a 2-byte pointer, a header which is as much as
49928   ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
49929   ** page pointer.
49930   */
49931   pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
49932   pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
49933   pBt->maxLeaf = (u16)(pBt->usableSize - 35);
49934   pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
49935   assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
49936   pBt->pPage1 = pPage1;
49937   pBt->nPage = nPage;
49938   return SQLITE_OK;
49939
49940 page1_init_failed:
49941   releasePage(pPage1);
49942   pBt->pPage1 = 0;
49943   return rc;
49944 }
49945
49946 /*
49947 ** If there are no outstanding cursors and we are not in the middle
49948 ** of a transaction but there is a read lock on the database, then
49949 ** this routine unrefs the first page of the database file which 
49950 ** has the effect of releasing the read lock.
49951 **
49952 ** If there is a transaction in progress, this routine is a no-op.
49953 */
49954 static void unlockBtreeIfUnused(BtShared *pBt){
49955   assert( sqlite3_mutex_held(pBt->mutex) );
49956   assert( pBt->pCursor==0 || pBt->inTransaction>TRANS_NONE );
49957   if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
49958     assert( pBt->pPage1->aData );
49959     assert( sqlite3PagerRefcount(pBt->pPager)==1 );
49960     assert( pBt->pPage1->aData );
49961     releasePage(pBt->pPage1);
49962     pBt->pPage1 = 0;
49963   }
49964 }
49965
49966 /*
49967 ** If pBt points to an empty file then convert that empty file
49968 ** into a new empty database by initializing the first page of
49969 ** the database.
49970 */
49971 static int newDatabase(BtShared *pBt){
49972   MemPage *pP1;
49973   unsigned char *data;
49974   int rc;
49975
49976   assert( sqlite3_mutex_held(pBt->mutex) );
49977   if( pBt->nPage>0 ){
49978     return SQLITE_OK;
49979   }
49980   pP1 = pBt->pPage1;
49981   assert( pP1!=0 );
49982   data = pP1->aData;
49983   rc = sqlite3PagerWrite(pP1->pDbPage);
49984   if( rc ) return rc;
49985   memcpy(data, zMagicHeader, sizeof(zMagicHeader));
49986   assert( sizeof(zMagicHeader)==16 );
49987   data[16] = (u8)((pBt->pageSize>>8)&0xff);
49988   data[17] = (u8)((pBt->pageSize>>16)&0xff);
49989   data[18] = 1;
49990   data[19] = 1;
49991   assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
49992   data[20] = (u8)(pBt->pageSize - pBt->usableSize);
49993   data[21] = 64;
49994   data[22] = 32;
49995   data[23] = 32;
49996   memset(&data[24], 0, 100-24);
49997   zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
49998   pBt->pageSizeFixed = 1;
49999 #ifndef SQLITE_OMIT_AUTOVACUUM
50000   assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
50001   assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
50002   put4byte(&data[36 + 4*4], pBt->autoVacuum);
50003   put4byte(&data[36 + 7*4], pBt->incrVacuum);
50004 #endif
50005   pBt->nPage = 1;
50006   data[31] = 1;
50007   return SQLITE_OK;
50008 }
50009
50010 /*
50011 ** Attempt to start a new transaction. A write-transaction
50012 ** is started if the second argument is nonzero, otherwise a read-
50013 ** transaction.  If the second argument is 2 or more and exclusive
50014 ** transaction is started, meaning that no other process is allowed
50015 ** to access the database.  A preexisting transaction may not be
50016 ** upgraded to exclusive by calling this routine a second time - the
50017 ** exclusivity flag only works for a new transaction.
50018 **
50019 ** A write-transaction must be started before attempting any 
50020 ** changes to the database.  None of the following routines 
50021 ** will work unless a transaction is started first:
50022 **
50023 **      sqlite3BtreeCreateTable()
50024 **      sqlite3BtreeCreateIndex()
50025 **      sqlite3BtreeClearTable()
50026 **      sqlite3BtreeDropTable()
50027 **      sqlite3BtreeInsert()
50028 **      sqlite3BtreeDelete()
50029 **      sqlite3BtreeUpdateMeta()
50030 **
50031 ** If an initial attempt to acquire the lock fails because of lock contention
50032 ** and the database was previously unlocked, then invoke the busy handler
50033 ** if there is one.  But if there was previously a read-lock, do not
50034 ** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is 
50035 ** returned when there is already a read-lock in order to avoid a deadlock.
50036 **
50037 ** Suppose there are two processes A and B.  A has a read lock and B has
50038 ** a reserved lock.  B tries to promote to exclusive but is blocked because
50039 ** of A's read lock.  A tries to promote to reserved but is blocked by B.
50040 ** One or the other of the two processes must give way or there can be
50041 ** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
50042 ** when A already has a read lock, we encourage A to give up and let B
50043 ** proceed.
50044 */
50045 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
50046   sqlite3 *pBlock = 0;
50047   BtShared *pBt = p->pBt;
50048   int rc = SQLITE_OK;
50049
50050   sqlite3BtreeEnter(p);
50051   btreeIntegrity(p);
50052
50053   /* If the btree is already in a write-transaction, or it
50054   ** is already in a read-transaction and a read-transaction
50055   ** is requested, this is a no-op.
50056   */
50057   if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
50058     goto trans_begun;
50059   }
50060
50061   /* Write transactions are not possible on a read-only database */
50062   if( pBt->readOnly && wrflag ){
50063     rc = SQLITE_READONLY;
50064     goto trans_begun;
50065   }
50066
50067 #ifndef SQLITE_OMIT_SHARED_CACHE
50068   /* If another database handle has already opened a write transaction 
50069   ** on this shared-btree structure and a second write transaction is
50070   ** requested, return SQLITE_LOCKED.
50071   */
50072   if( (wrflag && pBt->inTransaction==TRANS_WRITE) || pBt->isPending ){
50073     pBlock = pBt->pWriter->db;
50074   }else if( wrflag>1 ){
50075     BtLock *pIter;
50076     for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
50077       if( pIter->pBtree!=p ){
50078         pBlock = pIter->pBtree->db;
50079         break;
50080       }
50081     }
50082   }
50083   if( pBlock ){
50084     sqlite3ConnectionBlocked(p->db, pBlock);
50085     rc = SQLITE_LOCKED_SHAREDCACHE;
50086     goto trans_begun;
50087   }
50088 #endif
50089
50090   /* Any read-only or read-write transaction implies a read-lock on 
50091   ** page 1. So if some other shared-cache client already has a write-lock 
50092   ** on page 1, the transaction cannot be opened. */
50093   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
50094   if( SQLITE_OK!=rc ) goto trans_begun;
50095
50096   pBt->initiallyEmpty = (u8)(pBt->nPage==0);
50097   do {
50098     /* Call lockBtree() until either pBt->pPage1 is populated or
50099     ** lockBtree() returns something other than SQLITE_OK. lockBtree()
50100     ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
50101     ** reading page 1 it discovers that the page-size of the database 
50102     ** file is not pBt->pageSize. In this case lockBtree() will update
50103     ** pBt->pageSize to the page-size of the file on disk.
50104     */
50105     while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
50106
50107     if( rc==SQLITE_OK && wrflag ){
50108       if( pBt->readOnly ){
50109         rc = SQLITE_READONLY;
50110       }else{
50111         rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
50112         if( rc==SQLITE_OK ){
50113           rc = newDatabase(pBt);
50114         }
50115       }
50116     }
50117   
50118     if( rc!=SQLITE_OK ){
50119       unlockBtreeIfUnused(pBt);
50120     }
50121   }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
50122           btreeInvokeBusyHandler(pBt) );
50123
50124   if( rc==SQLITE_OK ){
50125     if( p->inTrans==TRANS_NONE ){
50126       pBt->nTransaction++;
50127 #ifndef SQLITE_OMIT_SHARED_CACHE
50128       if( p->sharable ){
50129         assert( p->lock.pBtree==p && p->lock.iTable==1 );
50130         p->lock.eLock = READ_LOCK;
50131         p->lock.pNext = pBt->pLock;
50132         pBt->pLock = &p->lock;
50133       }
50134 #endif
50135     }
50136     p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
50137     if( p->inTrans>pBt->inTransaction ){
50138       pBt->inTransaction = p->inTrans;
50139     }
50140     if( wrflag ){
50141       MemPage *pPage1 = pBt->pPage1;
50142 #ifndef SQLITE_OMIT_SHARED_CACHE
50143       assert( !pBt->pWriter );
50144       pBt->pWriter = p;
50145       pBt->isExclusive = (u8)(wrflag>1);
50146 #endif
50147
50148       /* If the db-size header field is incorrect (as it may be if an old
50149       ** client has been writing the database file), update it now. Doing
50150       ** this sooner rather than later means the database size can safely 
50151       ** re-read the database size from page 1 if a savepoint or transaction
50152       ** rollback occurs within the transaction.
50153       */
50154       if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
50155         rc = sqlite3PagerWrite(pPage1->pDbPage);
50156         if( rc==SQLITE_OK ){
50157           put4byte(&pPage1->aData[28], pBt->nPage);
50158         }
50159       }
50160     }
50161   }
50162
50163
50164 trans_begun:
50165   if( rc==SQLITE_OK && wrflag ){
50166     /* This call makes sure that the pager has the correct number of
50167     ** open savepoints. If the second parameter is greater than 0 and
50168     ** the sub-journal is not already open, then it will be opened here.
50169     */
50170     rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
50171   }
50172
50173   btreeIntegrity(p);
50174   sqlite3BtreeLeave(p);
50175   return rc;
50176 }
50177
50178 #ifndef SQLITE_OMIT_AUTOVACUUM
50179
50180 /*
50181 ** Set the pointer-map entries for all children of page pPage. Also, if
50182 ** pPage contains cells that point to overflow pages, set the pointer
50183 ** map entries for the overflow pages as well.
50184 */
50185 static int setChildPtrmaps(MemPage *pPage){
50186   int i;                             /* Counter variable */
50187   int nCell;                         /* Number of cells in page pPage */
50188   int rc;                            /* Return code */
50189   BtShared *pBt = pPage->pBt;
50190   u8 isInitOrig = pPage->isInit;
50191   Pgno pgno = pPage->pgno;
50192
50193   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50194   rc = btreeInitPage(pPage);
50195   if( rc!=SQLITE_OK ){
50196     goto set_child_ptrmaps_out;
50197   }
50198   nCell = pPage->nCell;
50199
50200   for(i=0; i<nCell; i++){
50201     u8 *pCell = findCell(pPage, i);
50202
50203     ptrmapPutOvflPtr(pPage, pCell, &rc);
50204
50205     if( !pPage->leaf ){
50206       Pgno childPgno = get4byte(pCell);
50207       ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
50208     }
50209   }
50210
50211   if( !pPage->leaf ){
50212     Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
50213     ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
50214   }
50215
50216 set_child_ptrmaps_out:
50217   pPage->isInit = isInitOrig;
50218   return rc;
50219 }
50220
50221 /*
50222 ** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
50223 ** that it points to iTo. Parameter eType describes the type of pointer to
50224 ** be modified, as  follows:
50225 **
50226 ** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child 
50227 **                   page of pPage.
50228 **
50229 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
50230 **                   page pointed to by one of the cells on pPage.
50231 **
50232 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
50233 **                   overflow page in the list.
50234 */
50235 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
50236   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50237   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
50238   if( eType==PTRMAP_OVERFLOW2 ){
50239     /* The pointer is always the first 4 bytes of the page in this case.  */
50240     if( get4byte(pPage->aData)!=iFrom ){
50241       return SQLITE_CORRUPT_BKPT;
50242     }
50243     put4byte(pPage->aData, iTo);
50244   }else{
50245     u8 isInitOrig = pPage->isInit;
50246     int i;
50247     int nCell;
50248
50249     btreeInitPage(pPage);
50250     nCell = pPage->nCell;
50251
50252     for(i=0; i<nCell; i++){
50253       u8 *pCell = findCell(pPage, i);
50254       if( eType==PTRMAP_OVERFLOW1 ){
50255         CellInfo info;
50256         btreeParseCellPtr(pPage, pCell, &info);
50257         if( info.iOverflow ){
50258           if( iFrom==get4byte(&pCell[info.iOverflow]) ){
50259             put4byte(&pCell[info.iOverflow], iTo);
50260             break;
50261           }
50262         }
50263       }else{
50264         if( get4byte(pCell)==iFrom ){
50265           put4byte(pCell, iTo);
50266           break;
50267         }
50268       }
50269     }
50270   
50271     if( i==nCell ){
50272       if( eType!=PTRMAP_BTREE || 
50273           get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
50274         return SQLITE_CORRUPT_BKPT;
50275       }
50276       put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
50277     }
50278
50279     pPage->isInit = isInitOrig;
50280   }
50281   return SQLITE_OK;
50282 }
50283
50284
50285 /*
50286 ** Move the open database page pDbPage to location iFreePage in the 
50287 ** database. The pDbPage reference remains valid.
50288 **
50289 ** The isCommit flag indicates that there is no need to remember that
50290 ** the journal needs to be sync()ed before database page pDbPage->pgno 
50291 ** can be written to. The caller has already promised not to write to that
50292 ** page.
50293 */
50294 static int relocatePage(
50295   BtShared *pBt,           /* Btree */
50296   MemPage *pDbPage,        /* Open page to move */
50297   u8 eType,                /* Pointer map 'type' entry for pDbPage */
50298   Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
50299   Pgno iFreePage,          /* The location to move pDbPage to */
50300   int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
50301 ){
50302   MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
50303   Pgno iDbPage = pDbPage->pgno;
50304   Pager *pPager = pBt->pPager;
50305   int rc;
50306
50307   assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 || 
50308       eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
50309   assert( sqlite3_mutex_held(pBt->mutex) );
50310   assert( pDbPage->pBt==pBt );
50311
50312   /* Move page iDbPage from its current location to page number iFreePage */
50313   TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n", 
50314       iDbPage, iFreePage, iPtrPage, eType));
50315   rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
50316   if( rc!=SQLITE_OK ){
50317     return rc;
50318   }
50319   pDbPage->pgno = iFreePage;
50320
50321   /* If pDbPage was a btree-page, then it may have child pages and/or cells
50322   ** that point to overflow pages. The pointer map entries for all these
50323   ** pages need to be changed.
50324   **
50325   ** If pDbPage is an overflow page, then the first 4 bytes may store a
50326   ** pointer to a subsequent overflow page. If this is the case, then
50327   ** the pointer map needs to be updated for the subsequent overflow page.
50328   */
50329   if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
50330     rc = setChildPtrmaps(pDbPage);
50331     if( rc!=SQLITE_OK ){
50332       return rc;
50333     }
50334   }else{
50335     Pgno nextOvfl = get4byte(pDbPage->aData);
50336     if( nextOvfl!=0 ){
50337       ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
50338       if( rc!=SQLITE_OK ){
50339         return rc;
50340       }
50341     }
50342   }
50343
50344   /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
50345   ** that it points at iFreePage. Also fix the pointer map entry for
50346   ** iPtrPage.
50347   */
50348   if( eType!=PTRMAP_ROOTPAGE ){
50349     rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
50350     if( rc!=SQLITE_OK ){
50351       return rc;
50352     }
50353     rc = sqlite3PagerWrite(pPtrPage->pDbPage);
50354     if( rc!=SQLITE_OK ){
50355       releasePage(pPtrPage);
50356       return rc;
50357     }
50358     rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
50359     releasePage(pPtrPage);
50360     if( rc==SQLITE_OK ){
50361       ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
50362     }
50363   }
50364   return rc;
50365 }
50366
50367 /* Forward declaration required by incrVacuumStep(). */
50368 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
50369
50370 /*
50371 ** Perform a single step of an incremental-vacuum. If successful,
50372 ** return SQLITE_OK. If there is no work to do (and therefore no
50373 ** point in calling this function again), return SQLITE_DONE.
50374 **
50375 ** More specificly, this function attempts to re-organize the 
50376 ** database so that the last page of the file currently in use
50377 ** is no longer in use.
50378 **
50379 ** If the nFin parameter is non-zero, this function assumes
50380 ** that the caller will keep calling incrVacuumStep() until
50381 ** it returns SQLITE_DONE or an error, and that nFin is the
50382 ** number of pages the database file will contain after this 
50383 ** process is complete.  If nFin is zero, it is assumed that
50384 ** incrVacuumStep() will be called a finite amount of times
50385 ** which may or may not empty the freelist.  A full autovacuum
50386 ** has nFin>0.  A "PRAGMA incremental_vacuum" has nFin==0.
50387 */
50388 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){
50389   Pgno nFreeList;           /* Number of pages still on the free-list */
50390   int rc;
50391
50392   assert( sqlite3_mutex_held(pBt->mutex) );
50393   assert( iLastPg>nFin );
50394
50395   if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
50396     u8 eType;
50397     Pgno iPtrPage;
50398
50399     nFreeList = get4byte(&pBt->pPage1->aData[36]);
50400     if( nFreeList==0 ){
50401       return SQLITE_DONE;
50402     }
50403
50404     rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
50405     if( rc!=SQLITE_OK ){
50406       return rc;
50407     }
50408     if( eType==PTRMAP_ROOTPAGE ){
50409       return SQLITE_CORRUPT_BKPT;
50410     }
50411
50412     if( eType==PTRMAP_FREEPAGE ){
50413       if( nFin==0 ){
50414         /* Remove the page from the files free-list. This is not required
50415         ** if nFin is non-zero. In that case, the free-list will be
50416         ** truncated to zero after this function returns, so it doesn't 
50417         ** matter if it still contains some garbage entries.
50418         */
50419         Pgno iFreePg;
50420         MemPage *pFreePg;
50421         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
50422         if( rc!=SQLITE_OK ){
50423           return rc;
50424         }
50425         assert( iFreePg==iLastPg );
50426         releasePage(pFreePg);
50427       }
50428     } else {
50429       Pgno iFreePg;             /* Index of free page to move pLastPg to */
50430       MemPage *pLastPg;
50431
50432       rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
50433       if( rc!=SQLITE_OK ){
50434         return rc;
50435       }
50436
50437       /* If nFin is zero, this loop runs exactly once and page pLastPg
50438       ** is swapped with the first free page pulled off the free list.
50439       **
50440       ** On the other hand, if nFin is greater than zero, then keep
50441       ** looping until a free-page located within the first nFin pages
50442       ** of the file is found.
50443       */
50444       do {
50445         MemPage *pFreePg;
50446         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
50447         if( rc!=SQLITE_OK ){
50448           releasePage(pLastPg);
50449           return rc;
50450         }
50451         releasePage(pFreePg);
50452       }while( nFin!=0 && iFreePg>nFin );
50453       assert( iFreePg<iLastPg );
50454       
50455       rc = sqlite3PagerWrite(pLastPg->pDbPage);
50456       if( rc==SQLITE_OK ){
50457         rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
50458       }
50459       releasePage(pLastPg);
50460       if( rc!=SQLITE_OK ){
50461         return rc;
50462       }
50463     }
50464   }
50465
50466   if( nFin==0 ){
50467     iLastPg--;
50468     while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){
50469       if( PTRMAP_ISPAGE(pBt, iLastPg) ){
50470         MemPage *pPg;
50471         rc = btreeGetPage(pBt, iLastPg, &pPg, 0);
50472         if( rc!=SQLITE_OK ){
50473           return rc;
50474         }
50475         rc = sqlite3PagerWrite(pPg->pDbPage);
50476         releasePage(pPg);
50477         if( rc!=SQLITE_OK ){
50478           return rc;
50479         }
50480       }
50481       iLastPg--;
50482     }
50483     sqlite3PagerTruncateImage(pBt->pPager, iLastPg);
50484     pBt->nPage = iLastPg;
50485   }
50486   return SQLITE_OK;
50487 }
50488
50489 /*
50490 ** A write-transaction must be opened before calling this function.
50491 ** It performs a single unit of work towards an incremental vacuum.
50492 **
50493 ** If the incremental vacuum is finished after this function has run,
50494 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
50495 ** SQLITE_OK is returned. Otherwise an SQLite error code. 
50496 */
50497 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
50498   int rc;
50499   BtShared *pBt = p->pBt;
50500
50501   sqlite3BtreeEnter(p);
50502   assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
50503   if( !pBt->autoVacuum ){
50504     rc = SQLITE_DONE;
50505   }else{
50506     invalidateAllOverflowCache(pBt);
50507     rc = incrVacuumStep(pBt, 0, btreePagecount(pBt));
50508     if( rc==SQLITE_OK ){
50509       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
50510       put4byte(&pBt->pPage1->aData[28], pBt->nPage);
50511     }
50512   }
50513   sqlite3BtreeLeave(p);
50514   return rc;
50515 }
50516
50517 /*
50518 ** This routine is called prior to sqlite3PagerCommit when a transaction
50519 ** is commited for an auto-vacuum database.
50520 **
50521 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
50522 ** the database file should be truncated to during the commit process. 
50523 ** i.e. the database has been reorganized so that only the first *pnTrunc
50524 ** pages are in use.
50525 */
50526 static int autoVacuumCommit(BtShared *pBt){
50527   int rc = SQLITE_OK;
50528   Pager *pPager = pBt->pPager;
50529   VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
50530
50531   assert( sqlite3_mutex_held(pBt->mutex) );
50532   invalidateAllOverflowCache(pBt);
50533   assert(pBt->autoVacuum);
50534   if( !pBt->incrVacuum ){
50535     Pgno nFin;         /* Number of pages in database after autovacuuming */
50536     Pgno nFree;        /* Number of pages on the freelist initially */
50537     Pgno nPtrmap;      /* Number of PtrMap pages to be freed */
50538     Pgno iFree;        /* The next page to be freed */
50539     int nEntry;        /* Number of entries on one ptrmap page */
50540     Pgno nOrig;        /* Database size before freeing */
50541
50542     nOrig = btreePagecount(pBt);
50543     if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
50544       /* It is not possible to create a database for which the final page
50545       ** is either a pointer-map page or the pending-byte page. If one
50546       ** is encountered, this indicates corruption.
50547       */
50548       return SQLITE_CORRUPT_BKPT;
50549     }
50550
50551     nFree = get4byte(&pBt->pPage1->aData[36]);
50552     nEntry = pBt->usableSize/5;
50553     nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
50554     nFin = nOrig - nFree - nPtrmap;
50555     if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
50556       nFin--;
50557     }
50558     while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
50559       nFin--;
50560     }
50561     if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
50562
50563     for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
50564       rc = incrVacuumStep(pBt, nFin, iFree);
50565     }
50566     if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
50567       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
50568       put4byte(&pBt->pPage1->aData[32], 0);
50569       put4byte(&pBt->pPage1->aData[36], 0);
50570       put4byte(&pBt->pPage1->aData[28], nFin);
50571       sqlite3PagerTruncateImage(pBt->pPager, nFin);
50572       pBt->nPage = nFin;
50573     }
50574     if( rc!=SQLITE_OK ){
50575       sqlite3PagerRollback(pPager);
50576     }
50577   }
50578
50579   assert( nRef==sqlite3PagerRefcount(pPager) );
50580   return rc;
50581 }
50582
50583 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
50584 # define setChildPtrmaps(x) SQLITE_OK
50585 #endif
50586
50587 /*
50588 ** This routine does the first phase of a two-phase commit.  This routine
50589 ** causes a rollback journal to be created (if it does not already exist)
50590 ** and populated with enough information so that if a power loss occurs
50591 ** the database can be restored to its original state by playing back
50592 ** the journal.  Then the contents of the journal are flushed out to
50593 ** the disk.  After the journal is safely on oxide, the changes to the
50594 ** database are written into the database file and flushed to oxide.
50595 ** At the end of this call, the rollback journal still exists on the
50596 ** disk and we are still holding all locks, so the transaction has not
50597 ** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
50598 ** commit process.
50599 **
50600 ** This call is a no-op if no write-transaction is currently active on pBt.
50601 **
50602 ** Otherwise, sync the database file for the btree pBt. zMaster points to
50603 ** the name of a master journal file that should be written into the
50604 ** individual journal file, or is NULL, indicating no master journal file 
50605 ** (single database transaction).
50606 **
50607 ** When this is called, the master journal should already have been
50608 ** created, populated with this journal pointer and synced to disk.
50609 **
50610 ** Once this is routine has returned, the only thing required to commit
50611 ** the write-transaction for this database file is to delete the journal.
50612 */
50613 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
50614   int rc = SQLITE_OK;
50615   if( p->inTrans==TRANS_WRITE ){
50616     BtShared *pBt = p->pBt;
50617     sqlite3BtreeEnter(p);
50618 #ifndef SQLITE_OMIT_AUTOVACUUM
50619     if( pBt->autoVacuum ){
50620       rc = autoVacuumCommit(pBt);
50621       if( rc!=SQLITE_OK ){
50622         sqlite3BtreeLeave(p);
50623         return rc;
50624       }
50625     }
50626 #endif
50627     rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
50628     sqlite3BtreeLeave(p);
50629   }
50630   return rc;
50631 }
50632
50633 /*
50634 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
50635 ** at the conclusion of a transaction.
50636 */
50637 static void btreeEndTransaction(Btree *p){
50638   BtShared *pBt = p->pBt;
50639   assert( sqlite3BtreeHoldsMutex(p) );
50640
50641   btreeClearHasContent(pBt);
50642   if( p->inTrans>TRANS_NONE && p->db->activeVdbeCnt>1 ){
50643     /* If there are other active statements that belong to this database
50644     ** handle, downgrade to a read-only transaction. The other statements
50645     ** may still be reading from the database.  */
50646     downgradeAllSharedCacheTableLocks(p);
50647     p->inTrans = TRANS_READ;
50648   }else{
50649     /* If the handle had any kind of transaction open, decrement the 
50650     ** transaction count of the shared btree. If the transaction count 
50651     ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
50652     ** call below will unlock the pager.  */
50653     if( p->inTrans!=TRANS_NONE ){
50654       clearAllSharedCacheTableLocks(p);
50655       pBt->nTransaction--;
50656       if( 0==pBt->nTransaction ){
50657         pBt->inTransaction = TRANS_NONE;
50658       }
50659     }
50660
50661     /* Set the current transaction state to TRANS_NONE and unlock the 
50662     ** pager if this call closed the only read or write transaction.  */
50663     p->inTrans = TRANS_NONE;
50664     unlockBtreeIfUnused(pBt);
50665   }
50666
50667   btreeIntegrity(p);
50668 }
50669
50670 /*
50671 ** Commit the transaction currently in progress.
50672 **
50673 ** This routine implements the second phase of a 2-phase commit.  The
50674 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
50675 ** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
50676 ** routine did all the work of writing information out to disk and flushing the
50677 ** contents so that they are written onto the disk platter.  All this
50678 ** routine has to do is delete or truncate or zero the header in the
50679 ** the rollback journal (which causes the transaction to commit) and
50680 ** drop locks.
50681 **
50682 ** Normally, if an error occurs while the pager layer is attempting to 
50683 ** finalize the underlying journal file, this function returns an error and
50684 ** the upper layer will attempt a rollback. However, if the second argument
50685 ** is non-zero then this b-tree transaction is part of a multi-file 
50686 ** transaction. In this case, the transaction has already been committed 
50687 ** (by deleting a master journal file) and the caller will ignore this 
50688 ** functions return code. So, even if an error occurs in the pager layer,
50689 ** reset the b-tree objects internal state to indicate that the write
50690 ** transaction has been closed. This is quite safe, as the pager will have
50691 ** transitioned to the error state.
50692 **
50693 ** This will release the write lock on the database file.  If there
50694 ** are no active cursors, it also releases the read lock.
50695 */
50696 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
50697
50698   if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
50699   sqlite3BtreeEnter(p);
50700   btreeIntegrity(p);
50701
50702   /* If the handle has a write-transaction open, commit the shared-btrees 
50703   ** transaction and set the shared state to TRANS_READ.
50704   */
50705   if( p->inTrans==TRANS_WRITE ){
50706     int rc;
50707     BtShared *pBt = p->pBt;
50708     assert( pBt->inTransaction==TRANS_WRITE );
50709     assert( pBt->nTransaction>0 );
50710     rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
50711     if( rc!=SQLITE_OK && bCleanup==0 ){
50712       sqlite3BtreeLeave(p);
50713       return rc;
50714     }
50715     pBt->inTransaction = TRANS_READ;
50716   }
50717
50718   btreeEndTransaction(p);
50719   sqlite3BtreeLeave(p);
50720   return SQLITE_OK;
50721 }
50722
50723 /*
50724 ** Do both phases of a commit.
50725 */
50726 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
50727   int rc;
50728   sqlite3BtreeEnter(p);
50729   rc = sqlite3BtreeCommitPhaseOne(p, 0);
50730   if( rc==SQLITE_OK ){
50731     rc = sqlite3BtreeCommitPhaseTwo(p, 0);
50732   }
50733   sqlite3BtreeLeave(p);
50734   return rc;
50735 }
50736
50737 #ifndef NDEBUG
50738 /*
50739 ** Return the number of write-cursors open on this handle. This is for use
50740 ** in assert() expressions, so it is only compiled if NDEBUG is not
50741 ** defined.
50742 **
50743 ** For the purposes of this routine, a write-cursor is any cursor that
50744 ** is capable of writing to the databse.  That means the cursor was
50745 ** originally opened for writing and the cursor has not be disabled
50746 ** by having its state changed to CURSOR_FAULT.
50747 */
50748 static int countWriteCursors(BtShared *pBt){
50749   BtCursor *pCur;
50750   int r = 0;
50751   for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
50752     if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++; 
50753   }
50754   return r;
50755 }
50756 #endif
50757
50758 /*
50759 ** This routine sets the state to CURSOR_FAULT and the error
50760 ** code to errCode for every cursor on BtShared that pBtree
50761 ** references.
50762 **
50763 ** Every cursor is tripped, including cursors that belong
50764 ** to other database connections that happen to be sharing
50765 ** the cache with pBtree.
50766 **
50767 ** This routine gets called when a rollback occurs.
50768 ** All cursors using the same cache must be tripped
50769 ** to prevent them from trying to use the btree after
50770 ** the rollback.  The rollback may have deleted tables
50771 ** or moved root pages, so it is not sufficient to
50772 ** save the state of the cursor.  The cursor must be
50773 ** invalidated.
50774 */
50775 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
50776   BtCursor *p;
50777   sqlite3BtreeEnter(pBtree);
50778   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
50779     int i;
50780     sqlite3BtreeClearCursor(p);
50781     p->eState = CURSOR_FAULT;
50782     p->skipNext = errCode;
50783     for(i=0; i<=p->iPage; i++){
50784       releasePage(p->apPage[i]);
50785       p->apPage[i] = 0;
50786     }
50787   }
50788   sqlite3BtreeLeave(pBtree);
50789 }
50790
50791 /*
50792 ** Rollback the transaction in progress.  All cursors will be
50793 ** invalided by this operation.  Any attempt to use a cursor
50794 ** that was open at the beginning of this operation will result
50795 ** in an error.
50796 **
50797 ** This will release the write lock on the database file.  If there
50798 ** are no active cursors, it also releases the read lock.
50799 */
50800 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p){
50801   int rc;
50802   BtShared *pBt = p->pBt;
50803   MemPage *pPage1;
50804
50805   sqlite3BtreeEnter(p);
50806   rc = saveAllCursors(pBt, 0, 0);
50807 #ifndef SQLITE_OMIT_SHARED_CACHE
50808   if( rc!=SQLITE_OK ){
50809     /* This is a horrible situation. An IO or malloc() error occurred whilst
50810     ** trying to save cursor positions. If this is an automatic rollback (as
50811     ** the result of a constraint, malloc() failure or IO error) then 
50812     ** the cache may be internally inconsistent (not contain valid trees) so
50813     ** we cannot simply return the error to the caller. Instead, abort 
50814     ** all queries that may be using any of the cursors that failed to save.
50815     */
50816     sqlite3BtreeTripAllCursors(p, rc);
50817   }
50818 #endif
50819   btreeIntegrity(p);
50820
50821   if( p->inTrans==TRANS_WRITE ){
50822     int rc2;
50823
50824     assert( TRANS_WRITE==pBt->inTransaction );
50825     rc2 = sqlite3PagerRollback(pBt->pPager);
50826     if( rc2!=SQLITE_OK ){
50827       rc = rc2;
50828     }
50829
50830     /* The rollback may have destroyed the pPage1->aData value.  So
50831     ** call btreeGetPage() on page 1 again to make
50832     ** sure pPage1->aData is set correctly. */
50833     if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
50834       int nPage = get4byte(28+(u8*)pPage1->aData);
50835       testcase( nPage==0 );
50836       if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
50837       testcase( pBt->nPage!=nPage );
50838       pBt->nPage = nPage;
50839       releasePage(pPage1);
50840     }
50841     assert( countWriteCursors(pBt)==0 );
50842     pBt->inTransaction = TRANS_READ;
50843   }
50844
50845   btreeEndTransaction(p);
50846   sqlite3BtreeLeave(p);
50847   return rc;
50848 }
50849
50850 /*
50851 ** Start a statement subtransaction. The subtransaction can can be rolled
50852 ** back independently of the main transaction. You must start a transaction 
50853 ** before starting a subtransaction. The subtransaction is ended automatically 
50854 ** if the main transaction commits or rolls back.
50855 **
50856 ** Statement subtransactions are used around individual SQL statements
50857 ** that are contained within a BEGIN...COMMIT block.  If a constraint
50858 ** error occurs within the statement, the effect of that one statement
50859 ** can be rolled back without having to rollback the entire transaction.
50860 **
50861 ** A statement sub-transaction is implemented as an anonymous savepoint. The
50862 ** value passed as the second parameter is the total number of savepoints,
50863 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
50864 ** are no active savepoints and no other statement-transactions open,
50865 ** iStatement is 1. This anonymous savepoint can be released or rolled back
50866 ** using the sqlite3BtreeSavepoint() function.
50867 */
50868 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
50869   int rc;
50870   BtShared *pBt = p->pBt;
50871   sqlite3BtreeEnter(p);
50872   assert( p->inTrans==TRANS_WRITE );
50873   assert( pBt->readOnly==0 );
50874   assert( iStatement>0 );
50875   assert( iStatement>p->db->nSavepoint );
50876   assert( pBt->inTransaction==TRANS_WRITE );
50877   /* At the pager level, a statement transaction is a savepoint with
50878   ** an index greater than all savepoints created explicitly using
50879   ** SQL statements. It is illegal to open, release or rollback any
50880   ** such savepoints while the statement transaction savepoint is active.
50881   */
50882   rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
50883   sqlite3BtreeLeave(p);
50884   return rc;
50885 }
50886
50887 /*
50888 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
50889 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
50890 ** savepoint identified by parameter iSavepoint, depending on the value 
50891 ** of op.
50892 **
50893 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
50894 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the 
50895 ** contents of the entire transaction are rolled back. This is different
50896 ** from a normal transaction rollback, as no locks are released and the
50897 ** transaction remains open.
50898 */
50899 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
50900   int rc = SQLITE_OK;
50901   if( p && p->inTrans==TRANS_WRITE ){
50902     BtShared *pBt = p->pBt;
50903     assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
50904     assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
50905     sqlite3BtreeEnter(p);
50906     rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
50907     if( rc==SQLITE_OK ){
50908       if( iSavepoint<0 && pBt->initiallyEmpty ) pBt->nPage = 0;
50909       rc = newDatabase(pBt);
50910       pBt->nPage = get4byte(28 + pBt->pPage1->aData);
50911
50912       /* The database size was written into the offset 28 of the header
50913       ** when the transaction started, so we know that the value at offset
50914       ** 28 is nonzero. */
50915       assert( pBt->nPage>0 );
50916     }
50917     sqlite3BtreeLeave(p);
50918   }
50919   return rc;
50920 }
50921
50922 /*
50923 ** Create a new cursor for the BTree whose root is on the page
50924 ** iTable. If a read-only cursor is requested, it is assumed that
50925 ** the caller already has at least a read-only transaction open
50926 ** on the database already. If a write-cursor is requested, then
50927 ** the caller is assumed to have an open write transaction.
50928 **
50929 ** If wrFlag==0, then the cursor can only be used for reading.
50930 ** If wrFlag==1, then the cursor can be used for reading or for
50931 ** writing if other conditions for writing are also met.  These
50932 ** are the conditions that must be met in order for writing to
50933 ** be allowed:
50934 **
50935 ** 1:  The cursor must have been opened with wrFlag==1
50936 **
50937 ** 2:  Other database connections that share the same pager cache
50938 **     but which are not in the READ_UNCOMMITTED state may not have
50939 **     cursors open with wrFlag==0 on the same table.  Otherwise
50940 **     the changes made by this write cursor would be visible to
50941 **     the read cursors in the other database connection.
50942 **
50943 ** 3:  The database must be writable (not on read-only media)
50944 **
50945 ** 4:  There must be an active transaction.
50946 **
50947 ** No checking is done to make sure that page iTable really is the
50948 ** root page of a b-tree.  If it is not, then the cursor acquired
50949 ** will not work correctly.
50950 **
50951 ** It is assumed that the sqlite3BtreeCursorZero() has been called
50952 ** on pCur to initialize the memory space prior to invoking this routine.
50953 */
50954 static int btreeCursor(
50955   Btree *p,                              /* The btree */
50956   int iTable,                            /* Root page of table to open */
50957   int wrFlag,                            /* 1 to write. 0 read-only */
50958   struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
50959   BtCursor *pCur                         /* Space for new cursor */
50960 ){
50961   BtShared *pBt = p->pBt;                /* Shared b-tree handle */
50962
50963   assert( sqlite3BtreeHoldsMutex(p) );
50964   assert( wrFlag==0 || wrFlag==1 );
50965
50966   /* The following assert statements verify that if this is a sharable 
50967   ** b-tree database, the connection is holding the required table locks, 
50968   ** and that no other connection has any open cursor that conflicts with 
50969   ** this lock.  */
50970   assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
50971   assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
50972
50973   /* Assert that the caller has opened the required transaction. */
50974   assert( p->inTrans>TRANS_NONE );
50975   assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
50976   assert( pBt->pPage1 && pBt->pPage1->aData );
50977
50978   if( NEVER(wrFlag && pBt->readOnly) ){
50979     return SQLITE_READONLY;
50980   }
50981   if( iTable==1 && btreePagecount(pBt)==0 ){
50982     return SQLITE_EMPTY;
50983   }
50984
50985   /* Now that no other errors can occur, finish filling in the BtCursor
50986   ** variables and link the cursor into the BtShared list.  */
50987   pCur->pgnoRoot = (Pgno)iTable;
50988   pCur->iPage = -1;
50989   pCur->pKeyInfo = pKeyInfo;
50990   pCur->pBtree = p;
50991   pCur->pBt = pBt;
50992   pCur->wrFlag = (u8)wrFlag;
50993   pCur->pNext = pBt->pCursor;
50994   if( pCur->pNext ){
50995     pCur->pNext->pPrev = pCur;
50996   }
50997   pBt->pCursor = pCur;
50998   pCur->eState = CURSOR_INVALID;
50999   pCur->cachedRowid = 0;
51000   return SQLITE_OK;
51001 }
51002 SQLITE_PRIVATE int sqlite3BtreeCursor(
51003   Btree *p,                                   /* The btree */
51004   int iTable,                                 /* Root page of table to open */
51005   int wrFlag,                                 /* 1 to write. 0 read-only */
51006   struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
51007   BtCursor *pCur                              /* Write new cursor here */
51008 ){
51009   int rc;
51010   sqlite3BtreeEnter(p);
51011   rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
51012   sqlite3BtreeLeave(p);
51013   return rc;
51014 }
51015
51016 /*
51017 ** Return the size of a BtCursor object in bytes.
51018 **
51019 ** This interfaces is needed so that users of cursors can preallocate
51020 ** sufficient storage to hold a cursor.  The BtCursor object is opaque
51021 ** to users so they cannot do the sizeof() themselves - they must call
51022 ** this routine.
51023 */
51024 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
51025   return ROUND8(sizeof(BtCursor));
51026 }
51027
51028 /*
51029 ** Initialize memory that will be converted into a BtCursor object.
51030 **
51031 ** The simple approach here would be to memset() the entire object
51032 ** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
51033 ** do not need to be zeroed and they are large, so we can save a lot
51034 ** of run-time by skipping the initialization of those elements.
51035 */
51036 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
51037   memset(p, 0, offsetof(BtCursor, iPage));
51038 }
51039
51040 /*
51041 ** Set the cached rowid value of every cursor in the same database file
51042 ** as pCur and having the same root page number as pCur.  The value is
51043 ** set to iRowid.
51044 **
51045 ** Only positive rowid values are considered valid for this cache.
51046 ** The cache is initialized to zero, indicating an invalid cache.
51047 ** A btree will work fine with zero or negative rowids.  We just cannot
51048 ** cache zero or negative rowids, which means tables that use zero or
51049 ** negative rowids might run a little slower.  But in practice, zero
51050 ** or negative rowids are very uncommon so this should not be a problem.
51051 */
51052 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
51053   BtCursor *p;
51054   for(p=pCur->pBt->pCursor; p; p=p->pNext){
51055     if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
51056   }
51057   assert( pCur->cachedRowid==iRowid );
51058 }
51059
51060 /*
51061 ** Return the cached rowid for the given cursor.  A negative or zero
51062 ** return value indicates that the rowid cache is invalid and should be
51063 ** ignored.  If the rowid cache has never before been set, then a
51064 ** zero is returned.
51065 */
51066 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
51067   return pCur->cachedRowid;
51068 }
51069
51070 /*
51071 ** Close a cursor.  The read lock on the database file is released
51072 ** when the last cursor is closed.
51073 */
51074 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
51075   Btree *pBtree = pCur->pBtree;
51076   if( pBtree ){
51077     int i;
51078     BtShared *pBt = pCur->pBt;
51079     sqlite3BtreeEnter(pBtree);
51080     sqlite3BtreeClearCursor(pCur);
51081     if( pCur->pPrev ){
51082       pCur->pPrev->pNext = pCur->pNext;
51083     }else{
51084       pBt->pCursor = pCur->pNext;
51085     }
51086     if( pCur->pNext ){
51087       pCur->pNext->pPrev = pCur->pPrev;
51088     }
51089     for(i=0; i<=pCur->iPage; i++){
51090       releasePage(pCur->apPage[i]);
51091     }
51092     unlockBtreeIfUnused(pBt);
51093     invalidateOverflowCache(pCur);
51094     /* sqlite3_free(pCur); */
51095     sqlite3BtreeLeave(pBtree);
51096   }
51097   return SQLITE_OK;
51098 }
51099
51100 /*
51101 ** Make sure the BtCursor* given in the argument has a valid
51102 ** BtCursor.info structure.  If it is not already valid, call
51103 ** btreeParseCell() to fill it in.
51104 **
51105 ** BtCursor.info is a cache of the information in the current cell.
51106 ** Using this cache reduces the number of calls to btreeParseCell().
51107 **
51108 ** 2007-06-25:  There is a bug in some versions of MSVC that cause the
51109 ** compiler to crash when getCellInfo() is implemented as a macro.
51110 ** But there is a measureable speed advantage to using the macro on gcc
51111 ** (when less compiler optimizations like -Os or -O0 are used and the
51112 ** compiler is not doing agressive inlining.)  So we use a real function
51113 ** for MSVC and a macro for everything else.  Ticket #2457.
51114 */
51115 #ifndef NDEBUG
51116   static void assertCellInfo(BtCursor *pCur){
51117     CellInfo info;
51118     int iPage = pCur->iPage;
51119     memset(&info, 0, sizeof(info));
51120     btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
51121     assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
51122   }
51123 #else
51124   #define assertCellInfo(x)
51125 #endif
51126 #ifdef _MSC_VER
51127   /* Use a real function in MSVC to work around bugs in that compiler. */
51128   static void getCellInfo(BtCursor *pCur){
51129     if( pCur->info.nSize==0 ){
51130       int iPage = pCur->iPage;
51131       btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
51132       pCur->validNKey = 1;
51133     }else{
51134       assertCellInfo(pCur);
51135     }
51136   }
51137 #else /* if not _MSC_VER */
51138   /* Use a macro in all other compilers so that the function is inlined */
51139 #define getCellInfo(pCur)                                                      \
51140   if( pCur->info.nSize==0 ){                                                   \
51141     int iPage = pCur->iPage;                                                   \
51142     btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
51143     pCur->validNKey = 1;                                                       \
51144   }else{                                                                       \
51145     assertCellInfo(pCur);                                                      \
51146   }
51147 #endif /* _MSC_VER */
51148
51149 #ifndef NDEBUG  /* The next routine used only within assert() statements */
51150 /*
51151 ** Return true if the given BtCursor is valid.  A valid cursor is one
51152 ** that is currently pointing to a row in a (non-empty) table.
51153 ** This is a verification routine is used only within assert() statements.
51154 */
51155 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
51156   return pCur && pCur->eState==CURSOR_VALID;
51157 }
51158 #endif /* NDEBUG */
51159
51160 /*
51161 ** Set *pSize to the size of the buffer needed to hold the value of
51162 ** the key for the current entry.  If the cursor is not pointing
51163 ** to a valid entry, *pSize is set to 0. 
51164 **
51165 ** For a table with the INTKEY flag set, this routine returns the key
51166 ** itself, not the number of bytes in the key.
51167 **
51168 ** The caller must position the cursor prior to invoking this routine.
51169 ** 
51170 ** This routine cannot fail.  It always returns SQLITE_OK.  
51171 */
51172 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
51173   assert( cursorHoldsMutex(pCur) );
51174   assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
51175   if( pCur->eState!=CURSOR_VALID ){
51176     *pSize = 0;
51177   }else{
51178     getCellInfo(pCur);
51179     *pSize = pCur->info.nKey;
51180   }
51181   return SQLITE_OK;
51182 }
51183
51184 /*
51185 ** Set *pSize to the number of bytes of data in the entry the
51186 ** cursor currently points to.
51187 **
51188 ** The caller must guarantee that the cursor is pointing to a non-NULL
51189 ** valid entry.  In other words, the calling procedure must guarantee
51190 ** that the cursor has Cursor.eState==CURSOR_VALID.
51191 **
51192 ** Failure is not possible.  This function always returns SQLITE_OK.
51193 ** It might just as well be a procedure (returning void) but we continue
51194 ** to return an integer result code for historical reasons.
51195 */
51196 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
51197   assert( cursorHoldsMutex(pCur) );
51198   assert( pCur->eState==CURSOR_VALID );
51199   getCellInfo(pCur);
51200   *pSize = pCur->info.nData;
51201   return SQLITE_OK;
51202 }
51203
51204 /*
51205 ** Given the page number of an overflow page in the database (parameter
51206 ** ovfl), this function finds the page number of the next page in the 
51207 ** linked list of overflow pages. If possible, it uses the auto-vacuum
51208 ** pointer-map data instead of reading the content of page ovfl to do so. 
51209 **
51210 ** If an error occurs an SQLite error code is returned. Otherwise:
51211 **
51212 ** The page number of the next overflow page in the linked list is 
51213 ** written to *pPgnoNext. If page ovfl is the last page in its linked 
51214 ** list, *pPgnoNext is set to zero. 
51215 **
51216 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
51217 ** to page number pOvfl was obtained, then *ppPage is set to point to that
51218 ** reference. It is the responsibility of the caller to call releasePage()
51219 ** on *ppPage to free the reference. In no reference was obtained (because
51220 ** the pointer-map was used to obtain the value for *pPgnoNext), then
51221 ** *ppPage is set to zero.
51222 */
51223 static int getOverflowPage(
51224   BtShared *pBt,               /* The database file */
51225   Pgno ovfl,                   /* Current overflow page number */
51226   MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
51227   Pgno *pPgnoNext              /* OUT: Next overflow page number */
51228 ){
51229   Pgno next = 0;
51230   MemPage *pPage = 0;
51231   int rc = SQLITE_OK;
51232
51233   assert( sqlite3_mutex_held(pBt->mutex) );
51234   assert(pPgnoNext);
51235
51236 #ifndef SQLITE_OMIT_AUTOVACUUM
51237   /* Try to find the next page in the overflow list using the
51238   ** autovacuum pointer-map pages. Guess that the next page in 
51239   ** the overflow list is page number (ovfl+1). If that guess turns 
51240   ** out to be wrong, fall back to loading the data of page 
51241   ** number ovfl to determine the next page number.
51242   */
51243   if( pBt->autoVacuum ){
51244     Pgno pgno;
51245     Pgno iGuess = ovfl+1;
51246     u8 eType;
51247
51248     while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
51249       iGuess++;
51250     }
51251
51252     if( iGuess<=btreePagecount(pBt) ){
51253       rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
51254       if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
51255         next = iGuess;
51256         rc = SQLITE_DONE;
51257       }
51258     }
51259   }
51260 #endif
51261
51262   assert( next==0 || rc==SQLITE_DONE );
51263   if( rc==SQLITE_OK ){
51264     rc = btreeGetPage(pBt, ovfl, &pPage, 0);
51265     assert( rc==SQLITE_OK || pPage==0 );
51266     if( rc==SQLITE_OK ){
51267       next = get4byte(pPage->aData);
51268     }
51269   }
51270
51271   *pPgnoNext = next;
51272   if( ppPage ){
51273     *ppPage = pPage;
51274   }else{
51275     releasePage(pPage);
51276   }
51277   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
51278 }
51279
51280 /*
51281 ** Copy data from a buffer to a page, or from a page to a buffer.
51282 **
51283 ** pPayload is a pointer to data stored on database page pDbPage.
51284 ** If argument eOp is false, then nByte bytes of data are copied
51285 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
51286 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
51287 ** of data are copied from the buffer pBuf to pPayload.
51288 **
51289 ** SQLITE_OK is returned on success, otherwise an error code.
51290 */
51291 static int copyPayload(
51292   void *pPayload,           /* Pointer to page data */
51293   void *pBuf,               /* Pointer to buffer */
51294   int nByte,                /* Number of bytes to copy */
51295   int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
51296   DbPage *pDbPage           /* Page containing pPayload */
51297 ){
51298   if( eOp ){
51299     /* Copy data from buffer to page (a write operation) */
51300     int rc = sqlite3PagerWrite(pDbPage);
51301     if( rc!=SQLITE_OK ){
51302       return rc;
51303     }
51304     memcpy(pPayload, pBuf, nByte);
51305   }else{
51306     /* Copy data from page to buffer (a read operation) */
51307     memcpy(pBuf, pPayload, nByte);
51308   }
51309   return SQLITE_OK;
51310 }
51311
51312 /*
51313 ** This function is used to read or overwrite payload information
51314 ** for the entry that the pCur cursor is pointing to. If the eOp
51315 ** parameter is 0, this is a read operation (data copied into
51316 ** buffer pBuf). If it is non-zero, a write (data copied from
51317 ** buffer pBuf).
51318 **
51319 ** A total of "amt" bytes are read or written beginning at "offset".
51320 ** Data is read to or from the buffer pBuf.
51321 **
51322 ** The content being read or written might appear on the main page
51323 ** or be scattered out on multiple overflow pages.
51324 **
51325 ** If the BtCursor.isIncrblobHandle flag is set, and the current
51326 ** cursor entry uses one or more overflow pages, this function
51327 ** allocates space for and lazily popluates the overflow page-list 
51328 ** cache array (BtCursor.aOverflow). Subsequent calls use this
51329 ** cache to make seeking to the supplied offset more efficient.
51330 **
51331 ** Once an overflow page-list cache has been allocated, it may be
51332 ** invalidated if some other cursor writes to the same table, or if
51333 ** the cursor is moved to a different row. Additionally, in auto-vacuum
51334 ** mode, the following events may invalidate an overflow page-list cache.
51335 **
51336 **   * An incremental vacuum,
51337 **   * A commit in auto_vacuum="full" mode,
51338 **   * Creating a table (may require moving an overflow page).
51339 */
51340 static int accessPayload(
51341   BtCursor *pCur,      /* Cursor pointing to entry to read from */
51342   u32 offset,          /* Begin reading this far into payload */
51343   u32 amt,             /* Read this many bytes */
51344   unsigned char *pBuf, /* Write the bytes into this buffer */ 
51345   int eOp              /* zero to read. non-zero to write. */
51346 ){
51347   unsigned char *aPayload;
51348   int rc = SQLITE_OK;
51349   u32 nKey;
51350   int iIdx = 0;
51351   MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
51352   BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
51353
51354   assert( pPage );
51355   assert( pCur->eState==CURSOR_VALID );
51356   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
51357   assert( cursorHoldsMutex(pCur) );
51358
51359   getCellInfo(pCur);
51360   aPayload = pCur->info.pCell + pCur->info.nHeader;
51361   nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
51362
51363   if( NEVER(offset+amt > nKey+pCur->info.nData) 
51364    || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
51365   ){
51366     /* Trying to read or write past the end of the data is an error */
51367     return SQLITE_CORRUPT_BKPT;
51368   }
51369
51370   /* Check if data must be read/written to/from the btree page itself. */
51371   if( offset<pCur->info.nLocal ){
51372     int a = amt;
51373     if( a+offset>pCur->info.nLocal ){
51374       a = pCur->info.nLocal - offset;
51375     }
51376     rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
51377     offset = 0;
51378     pBuf += a;
51379     amt -= a;
51380   }else{
51381     offset -= pCur->info.nLocal;
51382   }
51383
51384   if( rc==SQLITE_OK && amt>0 ){
51385     const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
51386     Pgno nextPage;
51387
51388     nextPage = get4byte(&aPayload[pCur->info.nLocal]);
51389
51390 #ifndef SQLITE_OMIT_INCRBLOB
51391     /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
51392     ** has not been allocated, allocate it now. The array is sized at
51393     ** one entry for each overflow page in the overflow chain. The
51394     ** page number of the first overflow page is stored in aOverflow[0],
51395     ** etc. A value of 0 in the aOverflow[] array means "not yet known"
51396     ** (the cache is lazily populated).
51397     */
51398     if( pCur->isIncrblobHandle && !pCur->aOverflow ){
51399       int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
51400       pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
51401       /* nOvfl is always positive.  If it were zero, fetchPayload would have
51402       ** been used instead of this routine. */
51403       if( ALWAYS(nOvfl) && !pCur->aOverflow ){
51404         rc = SQLITE_NOMEM;
51405       }
51406     }
51407
51408     /* If the overflow page-list cache has been allocated and the
51409     ** entry for the first required overflow page is valid, skip
51410     ** directly to it.
51411     */
51412     if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
51413       iIdx = (offset/ovflSize);
51414       nextPage = pCur->aOverflow[iIdx];
51415       offset = (offset%ovflSize);
51416     }
51417 #endif
51418
51419     for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
51420
51421 #ifndef SQLITE_OMIT_INCRBLOB
51422       /* If required, populate the overflow page-list cache. */
51423       if( pCur->aOverflow ){
51424         assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
51425         pCur->aOverflow[iIdx] = nextPage;
51426       }
51427 #endif
51428
51429       if( offset>=ovflSize ){
51430         /* The only reason to read this page is to obtain the page
51431         ** number for the next page in the overflow chain. The page
51432         ** data is not required. So first try to lookup the overflow
51433         ** page-list cache, if any, then fall back to the getOverflowPage()
51434         ** function.
51435         */
51436 #ifndef SQLITE_OMIT_INCRBLOB
51437         if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
51438           nextPage = pCur->aOverflow[iIdx+1];
51439         } else 
51440 #endif
51441           rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
51442         offset -= ovflSize;
51443       }else{
51444         /* Need to read this page properly. It contains some of the
51445         ** range of data that is being read (eOp==0) or written (eOp!=0).
51446         */
51447         DbPage *pDbPage;
51448         int a = amt;
51449         rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
51450         if( rc==SQLITE_OK ){
51451           aPayload = sqlite3PagerGetData(pDbPage);
51452           nextPage = get4byte(aPayload);
51453           if( a + offset > ovflSize ){
51454             a = ovflSize - offset;
51455           }
51456           rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
51457           sqlite3PagerUnref(pDbPage);
51458           offset = 0;
51459           amt -= a;
51460           pBuf += a;
51461         }
51462       }
51463     }
51464   }
51465
51466   if( rc==SQLITE_OK && amt>0 ){
51467     return SQLITE_CORRUPT_BKPT;
51468   }
51469   return rc;
51470 }
51471
51472 /*
51473 ** Read part of the key associated with cursor pCur.  Exactly
51474 ** "amt" bytes will be transfered into pBuf[].  The transfer
51475 ** begins at "offset".
51476 **
51477 ** The caller must ensure that pCur is pointing to a valid row
51478 ** in the table.
51479 **
51480 ** Return SQLITE_OK on success or an error code if anything goes
51481 ** wrong.  An error is returned if "offset+amt" is larger than
51482 ** the available payload.
51483 */
51484 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
51485   assert( cursorHoldsMutex(pCur) );
51486   assert( pCur->eState==CURSOR_VALID );
51487   assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
51488   assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
51489   return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
51490 }
51491
51492 /*
51493 ** Read part of the data associated with cursor pCur.  Exactly
51494 ** "amt" bytes will be transfered into pBuf[].  The transfer
51495 ** begins at "offset".
51496 **
51497 ** Return SQLITE_OK on success or an error code if anything goes
51498 ** wrong.  An error is returned if "offset+amt" is larger than
51499 ** the available payload.
51500 */
51501 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
51502   int rc;
51503
51504 #ifndef SQLITE_OMIT_INCRBLOB
51505   if ( pCur->eState==CURSOR_INVALID ){
51506     return SQLITE_ABORT;
51507   }
51508 #endif
51509
51510   assert( cursorHoldsMutex(pCur) );
51511   rc = restoreCursorPosition(pCur);
51512   if( rc==SQLITE_OK ){
51513     assert( pCur->eState==CURSOR_VALID );
51514     assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
51515     assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
51516     rc = accessPayload(pCur, offset, amt, pBuf, 0);
51517   }
51518   return rc;
51519 }
51520
51521 /*
51522 ** Return a pointer to payload information from the entry that the 
51523 ** pCur cursor is pointing to.  The pointer is to the beginning of
51524 ** the key if skipKey==0 and it points to the beginning of data if
51525 ** skipKey==1.  The number of bytes of available key/data is written
51526 ** into *pAmt.  If *pAmt==0, then the value returned will not be
51527 ** a valid pointer.
51528 **
51529 ** This routine is an optimization.  It is common for the entire key
51530 ** and data to fit on the local page and for there to be no overflow
51531 ** pages.  When that is so, this routine can be used to access the
51532 ** key and data without making a copy.  If the key and/or data spills
51533 ** onto overflow pages, then accessPayload() must be used to reassemble
51534 ** the key/data and copy it into a preallocated buffer.
51535 **
51536 ** The pointer returned by this routine looks directly into the cached
51537 ** page of the database.  The data might change or move the next time
51538 ** any btree routine is called.
51539 */
51540 static const unsigned char *fetchPayload(
51541   BtCursor *pCur,      /* Cursor pointing to entry to read from */
51542   int *pAmt,           /* Write the number of available bytes here */
51543   int skipKey          /* read beginning at data if this is true */
51544 ){
51545   unsigned char *aPayload;
51546   MemPage *pPage;
51547   u32 nKey;
51548   u32 nLocal;
51549
51550   assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
51551   assert( pCur->eState==CURSOR_VALID );
51552   assert( cursorHoldsMutex(pCur) );
51553   pPage = pCur->apPage[pCur->iPage];
51554   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
51555   if( NEVER(pCur->info.nSize==0) ){
51556     btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
51557                    &pCur->info);
51558   }
51559   aPayload = pCur->info.pCell;
51560   aPayload += pCur->info.nHeader;
51561   if( pPage->intKey ){
51562     nKey = 0;
51563   }else{
51564     nKey = (int)pCur->info.nKey;
51565   }
51566   if( skipKey ){
51567     aPayload += nKey;
51568     nLocal = pCur->info.nLocal - nKey;
51569   }else{
51570     nLocal = pCur->info.nLocal;
51571     assert( nLocal<=nKey );
51572   }
51573   *pAmt = nLocal;
51574   return aPayload;
51575 }
51576
51577
51578 /*
51579 ** For the entry that cursor pCur is point to, return as
51580 ** many bytes of the key or data as are available on the local
51581 ** b-tree page.  Write the number of available bytes into *pAmt.
51582 **
51583 ** The pointer returned is ephemeral.  The key/data may move
51584 ** or be destroyed on the next call to any Btree routine,
51585 ** including calls from other threads against the same cache.
51586 ** Hence, a mutex on the BtShared should be held prior to calling
51587 ** this routine.
51588 **
51589 ** These routines is used to get quick access to key and data
51590 ** in the common case where no overflow pages are used.
51591 */
51592 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
51593   const void *p = 0;
51594   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
51595   assert( cursorHoldsMutex(pCur) );
51596   if( ALWAYS(pCur->eState==CURSOR_VALID) ){
51597     p = (const void*)fetchPayload(pCur, pAmt, 0);
51598   }
51599   return p;
51600 }
51601 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
51602   const void *p = 0;
51603   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
51604   assert( cursorHoldsMutex(pCur) );
51605   if( ALWAYS(pCur->eState==CURSOR_VALID) ){
51606     p = (const void*)fetchPayload(pCur, pAmt, 1);
51607   }
51608   return p;
51609 }
51610
51611
51612 /*
51613 ** Move the cursor down to a new child page.  The newPgno argument is the
51614 ** page number of the child page to move to.
51615 **
51616 ** This function returns SQLITE_CORRUPT if the page-header flags field of
51617 ** the new child page does not match the flags field of the parent (i.e.
51618 ** if an intkey page appears to be the parent of a non-intkey page, or
51619 ** vice-versa).
51620 */
51621 static int moveToChild(BtCursor *pCur, u32 newPgno){
51622   int rc;
51623   int i = pCur->iPage;
51624   MemPage *pNewPage;
51625   BtShared *pBt = pCur->pBt;
51626
51627   assert( cursorHoldsMutex(pCur) );
51628   assert( pCur->eState==CURSOR_VALID );
51629   assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
51630   if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
51631     return SQLITE_CORRUPT_BKPT;
51632   }
51633   rc = getAndInitPage(pBt, newPgno, &pNewPage);
51634   if( rc ) return rc;
51635   pCur->apPage[i+1] = pNewPage;
51636   pCur->aiIdx[i+1] = 0;
51637   pCur->iPage++;
51638
51639   pCur->info.nSize = 0;
51640   pCur->validNKey = 0;
51641   if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
51642     return SQLITE_CORRUPT_BKPT;
51643   }
51644   return SQLITE_OK;
51645 }
51646
51647 #ifndef NDEBUG
51648 /*
51649 ** Page pParent is an internal (non-leaf) tree page. This function 
51650 ** asserts that page number iChild is the left-child if the iIdx'th
51651 ** cell in page pParent. Or, if iIdx is equal to the total number of
51652 ** cells in pParent, that page number iChild is the right-child of
51653 ** the page.
51654 */
51655 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
51656   assert( iIdx<=pParent->nCell );
51657   if( iIdx==pParent->nCell ){
51658     assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
51659   }else{
51660     assert( get4byte(findCell(pParent, iIdx))==iChild );
51661   }
51662 }
51663 #else
51664 #  define assertParentIndex(x,y,z) 
51665 #endif
51666
51667 /*
51668 ** Move the cursor up to the parent page.
51669 **
51670 ** pCur->idx is set to the cell index that contains the pointer
51671 ** to the page we are coming from.  If we are coming from the
51672 ** right-most child page then pCur->idx is set to one more than
51673 ** the largest cell index.
51674 */
51675 static void moveToParent(BtCursor *pCur){
51676   assert( cursorHoldsMutex(pCur) );
51677   assert( pCur->eState==CURSOR_VALID );
51678   assert( pCur->iPage>0 );
51679   assert( pCur->apPage[pCur->iPage] );
51680   assertParentIndex(
51681     pCur->apPage[pCur->iPage-1], 
51682     pCur->aiIdx[pCur->iPage-1], 
51683     pCur->apPage[pCur->iPage]->pgno
51684   );
51685   releasePage(pCur->apPage[pCur->iPage]);
51686   pCur->iPage--;
51687   pCur->info.nSize = 0;
51688   pCur->validNKey = 0;
51689 }
51690
51691 /*
51692 ** Move the cursor to point to the root page of its b-tree structure.
51693 **
51694 ** If the table has a virtual root page, then the cursor is moved to point
51695 ** to the virtual root page instead of the actual root page. A table has a
51696 ** virtual root page when the actual root page contains no cells and a 
51697 ** single child page. This can only happen with the table rooted at page 1.
51698 **
51699 ** If the b-tree structure is empty, the cursor state is set to 
51700 ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
51701 ** cell located on the root (or virtual root) page and the cursor state
51702 ** is set to CURSOR_VALID.
51703 **
51704 ** If this function returns successfully, it may be assumed that the
51705 ** page-header flags indicate that the [virtual] root-page is the expected 
51706 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
51707 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
51708 ** indicating a table b-tree, or if the caller did specify a KeyInfo 
51709 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
51710 ** b-tree).
51711 */
51712 static int moveToRoot(BtCursor *pCur){
51713   MemPage *pRoot;
51714   int rc = SQLITE_OK;
51715   Btree *p = pCur->pBtree;
51716   BtShared *pBt = p->pBt;
51717
51718   assert( cursorHoldsMutex(pCur) );
51719   assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
51720   assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
51721   assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
51722   if( pCur->eState>=CURSOR_REQUIRESEEK ){
51723     if( pCur->eState==CURSOR_FAULT ){
51724       assert( pCur->skipNext!=SQLITE_OK );
51725       return pCur->skipNext;
51726     }
51727     sqlite3BtreeClearCursor(pCur);
51728   }
51729
51730   if( pCur->iPage>=0 ){
51731     int i;
51732     for(i=1; i<=pCur->iPage; i++){
51733       releasePage(pCur->apPage[i]);
51734     }
51735     pCur->iPage = 0;
51736   }else{
51737     rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
51738     if( rc!=SQLITE_OK ){
51739       pCur->eState = CURSOR_INVALID;
51740       return rc;
51741     }
51742     pCur->iPage = 0;
51743
51744     /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
51745     ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
51746     ** NULL, the caller expects a table b-tree. If this is not the case,
51747     ** return an SQLITE_CORRUPT error.  */
51748     assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );
51749     if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){
51750       return SQLITE_CORRUPT_BKPT;
51751     }
51752   }
51753
51754   /* Assert that the root page is of the correct type. This must be the
51755   ** case as the call to this function that loaded the root-page (either
51756   ** this call or a previous invocation) would have detected corruption 
51757   ** if the assumption were not true, and it is not possible for the flags 
51758   ** byte to have been modified while this cursor is holding a reference
51759   ** to the page.  */
51760   pRoot = pCur->apPage[0];
51761   assert( pRoot->pgno==pCur->pgnoRoot );
51762   assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );
51763
51764   pCur->aiIdx[0] = 0;
51765   pCur->info.nSize = 0;
51766   pCur->atLast = 0;
51767   pCur->validNKey = 0;
51768
51769   if( pRoot->nCell==0 && !pRoot->leaf ){
51770     Pgno subpage;
51771     if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
51772     subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
51773     pCur->eState = CURSOR_VALID;
51774     rc = moveToChild(pCur, subpage);
51775   }else{
51776     pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
51777   }
51778   return rc;
51779 }
51780
51781 /*
51782 ** Move the cursor down to the left-most leaf entry beneath the
51783 ** entry to which it is currently pointing.
51784 **
51785 ** The left-most leaf is the one with the smallest key - the first
51786 ** in ascending order.
51787 */
51788 static int moveToLeftmost(BtCursor *pCur){
51789   Pgno pgno;
51790   int rc = SQLITE_OK;
51791   MemPage *pPage;
51792
51793   assert( cursorHoldsMutex(pCur) );
51794   assert( pCur->eState==CURSOR_VALID );
51795   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
51796     assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
51797     pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
51798     rc = moveToChild(pCur, pgno);
51799   }
51800   return rc;
51801 }
51802
51803 /*
51804 ** Move the cursor down to the right-most leaf entry beneath the
51805 ** page to which it is currently pointing.  Notice the difference
51806 ** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
51807 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
51808 ** finds the right-most entry beneath the *page*.
51809 **
51810 ** The right-most entry is the one with the largest key - the last
51811 ** key in ascending order.
51812 */
51813 static int moveToRightmost(BtCursor *pCur){
51814   Pgno pgno;
51815   int rc = SQLITE_OK;
51816   MemPage *pPage = 0;
51817
51818   assert( cursorHoldsMutex(pCur) );
51819   assert( pCur->eState==CURSOR_VALID );
51820   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
51821     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
51822     pCur->aiIdx[pCur->iPage] = pPage->nCell;
51823     rc = moveToChild(pCur, pgno);
51824   }
51825   if( rc==SQLITE_OK ){
51826     pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
51827     pCur->info.nSize = 0;
51828     pCur->validNKey = 0;
51829   }
51830   return rc;
51831 }
51832
51833 /* Move the cursor to the first entry in the table.  Return SQLITE_OK
51834 ** on success.  Set *pRes to 0 if the cursor actually points to something
51835 ** or set *pRes to 1 if the table is empty.
51836 */
51837 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
51838   int rc;
51839
51840   assert( cursorHoldsMutex(pCur) );
51841   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
51842   rc = moveToRoot(pCur);
51843   if( rc==SQLITE_OK ){
51844     if( pCur->eState==CURSOR_INVALID ){
51845       assert( pCur->apPage[pCur->iPage]->nCell==0 );
51846       *pRes = 1;
51847     }else{
51848       assert( pCur->apPage[pCur->iPage]->nCell>0 );
51849       *pRes = 0;
51850       rc = moveToLeftmost(pCur);
51851     }
51852   }
51853   return rc;
51854 }
51855
51856 /* Move the cursor to the last entry in the table.  Return SQLITE_OK
51857 ** on success.  Set *pRes to 0 if the cursor actually points to something
51858 ** or set *pRes to 1 if the table is empty.
51859 */
51860 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
51861   int rc;
51862  
51863   assert( cursorHoldsMutex(pCur) );
51864   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
51865
51866   /* If the cursor already points to the last entry, this is a no-op. */
51867   if( CURSOR_VALID==pCur->eState && pCur->atLast ){
51868 #ifdef SQLITE_DEBUG
51869     /* This block serves to assert() that the cursor really does point 
51870     ** to the last entry in the b-tree. */
51871     int ii;
51872     for(ii=0; ii<pCur->iPage; ii++){
51873       assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
51874     }
51875     assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
51876     assert( pCur->apPage[pCur->iPage]->leaf );
51877 #endif
51878     return SQLITE_OK;
51879   }
51880
51881   rc = moveToRoot(pCur);
51882   if( rc==SQLITE_OK ){
51883     if( CURSOR_INVALID==pCur->eState ){
51884       assert( pCur->apPage[pCur->iPage]->nCell==0 );
51885       *pRes = 1;
51886     }else{
51887       assert( pCur->eState==CURSOR_VALID );
51888       *pRes = 0;
51889       rc = moveToRightmost(pCur);
51890       pCur->atLast = rc==SQLITE_OK ?1:0;
51891     }
51892   }
51893   return rc;
51894 }
51895
51896 /* Move the cursor so that it points to an entry near the key 
51897 ** specified by pIdxKey or intKey.   Return a success code.
51898 **
51899 ** For INTKEY tables, the intKey parameter is used.  pIdxKey 
51900 ** must be NULL.  For index tables, pIdxKey is used and intKey
51901 ** is ignored.
51902 **
51903 ** If an exact match is not found, then the cursor is always
51904 ** left pointing at a leaf page which would hold the entry if it
51905 ** were present.  The cursor might point to an entry that comes
51906 ** before or after the key.
51907 **
51908 ** An integer is written into *pRes which is the result of
51909 ** comparing the key with the entry to which the cursor is 
51910 ** pointing.  The meaning of the integer written into
51911 ** *pRes is as follows:
51912 **
51913 **     *pRes<0      The cursor is left pointing at an entry that
51914 **                  is smaller than intKey/pIdxKey or if the table is empty
51915 **                  and the cursor is therefore left point to nothing.
51916 **
51917 **     *pRes==0     The cursor is left pointing at an entry that
51918 **                  exactly matches intKey/pIdxKey.
51919 **
51920 **     *pRes>0      The cursor is left pointing at an entry that
51921 **                  is larger than intKey/pIdxKey.
51922 **
51923 */
51924 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
51925   BtCursor *pCur,          /* The cursor to be moved */
51926   UnpackedRecord *pIdxKey, /* Unpacked index key */
51927   i64 intKey,              /* The table key */
51928   int biasRight,           /* If true, bias the search to the high end */
51929   int *pRes                /* Write search results here */
51930 ){
51931   int rc;
51932
51933   assert( cursorHoldsMutex(pCur) );
51934   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
51935   assert( pRes );
51936   assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
51937
51938   /* If the cursor is already positioned at the point we are trying
51939   ** to move to, then just return without doing any work */
51940   if( pCur->eState==CURSOR_VALID && pCur->validNKey 
51941    && pCur->apPage[0]->intKey 
51942   ){
51943     if( pCur->info.nKey==intKey ){
51944       *pRes = 0;
51945       return SQLITE_OK;
51946     }
51947     if( pCur->atLast && pCur->info.nKey<intKey ){
51948       *pRes = -1;
51949       return SQLITE_OK;
51950     }
51951   }
51952
51953   rc = moveToRoot(pCur);
51954   if( rc ){
51955     return rc;
51956   }
51957   assert( pCur->apPage[pCur->iPage] );
51958   assert( pCur->apPage[pCur->iPage]->isInit );
51959   assert( pCur->apPage[pCur->iPage]->nCell>0 || pCur->eState==CURSOR_INVALID );
51960   if( pCur->eState==CURSOR_INVALID ){
51961     *pRes = -1;
51962     assert( pCur->apPage[pCur->iPage]->nCell==0 );
51963     return SQLITE_OK;
51964   }
51965   assert( pCur->apPage[0]->intKey || pIdxKey );
51966   for(;;){
51967     int lwr, upr, idx;
51968     Pgno chldPg;
51969     MemPage *pPage = pCur->apPage[pCur->iPage];
51970     int c;
51971
51972     /* pPage->nCell must be greater than zero. If this is the root-page
51973     ** the cursor would have been INVALID above and this for(;;) loop
51974     ** not run. If this is not the root-page, then the moveToChild() routine
51975     ** would have already detected db corruption. Similarly, pPage must
51976     ** be the right kind (index or table) of b-tree page. Otherwise
51977     ** a moveToChild() or moveToRoot() call would have detected corruption.  */
51978     assert( pPage->nCell>0 );
51979     assert( pPage->intKey==(pIdxKey==0) );
51980     lwr = 0;
51981     upr = pPage->nCell-1;
51982     if( biasRight ){
51983       pCur->aiIdx[pCur->iPage] = (u16)(idx = upr);
51984     }else{
51985       pCur->aiIdx[pCur->iPage] = (u16)(idx = (upr+lwr)/2);
51986     }
51987     for(;;){
51988       u8 *pCell;                          /* Pointer to current cell in pPage */
51989
51990       assert( idx==pCur->aiIdx[pCur->iPage] );
51991       pCur->info.nSize = 0;
51992       pCell = findCell(pPage, idx) + pPage->childPtrSize;
51993       if( pPage->intKey ){
51994         i64 nCellKey;
51995         if( pPage->hasData ){
51996           u32 dummy;
51997           pCell += getVarint32(pCell, dummy);
51998         }
51999         getVarint(pCell, (u64*)&nCellKey);
52000         if( nCellKey==intKey ){
52001           c = 0;
52002         }else if( nCellKey<intKey ){
52003           c = -1;
52004         }else{
52005           assert( nCellKey>intKey );
52006           c = +1;
52007         }
52008         pCur->validNKey = 1;
52009         pCur->info.nKey = nCellKey;
52010       }else{
52011         /* The maximum supported page-size is 65536 bytes. This means that
52012         ** the maximum number of record bytes stored on an index B-Tree
52013         ** page is less than 16384 bytes and may be stored as a 2-byte
52014         ** varint. This information is used to attempt to avoid parsing 
52015         ** the entire cell by checking for the cases where the record is 
52016         ** stored entirely within the b-tree page by inspecting the first 
52017         ** 2 bytes of the cell.
52018         */
52019         int nCell = pCell[0];
52020         if( !(nCell & 0x80) && nCell<=pPage->maxLocal ){
52021           /* This branch runs if the record-size field of the cell is a
52022           ** single byte varint and the record fits entirely on the main
52023           ** b-tree page.  */
52024           c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
52025         }else if( !(pCell[1] & 0x80) 
52026           && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
52027         ){
52028           /* The record-size field is a 2 byte varint and the record 
52029           ** fits entirely on the main b-tree page.  */
52030           c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
52031         }else{
52032           /* The record flows over onto one or more overflow pages. In
52033           ** this case the whole cell needs to be parsed, a buffer allocated
52034           ** and accessPayload() used to retrieve the record into the
52035           ** buffer before VdbeRecordCompare() can be called. */
52036           void *pCellKey;
52037           u8 * const pCellBody = pCell - pPage->childPtrSize;
52038           btreeParseCellPtr(pPage, pCellBody, &pCur->info);
52039           nCell = (int)pCur->info.nKey;
52040           pCellKey = sqlite3Malloc( nCell );
52041           if( pCellKey==0 ){
52042             rc = SQLITE_NOMEM;
52043             goto moveto_finish;
52044           }
52045           rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
52046           if( rc ){
52047             sqlite3_free(pCellKey);
52048             goto moveto_finish;
52049           }
52050           c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
52051           sqlite3_free(pCellKey);
52052         }
52053       }
52054       if( c==0 ){
52055         if( pPage->intKey && !pPage->leaf ){
52056           lwr = idx;
52057           upr = lwr - 1;
52058           break;
52059         }else{
52060           *pRes = 0;
52061           rc = SQLITE_OK;
52062           goto moveto_finish;
52063         }
52064       }
52065       if( c<0 ){
52066         lwr = idx+1;
52067       }else{
52068         upr = idx-1;
52069       }
52070       if( lwr>upr ){
52071         break;
52072       }
52073       pCur->aiIdx[pCur->iPage] = (u16)(idx = (lwr+upr)/2);
52074     }
52075     assert( lwr==upr+1 );
52076     assert( pPage->isInit );
52077     if( pPage->leaf ){
52078       chldPg = 0;
52079     }else if( lwr>=pPage->nCell ){
52080       chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
52081     }else{
52082       chldPg = get4byte(findCell(pPage, lwr));
52083     }
52084     if( chldPg==0 ){
52085       assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
52086       *pRes = c;
52087       rc = SQLITE_OK;
52088       goto moveto_finish;
52089     }
52090     pCur->aiIdx[pCur->iPage] = (u16)lwr;
52091     pCur->info.nSize = 0;
52092     pCur->validNKey = 0;
52093     rc = moveToChild(pCur, chldPg);
52094     if( rc ) goto moveto_finish;
52095   }
52096 moveto_finish:
52097   return rc;
52098 }
52099
52100
52101 /*
52102 ** Return TRUE if the cursor is not pointing at an entry of the table.
52103 **
52104 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
52105 ** past the last entry in the table or sqlite3BtreePrev() moves past
52106 ** the first entry.  TRUE is also returned if the table is empty.
52107 */
52108 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
52109   /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
52110   ** have been deleted? This API will need to change to return an error code
52111   ** as well as the boolean result value.
52112   */
52113   return (CURSOR_VALID!=pCur->eState);
52114 }
52115
52116 /*
52117 ** Advance the cursor to the next entry in the database.  If
52118 ** successful then set *pRes=0.  If the cursor
52119 ** was already pointing to the last entry in the database before
52120 ** this routine was called, then set *pRes=1.
52121 */
52122 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
52123   int rc;
52124   int idx;
52125   MemPage *pPage;
52126
52127   assert( cursorHoldsMutex(pCur) );
52128   rc = restoreCursorPosition(pCur);
52129   if( rc!=SQLITE_OK ){
52130     return rc;
52131   }
52132   assert( pRes!=0 );
52133   if( CURSOR_INVALID==pCur->eState ){
52134     *pRes = 1;
52135     return SQLITE_OK;
52136   }
52137   if( pCur->skipNext>0 ){
52138     pCur->skipNext = 0;
52139     *pRes = 0;
52140     return SQLITE_OK;
52141   }
52142   pCur->skipNext = 0;
52143
52144   pPage = pCur->apPage[pCur->iPage];
52145   idx = ++pCur->aiIdx[pCur->iPage];
52146   assert( pPage->isInit );
52147   assert( idx<=pPage->nCell );
52148
52149   pCur->info.nSize = 0;
52150   pCur->validNKey = 0;
52151   if( idx>=pPage->nCell ){
52152     if( !pPage->leaf ){
52153       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
52154       if( rc ) return rc;
52155       rc = moveToLeftmost(pCur);
52156       *pRes = 0;
52157       return rc;
52158     }
52159     do{
52160       if( pCur->iPage==0 ){
52161         *pRes = 1;
52162         pCur->eState = CURSOR_INVALID;
52163         return SQLITE_OK;
52164       }
52165       moveToParent(pCur);
52166       pPage = pCur->apPage[pCur->iPage];
52167     }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
52168     *pRes = 0;
52169     if( pPage->intKey ){
52170       rc = sqlite3BtreeNext(pCur, pRes);
52171     }else{
52172       rc = SQLITE_OK;
52173     }
52174     return rc;
52175   }
52176   *pRes = 0;
52177   if( pPage->leaf ){
52178     return SQLITE_OK;
52179   }
52180   rc = moveToLeftmost(pCur);
52181   return rc;
52182 }
52183
52184
52185 /*
52186 ** Step the cursor to the back to the previous entry in the database.  If
52187 ** successful then set *pRes=0.  If the cursor
52188 ** was already pointing to the first entry in the database before
52189 ** this routine was called, then set *pRes=1.
52190 */
52191 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
52192   int rc;
52193   MemPage *pPage;
52194
52195   assert( cursorHoldsMutex(pCur) );
52196   rc = restoreCursorPosition(pCur);
52197   if( rc!=SQLITE_OK ){
52198     return rc;
52199   }
52200   pCur->atLast = 0;
52201   if( CURSOR_INVALID==pCur->eState ){
52202     *pRes = 1;
52203     return SQLITE_OK;
52204   }
52205   if( pCur->skipNext<0 ){
52206     pCur->skipNext = 0;
52207     *pRes = 0;
52208     return SQLITE_OK;
52209   }
52210   pCur->skipNext = 0;
52211
52212   pPage = pCur->apPage[pCur->iPage];
52213   assert( pPage->isInit );
52214   if( !pPage->leaf ){
52215     int idx = pCur->aiIdx[pCur->iPage];
52216     rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
52217     if( rc ){
52218       return rc;
52219     }
52220     rc = moveToRightmost(pCur);
52221   }else{
52222     while( pCur->aiIdx[pCur->iPage]==0 ){
52223       if( pCur->iPage==0 ){
52224         pCur->eState = CURSOR_INVALID;
52225         *pRes = 1;
52226         return SQLITE_OK;
52227       }
52228       moveToParent(pCur);
52229     }
52230     pCur->info.nSize = 0;
52231     pCur->validNKey = 0;
52232
52233     pCur->aiIdx[pCur->iPage]--;
52234     pPage = pCur->apPage[pCur->iPage];
52235     if( pPage->intKey && !pPage->leaf ){
52236       rc = sqlite3BtreePrevious(pCur, pRes);
52237     }else{
52238       rc = SQLITE_OK;
52239     }
52240   }
52241   *pRes = 0;
52242   return rc;
52243 }
52244
52245 /*
52246 ** Allocate a new page from the database file.
52247 **
52248 ** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
52249 ** has already been called on the new page.)  The new page has also
52250 ** been referenced and the calling routine is responsible for calling
52251 ** sqlite3PagerUnref() on the new page when it is done.
52252 **
52253 ** SQLITE_OK is returned on success.  Any other return value indicates
52254 ** an error.  *ppPage and *pPgno are undefined in the event of an error.
52255 ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
52256 **
52257 ** If the "nearby" parameter is not 0, then a (feeble) effort is made to 
52258 ** locate a page close to the page number "nearby".  This can be used in an
52259 ** attempt to keep related pages close to each other in the database file,
52260 ** which in turn can make database access faster.
52261 **
52262 ** If the "exact" parameter is not 0, and the page-number nearby exists 
52263 ** anywhere on the free-list, then it is guarenteed to be returned. This
52264 ** is only used by auto-vacuum databases when allocating a new table.
52265 */
52266 static int allocateBtreePage(
52267   BtShared *pBt, 
52268   MemPage **ppPage, 
52269   Pgno *pPgno, 
52270   Pgno nearby,
52271   u8 exact
52272 ){
52273   MemPage *pPage1;
52274   int rc;
52275   u32 n;     /* Number of pages on the freelist */
52276   u32 k;     /* Number of leaves on the trunk of the freelist */
52277   MemPage *pTrunk = 0;
52278   MemPage *pPrevTrunk = 0;
52279   Pgno mxPage;     /* Total size of the database file */
52280
52281   assert( sqlite3_mutex_held(pBt->mutex) );
52282   pPage1 = pBt->pPage1;
52283   mxPage = btreePagecount(pBt);
52284   n = get4byte(&pPage1->aData[36]);
52285   testcase( n==mxPage-1 );
52286   if( n>=mxPage ){
52287     return SQLITE_CORRUPT_BKPT;
52288   }
52289   if( n>0 ){
52290     /* There are pages on the freelist.  Reuse one of those pages. */
52291     Pgno iTrunk;
52292     u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
52293     
52294     /* If the 'exact' parameter was true and a query of the pointer-map
52295     ** shows that the page 'nearby' is somewhere on the free-list, then
52296     ** the entire-list will be searched for that page.
52297     */
52298 #ifndef SQLITE_OMIT_AUTOVACUUM
52299     if( exact && nearby<=mxPage ){
52300       u8 eType;
52301       assert( nearby>0 );
52302       assert( pBt->autoVacuum );
52303       rc = ptrmapGet(pBt, nearby, &eType, 0);
52304       if( rc ) return rc;
52305       if( eType==PTRMAP_FREEPAGE ){
52306         searchList = 1;
52307       }
52308       *pPgno = nearby;
52309     }
52310 #endif
52311
52312     /* Decrement the free-list count by 1. Set iTrunk to the index of the
52313     ** first free-list trunk page. iPrevTrunk is initially 1.
52314     */
52315     rc = sqlite3PagerWrite(pPage1->pDbPage);
52316     if( rc ) return rc;
52317     put4byte(&pPage1->aData[36], n-1);
52318
52319     /* The code within this loop is run only once if the 'searchList' variable
52320     ** is not true. Otherwise, it runs once for each trunk-page on the
52321     ** free-list until the page 'nearby' is located.
52322     */
52323     do {
52324       pPrevTrunk = pTrunk;
52325       if( pPrevTrunk ){
52326         iTrunk = get4byte(&pPrevTrunk->aData[0]);
52327       }else{
52328         iTrunk = get4byte(&pPage1->aData[32]);
52329       }
52330       testcase( iTrunk==mxPage );
52331       if( iTrunk>mxPage ){
52332         rc = SQLITE_CORRUPT_BKPT;
52333       }else{
52334         rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
52335       }
52336       if( rc ){
52337         pTrunk = 0;
52338         goto end_allocate_page;
52339       }
52340
52341       k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */
52342       if( k==0 && !searchList ){
52343         /* The trunk has no leaves and the list is not being searched. 
52344         ** So extract the trunk page itself and use it as the newly 
52345         ** allocated page */
52346         assert( pPrevTrunk==0 );
52347         rc = sqlite3PagerWrite(pTrunk->pDbPage);
52348         if( rc ){
52349           goto end_allocate_page;
52350         }
52351         *pPgno = iTrunk;
52352         memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
52353         *ppPage = pTrunk;
52354         pTrunk = 0;
52355         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
52356       }else if( k>(u32)(pBt->usableSize/4 - 2) ){
52357         /* Value of k is out of range.  Database corruption */
52358         rc = SQLITE_CORRUPT_BKPT;
52359         goto end_allocate_page;
52360 #ifndef SQLITE_OMIT_AUTOVACUUM
52361       }else if( searchList && nearby==iTrunk ){
52362         /* The list is being searched and this trunk page is the page
52363         ** to allocate, regardless of whether it has leaves.
52364         */
52365         assert( *pPgno==iTrunk );
52366         *ppPage = pTrunk;
52367         searchList = 0;
52368         rc = sqlite3PagerWrite(pTrunk->pDbPage);
52369         if( rc ){
52370           goto end_allocate_page;
52371         }
52372         if( k==0 ){
52373           if( !pPrevTrunk ){
52374             memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
52375           }else{
52376             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
52377             if( rc!=SQLITE_OK ){
52378               goto end_allocate_page;
52379             }
52380             memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
52381           }
52382         }else{
52383           /* The trunk page is required by the caller but it contains 
52384           ** pointers to free-list leaves. The first leaf becomes a trunk
52385           ** page in this case.
52386           */
52387           MemPage *pNewTrunk;
52388           Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
52389           if( iNewTrunk>mxPage ){ 
52390             rc = SQLITE_CORRUPT_BKPT;
52391             goto end_allocate_page;
52392           }
52393           testcase( iNewTrunk==mxPage );
52394           rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
52395           if( rc!=SQLITE_OK ){
52396             goto end_allocate_page;
52397           }
52398           rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
52399           if( rc!=SQLITE_OK ){
52400             releasePage(pNewTrunk);
52401             goto end_allocate_page;
52402           }
52403           memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
52404           put4byte(&pNewTrunk->aData[4], k-1);
52405           memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
52406           releasePage(pNewTrunk);
52407           if( !pPrevTrunk ){
52408             assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
52409             put4byte(&pPage1->aData[32], iNewTrunk);
52410           }else{
52411             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
52412             if( rc ){
52413               goto end_allocate_page;
52414             }
52415             put4byte(&pPrevTrunk->aData[0], iNewTrunk);
52416           }
52417         }
52418         pTrunk = 0;
52419         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
52420 #endif
52421       }else if( k>0 ){
52422         /* Extract a leaf from the trunk */
52423         u32 closest;
52424         Pgno iPage;
52425         unsigned char *aData = pTrunk->aData;
52426         if( nearby>0 ){
52427           u32 i;
52428           int dist;
52429           closest = 0;
52430           dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
52431           for(i=1; i<k; i++){
52432             int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
52433             if( d2<dist ){
52434               closest = i;
52435               dist = d2;
52436             }
52437           }
52438         }else{
52439           closest = 0;
52440         }
52441
52442         iPage = get4byte(&aData[8+closest*4]);
52443         testcase( iPage==mxPage );
52444         if( iPage>mxPage ){
52445           rc = SQLITE_CORRUPT_BKPT;
52446           goto end_allocate_page;
52447         }
52448         testcase( iPage==mxPage );
52449         if( !searchList || iPage==nearby ){
52450           int noContent;
52451           *pPgno = iPage;
52452           TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
52453                  ": %d more free pages\n",
52454                  *pPgno, closest+1, k, pTrunk->pgno, n-1));
52455           rc = sqlite3PagerWrite(pTrunk->pDbPage);
52456           if( rc ) goto end_allocate_page;
52457           if( closest<k-1 ){
52458             memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
52459           }
52460           put4byte(&aData[4], k-1);
52461           noContent = !btreeGetHasContent(pBt, *pPgno);
52462           rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
52463           if( rc==SQLITE_OK ){
52464             rc = sqlite3PagerWrite((*ppPage)->pDbPage);
52465             if( rc!=SQLITE_OK ){
52466               releasePage(*ppPage);
52467             }
52468           }
52469           searchList = 0;
52470         }
52471       }
52472       releasePage(pPrevTrunk);
52473       pPrevTrunk = 0;
52474     }while( searchList );
52475   }else{
52476     /* There are no pages on the freelist, so create a new page at the
52477     ** end of the file */
52478     rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
52479     if( rc ) return rc;
52480     pBt->nPage++;
52481     if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
52482
52483 #ifndef SQLITE_OMIT_AUTOVACUUM
52484     if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
52485       /* If *pPgno refers to a pointer-map page, allocate two new pages
52486       ** at the end of the file instead of one. The first allocated page
52487       ** becomes a new pointer-map page, the second is used by the caller.
52488       */
52489       MemPage *pPg = 0;
52490       TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
52491       assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
52492       rc = btreeGetPage(pBt, pBt->nPage, &pPg, 1);
52493       if( rc==SQLITE_OK ){
52494         rc = sqlite3PagerWrite(pPg->pDbPage);
52495         releasePage(pPg);
52496       }
52497       if( rc ) return rc;
52498       pBt->nPage++;
52499       if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
52500     }
52501 #endif
52502     put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
52503     *pPgno = pBt->nPage;
52504
52505     assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
52506     rc = btreeGetPage(pBt, *pPgno, ppPage, 1);
52507     if( rc ) return rc;
52508     rc = sqlite3PagerWrite((*ppPage)->pDbPage);
52509     if( rc!=SQLITE_OK ){
52510       releasePage(*ppPage);
52511     }
52512     TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
52513   }
52514
52515   assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
52516
52517 end_allocate_page:
52518   releasePage(pTrunk);
52519   releasePage(pPrevTrunk);
52520   if( rc==SQLITE_OK ){
52521     if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
52522       releasePage(*ppPage);
52523       return SQLITE_CORRUPT_BKPT;
52524     }
52525     (*ppPage)->isInit = 0;
52526   }else{
52527     *ppPage = 0;
52528   }
52529   assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) );
52530   return rc;
52531 }
52532
52533 /*
52534 ** This function is used to add page iPage to the database file free-list. 
52535 ** It is assumed that the page is not already a part of the free-list.
52536 **
52537 ** The value passed as the second argument to this function is optional.
52538 ** If the caller happens to have a pointer to the MemPage object 
52539 ** corresponding to page iPage handy, it may pass it as the second value. 
52540 ** Otherwise, it may pass NULL.
52541 **
52542 ** If a pointer to a MemPage object is passed as the second argument,
52543 ** its reference count is not altered by this function.
52544 */
52545 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
52546   MemPage *pTrunk = 0;                /* Free-list trunk page */
52547   Pgno iTrunk = 0;                    /* Page number of free-list trunk page */ 
52548   MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
52549   MemPage *pPage;                     /* Page being freed. May be NULL. */
52550   int rc;                             /* Return Code */
52551   int nFree;                          /* Initial number of pages on free-list */
52552
52553   assert( sqlite3_mutex_held(pBt->mutex) );
52554   assert( iPage>1 );
52555   assert( !pMemPage || pMemPage->pgno==iPage );
52556
52557   if( pMemPage ){
52558     pPage = pMemPage;
52559     sqlite3PagerRef(pPage->pDbPage);
52560   }else{
52561     pPage = btreePageLookup(pBt, iPage);
52562   }
52563
52564   /* Increment the free page count on pPage1 */
52565   rc = sqlite3PagerWrite(pPage1->pDbPage);
52566   if( rc ) goto freepage_out;
52567   nFree = get4byte(&pPage1->aData[36]);
52568   put4byte(&pPage1->aData[36], nFree+1);
52569
52570   if( pBt->secureDelete ){
52571     /* If the secure_delete option is enabled, then
52572     ** always fully overwrite deleted information with zeros.
52573     */
52574     if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
52575      ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
52576     ){
52577       goto freepage_out;
52578     }
52579     memset(pPage->aData, 0, pPage->pBt->pageSize);
52580   }
52581
52582   /* If the database supports auto-vacuum, write an entry in the pointer-map
52583   ** to indicate that the page is free.
52584   */
52585   if( ISAUTOVACUUM ){
52586     ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
52587     if( rc ) goto freepage_out;
52588   }
52589
52590   /* Now manipulate the actual database free-list structure. There are two
52591   ** possibilities. If the free-list is currently empty, or if the first
52592   ** trunk page in the free-list is full, then this page will become a
52593   ** new free-list trunk page. Otherwise, it will become a leaf of the
52594   ** first trunk page in the current free-list. This block tests if it
52595   ** is possible to add the page as a new free-list leaf.
52596   */
52597   if( nFree!=0 ){
52598     u32 nLeaf;                /* Initial number of leaf cells on trunk page */
52599
52600     iTrunk = get4byte(&pPage1->aData[32]);
52601     rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
52602     if( rc!=SQLITE_OK ){
52603       goto freepage_out;
52604     }
52605
52606     nLeaf = get4byte(&pTrunk->aData[4]);
52607     assert( pBt->usableSize>32 );
52608     if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
52609       rc = SQLITE_CORRUPT_BKPT;
52610       goto freepage_out;
52611     }
52612     if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
52613       /* In this case there is room on the trunk page to insert the page
52614       ** being freed as a new leaf.
52615       **
52616       ** Note that the trunk page is not really full until it contains
52617       ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
52618       ** coded.  But due to a coding error in versions of SQLite prior to
52619       ** 3.6.0, databases with freelist trunk pages holding more than
52620       ** usableSize/4 - 8 entries will be reported as corrupt.  In order
52621       ** to maintain backwards compatibility with older versions of SQLite,
52622       ** we will continue to restrict the number of entries to usableSize/4 - 8
52623       ** for now.  At some point in the future (once everyone has upgraded
52624       ** to 3.6.0 or later) we should consider fixing the conditional above
52625       ** to read "usableSize/4-2" instead of "usableSize/4-8".
52626       */
52627       rc = sqlite3PagerWrite(pTrunk->pDbPage);
52628       if( rc==SQLITE_OK ){
52629         put4byte(&pTrunk->aData[4], nLeaf+1);
52630         put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
52631         if( pPage && !pBt->secureDelete ){
52632           sqlite3PagerDontWrite(pPage->pDbPage);
52633         }
52634         rc = btreeSetHasContent(pBt, iPage);
52635       }
52636       TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
52637       goto freepage_out;
52638     }
52639   }
52640
52641   /* If control flows to this point, then it was not possible to add the
52642   ** the page being freed as a leaf page of the first trunk in the free-list.
52643   ** Possibly because the free-list is empty, or possibly because the 
52644   ** first trunk in the free-list is full. Either way, the page being freed
52645   ** will become the new first trunk page in the free-list.
52646   */
52647   if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
52648     goto freepage_out;
52649   }
52650   rc = sqlite3PagerWrite(pPage->pDbPage);
52651   if( rc!=SQLITE_OK ){
52652     goto freepage_out;
52653   }
52654   put4byte(pPage->aData, iTrunk);
52655   put4byte(&pPage->aData[4], 0);
52656   put4byte(&pPage1->aData[32], iPage);
52657   TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
52658
52659 freepage_out:
52660   if( pPage ){
52661     pPage->isInit = 0;
52662   }
52663   releasePage(pPage);
52664   releasePage(pTrunk);
52665   return rc;
52666 }
52667 static void freePage(MemPage *pPage, int *pRC){
52668   if( (*pRC)==SQLITE_OK ){
52669     *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
52670   }
52671 }
52672
52673 /*
52674 ** Free any overflow pages associated with the given Cell.
52675 */
52676 static int clearCell(MemPage *pPage, unsigned char *pCell){
52677   BtShared *pBt = pPage->pBt;
52678   CellInfo info;
52679   Pgno ovflPgno;
52680   int rc;
52681   int nOvfl;
52682   u32 ovflPageSize;
52683
52684   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52685   btreeParseCellPtr(pPage, pCell, &info);
52686   if( info.iOverflow==0 ){
52687     return SQLITE_OK;  /* No overflow pages. Return without doing anything */
52688   }
52689   ovflPgno = get4byte(&pCell[info.iOverflow]);
52690   assert( pBt->usableSize > 4 );
52691   ovflPageSize = pBt->usableSize - 4;
52692   nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
52693   assert( ovflPgno==0 || nOvfl>0 );
52694   while( nOvfl-- ){
52695     Pgno iNext = 0;
52696     MemPage *pOvfl = 0;
52697     if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
52698       /* 0 is not a legal page number and page 1 cannot be an 
52699       ** overflow page. Therefore if ovflPgno<2 or past the end of the 
52700       ** file the database must be corrupt. */
52701       return SQLITE_CORRUPT_BKPT;
52702     }
52703     if( nOvfl ){
52704       rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
52705       if( rc ) return rc;
52706     }
52707
52708     if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
52709      && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
52710     ){
52711       /* There is no reason any cursor should have an outstanding reference 
52712       ** to an overflow page belonging to a cell that is being deleted/updated.
52713       ** So if there exists more than one reference to this page, then it 
52714       ** must not really be an overflow page and the database must be corrupt. 
52715       ** It is helpful to detect this before calling freePage2(), as 
52716       ** freePage2() may zero the page contents if secure-delete mode is
52717       ** enabled. If this 'overflow' page happens to be a page that the
52718       ** caller is iterating through or using in some other way, this
52719       ** can be problematic.
52720       */
52721       rc = SQLITE_CORRUPT_BKPT;
52722     }else{
52723       rc = freePage2(pBt, pOvfl, ovflPgno);
52724     }
52725
52726     if( pOvfl ){
52727       sqlite3PagerUnref(pOvfl->pDbPage);
52728     }
52729     if( rc ) return rc;
52730     ovflPgno = iNext;
52731   }
52732   return SQLITE_OK;
52733 }
52734
52735 /*
52736 ** Create the byte sequence used to represent a cell on page pPage
52737 ** and write that byte sequence into pCell[].  Overflow pages are
52738 ** allocated and filled in as necessary.  The calling procedure
52739 ** is responsible for making sure sufficient space has been allocated
52740 ** for pCell[].
52741 **
52742 ** Note that pCell does not necessary need to point to the pPage->aData
52743 ** area.  pCell might point to some temporary storage.  The cell will
52744 ** be constructed in this temporary area then copied into pPage->aData
52745 ** later.
52746 */
52747 static int fillInCell(
52748   MemPage *pPage,                /* The page that contains the cell */
52749   unsigned char *pCell,          /* Complete text of the cell */
52750   const void *pKey, i64 nKey,    /* The key */
52751   const void *pData,int nData,   /* The data */
52752   int nZero,                     /* Extra zero bytes to append to pData */
52753   int *pnSize                    /* Write cell size here */
52754 ){
52755   int nPayload;
52756   const u8 *pSrc;
52757   int nSrc, n, rc;
52758   int spaceLeft;
52759   MemPage *pOvfl = 0;
52760   MemPage *pToRelease = 0;
52761   unsigned char *pPrior;
52762   unsigned char *pPayload;
52763   BtShared *pBt = pPage->pBt;
52764   Pgno pgnoOvfl = 0;
52765   int nHeader;
52766   CellInfo info;
52767
52768   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52769
52770   /* pPage is not necessarily writeable since pCell might be auxiliary
52771   ** buffer space that is separate from the pPage buffer area */
52772   assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
52773             || sqlite3PagerIswriteable(pPage->pDbPage) );
52774
52775   /* Fill in the header. */
52776   nHeader = 0;
52777   if( !pPage->leaf ){
52778     nHeader += 4;
52779   }
52780   if( pPage->hasData ){
52781     nHeader += putVarint(&pCell[nHeader], nData+nZero);
52782   }else{
52783     nData = nZero = 0;
52784   }
52785   nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
52786   btreeParseCellPtr(pPage, pCell, &info);
52787   assert( info.nHeader==nHeader );
52788   assert( info.nKey==nKey );
52789   assert( info.nData==(u32)(nData+nZero) );
52790   
52791   /* Fill in the payload */
52792   nPayload = nData + nZero;
52793   if( pPage->intKey ){
52794     pSrc = pData;
52795     nSrc = nData;
52796     nData = 0;
52797   }else{ 
52798     if( NEVER(nKey>0x7fffffff || pKey==0) ){
52799       return SQLITE_CORRUPT_BKPT;
52800     }
52801     nPayload += (int)nKey;
52802     pSrc = pKey;
52803     nSrc = (int)nKey;
52804   }
52805   *pnSize = info.nSize;
52806   spaceLeft = info.nLocal;
52807   pPayload = &pCell[nHeader];
52808   pPrior = &pCell[info.iOverflow];
52809
52810   while( nPayload>0 ){
52811     if( spaceLeft==0 ){
52812 #ifndef SQLITE_OMIT_AUTOVACUUM
52813       Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
52814       if( pBt->autoVacuum ){
52815         do{
52816           pgnoOvfl++;
52817         } while( 
52818           PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt) 
52819         );
52820       }
52821 #endif
52822       rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
52823 #ifndef SQLITE_OMIT_AUTOVACUUM
52824       /* If the database supports auto-vacuum, and the second or subsequent
52825       ** overflow page is being allocated, add an entry to the pointer-map
52826       ** for that page now. 
52827       **
52828       ** If this is the first overflow page, then write a partial entry 
52829       ** to the pointer-map. If we write nothing to this pointer-map slot,
52830       ** then the optimistic overflow chain processing in clearCell()
52831       ** may misinterpret the uninitialised values and delete the
52832       ** wrong pages from the database.
52833       */
52834       if( pBt->autoVacuum && rc==SQLITE_OK ){
52835         u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
52836         ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
52837         if( rc ){
52838           releasePage(pOvfl);
52839         }
52840       }
52841 #endif
52842       if( rc ){
52843         releasePage(pToRelease);
52844         return rc;
52845       }
52846
52847       /* If pToRelease is not zero than pPrior points into the data area
52848       ** of pToRelease.  Make sure pToRelease is still writeable. */
52849       assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
52850
52851       /* If pPrior is part of the data area of pPage, then make sure pPage
52852       ** is still writeable */
52853       assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
52854             || sqlite3PagerIswriteable(pPage->pDbPage) );
52855
52856       put4byte(pPrior, pgnoOvfl);
52857       releasePage(pToRelease);
52858       pToRelease = pOvfl;
52859       pPrior = pOvfl->aData;
52860       put4byte(pPrior, 0);
52861       pPayload = &pOvfl->aData[4];
52862       spaceLeft = pBt->usableSize - 4;
52863     }
52864     n = nPayload;
52865     if( n>spaceLeft ) n = spaceLeft;
52866
52867     /* If pToRelease is not zero than pPayload points into the data area
52868     ** of pToRelease.  Make sure pToRelease is still writeable. */
52869     assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
52870
52871     /* If pPayload is part of the data area of pPage, then make sure pPage
52872     ** is still writeable */
52873     assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
52874             || sqlite3PagerIswriteable(pPage->pDbPage) );
52875
52876     if( nSrc>0 ){
52877       if( n>nSrc ) n = nSrc;
52878       assert( pSrc );
52879       memcpy(pPayload, pSrc, n);
52880     }else{
52881       memset(pPayload, 0, n);
52882     }
52883     nPayload -= n;
52884     pPayload += n;
52885     pSrc += n;
52886     nSrc -= n;
52887     spaceLeft -= n;
52888     if( nSrc==0 ){
52889       nSrc = nData;
52890       pSrc = pData;
52891     }
52892   }
52893   releasePage(pToRelease);
52894   return SQLITE_OK;
52895 }
52896
52897 /*
52898 ** Remove the i-th cell from pPage.  This routine effects pPage only.
52899 ** The cell content is not freed or deallocated.  It is assumed that
52900 ** the cell content has been copied someplace else.  This routine just
52901 ** removes the reference to the cell from pPage.
52902 **
52903 ** "sz" must be the number of bytes in the cell.
52904 */
52905 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
52906   u32 pc;         /* Offset to cell content of cell being deleted */
52907   u8 *data;       /* pPage->aData */
52908   u8 *ptr;        /* Used to move bytes around within data[] */
52909   u8 *endPtr;     /* End of loop */
52910   int rc;         /* The return code */
52911   int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
52912
52913   if( *pRC ) return;
52914
52915   assert( idx>=0 && idx<pPage->nCell );
52916   assert( sz==cellSize(pPage, idx) );
52917   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
52918   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52919   data = pPage->aData;
52920   ptr = &data[pPage->cellOffset + 2*idx];
52921   pc = get2byte(ptr);
52922   hdr = pPage->hdrOffset;
52923   testcase( pc==get2byte(&data[hdr+5]) );
52924   testcase( pc+sz==pPage->pBt->usableSize );
52925   if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
52926     *pRC = SQLITE_CORRUPT_BKPT;
52927     return;
52928   }
52929   rc = freeSpace(pPage, pc, sz);
52930   if( rc ){
52931     *pRC = rc;
52932     return;
52933   }
52934   endPtr = &data[pPage->cellOffset + 2*pPage->nCell - 2];
52935   assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 );  /* ptr is always 2-byte aligned */
52936   while( ptr<endPtr ){
52937     *(u16*)ptr = *(u16*)&ptr[2];
52938     ptr += 2;
52939   }
52940   pPage->nCell--;
52941   put2byte(&data[hdr+3], pPage->nCell);
52942   pPage->nFree += 2;
52943 }
52944
52945 /*
52946 ** Insert a new cell on pPage at cell index "i".  pCell points to the
52947 ** content of the cell.
52948 **
52949 ** If the cell content will fit on the page, then put it there.  If it
52950 ** will not fit, then make a copy of the cell content into pTemp if
52951 ** pTemp is not null.  Regardless of pTemp, allocate a new entry
52952 ** in pPage->aOvfl[] and make it point to the cell content (either
52953 ** in pTemp or the original pCell) and also record its index. 
52954 ** Allocating a new entry in pPage->aCell[] implies that 
52955 ** pPage->nOverflow is incremented.
52956 **
52957 ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
52958 ** cell. The caller will overwrite them after this function returns. If
52959 ** nSkip is non-zero, then pCell may not point to an invalid memory location 
52960 ** (but pCell+nSkip is always valid).
52961 */
52962 static void insertCell(
52963   MemPage *pPage,   /* Page into which we are copying */
52964   int i,            /* New cell becomes the i-th cell of the page */
52965   u8 *pCell,        /* Content of the new cell */
52966   int sz,           /* Bytes of content in pCell */
52967   u8 *pTemp,        /* Temp storage space for pCell, if needed */
52968   Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
52969   int *pRC          /* Read and write return code from here */
52970 ){
52971   int idx = 0;      /* Where to write new cell content in data[] */
52972   int j;            /* Loop counter */
52973   int end;          /* First byte past the last cell pointer in data[] */
52974   int ins;          /* Index in data[] where new cell pointer is inserted */
52975   int cellOffset;   /* Address of first cell pointer in data[] */
52976   u8 *data;         /* The content of the whole page */
52977   u8 *ptr;          /* Used for moving information around in data[] */
52978   u8 *endPtr;       /* End of the loop */
52979
52980   int nSkip = (iChild ? 4 : 0);
52981
52982   if( *pRC ) return;
52983
52984   assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
52985   assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921 );
52986   assert( pPage->nOverflow<=ArraySize(pPage->aOvfl) );
52987   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52988   /* The cell should normally be sized correctly.  However, when moving a
52989   ** malformed cell from a leaf page to an interior page, if the cell size
52990   ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
52991   ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
52992   ** the term after the || in the following assert(). */
52993   assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
52994   if( pPage->nOverflow || sz+2>pPage->nFree ){
52995     if( pTemp ){
52996       memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
52997       pCell = pTemp;
52998     }
52999     if( iChild ){
53000       put4byte(pCell, iChild);
53001     }
53002     j = pPage->nOverflow++;
53003     assert( j<(int)(sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0])) );
53004     pPage->aOvfl[j].pCell = pCell;
53005     pPage->aOvfl[j].idx = (u16)i;
53006   }else{
53007     int rc = sqlite3PagerWrite(pPage->pDbPage);
53008     if( rc!=SQLITE_OK ){
53009       *pRC = rc;
53010       return;
53011     }
53012     assert( sqlite3PagerIswriteable(pPage->pDbPage) );
53013     data = pPage->aData;
53014     cellOffset = pPage->cellOffset;
53015     end = cellOffset + 2*pPage->nCell;
53016     ins = cellOffset + 2*i;
53017     rc = allocateSpace(pPage, sz, &idx);
53018     if( rc ){ *pRC = rc; return; }
53019     /* The allocateSpace() routine guarantees the following two properties
53020     ** if it returns success */
53021     assert( idx >= end+2 );
53022     assert( idx+sz <= (int)pPage->pBt->usableSize );
53023     pPage->nCell++;
53024     pPage->nFree -= (u16)(2 + sz);
53025     memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
53026     if( iChild ){
53027       put4byte(&data[idx], iChild);
53028     }
53029     ptr = &data[end];
53030     endPtr = &data[ins];
53031     assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 );  /* ptr is always 2-byte aligned */
53032     while( ptr>endPtr ){
53033       *(u16*)ptr = *(u16*)&ptr[-2];
53034       ptr -= 2;
53035     }
53036     put2byte(&data[ins], idx);
53037     put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
53038 #ifndef SQLITE_OMIT_AUTOVACUUM
53039     if( pPage->pBt->autoVacuum ){
53040       /* The cell may contain a pointer to an overflow page. If so, write
53041       ** the entry for the overflow page into the pointer map.
53042       */
53043       ptrmapPutOvflPtr(pPage, pCell, pRC);
53044     }
53045 #endif
53046   }
53047 }
53048
53049 /*
53050 ** Add a list of cells to a page.  The page should be initially empty.
53051 ** The cells are guaranteed to fit on the page.
53052 */
53053 static void assemblePage(
53054   MemPage *pPage,   /* The page to be assemblied */
53055   int nCell,        /* The number of cells to add to this page */
53056   u8 **apCell,      /* Pointers to cell bodies */
53057   u16 *aSize        /* Sizes of the cells */
53058 ){
53059   int i;            /* Loop counter */
53060   u8 *pCellptr;     /* Address of next cell pointer */
53061   int cellbody;     /* Address of next cell body */
53062   u8 * const data = pPage->aData;             /* Pointer to data for pPage */
53063   const int hdr = pPage->hdrOffset;           /* Offset of header on pPage */
53064   const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
53065
53066   assert( pPage->nOverflow==0 );
53067   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53068   assert( nCell>=0 && nCell<=(int)MX_CELL(pPage->pBt)
53069             && (int)MX_CELL(pPage->pBt)<=10921);
53070   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
53071
53072   /* Check that the page has just been zeroed by zeroPage() */
53073   assert( pPage->nCell==0 );
53074   assert( get2byteNotZero(&data[hdr+5])==nUsable );
53075
53076   pCellptr = &data[pPage->cellOffset + nCell*2];
53077   cellbody = nUsable;
53078   for(i=nCell-1; i>=0; i--){
53079     u16 sz = aSize[i];
53080     pCellptr -= 2;
53081     cellbody -= sz;
53082     put2byte(pCellptr, cellbody);
53083     memcpy(&data[cellbody], apCell[i], sz);
53084   }
53085   put2byte(&data[hdr+3], nCell);
53086   put2byte(&data[hdr+5], cellbody);
53087   pPage->nFree -= (nCell*2 + nUsable - cellbody);
53088   pPage->nCell = (u16)nCell;
53089 }
53090
53091 /*
53092 ** The following parameters determine how many adjacent pages get involved
53093 ** in a balancing operation.  NN is the number of neighbors on either side
53094 ** of the page that participate in the balancing operation.  NB is the
53095 ** total number of pages that participate, including the target page and
53096 ** NN neighbors on either side.
53097 **
53098 ** The minimum value of NN is 1 (of course).  Increasing NN above 1
53099 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
53100 ** in exchange for a larger degradation in INSERT and UPDATE performance.
53101 ** The value of NN appears to give the best results overall.
53102 */
53103 #define NN 1             /* Number of neighbors on either side of pPage */
53104 #define NB (NN*2+1)      /* Total pages involved in the balance */
53105
53106
53107 #ifndef SQLITE_OMIT_QUICKBALANCE
53108 /*
53109 ** This version of balance() handles the common special case where
53110 ** a new entry is being inserted on the extreme right-end of the
53111 ** tree, in other words, when the new entry will become the largest
53112 ** entry in the tree.
53113 **
53114 ** Instead of trying to balance the 3 right-most leaf pages, just add
53115 ** a new page to the right-hand side and put the one new entry in
53116 ** that page.  This leaves the right side of the tree somewhat
53117 ** unbalanced.  But odds are that we will be inserting new entries
53118 ** at the end soon afterwards so the nearly empty page will quickly
53119 ** fill up.  On average.
53120 **
53121 ** pPage is the leaf page which is the right-most page in the tree.
53122 ** pParent is its parent.  pPage must have a single overflow entry
53123 ** which is also the right-most entry on the page.
53124 **
53125 ** The pSpace buffer is used to store a temporary copy of the divider
53126 ** cell that will be inserted into pParent. Such a cell consists of a 4
53127 ** byte page number followed by a variable length integer. In other
53128 ** words, at most 13 bytes. Hence the pSpace buffer must be at
53129 ** least 13 bytes in size.
53130 */
53131 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
53132   BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
53133   MemPage *pNew;                       /* Newly allocated page */
53134   int rc;                              /* Return Code */
53135   Pgno pgnoNew;                        /* Page number of pNew */
53136
53137   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53138   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
53139   assert( pPage->nOverflow==1 );
53140
53141   /* This error condition is now caught prior to reaching this function */
53142   if( pPage->nCell<=0 ) return SQLITE_CORRUPT_BKPT;
53143
53144   /* Allocate a new page. This page will become the right-sibling of 
53145   ** pPage. Make the parent page writable, so that the new divider cell
53146   ** may be inserted. If both these operations are successful, proceed.
53147   */
53148   rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
53149
53150   if( rc==SQLITE_OK ){
53151
53152     u8 *pOut = &pSpace[4];
53153     u8 *pCell = pPage->aOvfl[0].pCell;
53154     u16 szCell = cellSizePtr(pPage, pCell);
53155     u8 *pStop;
53156
53157     assert( sqlite3PagerIswriteable(pNew->pDbPage) );
53158     assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
53159     zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
53160     assemblePage(pNew, 1, &pCell, &szCell);
53161
53162     /* If this is an auto-vacuum database, update the pointer map
53163     ** with entries for the new page, and any pointer from the 
53164     ** cell on the page to an overflow page. If either of these
53165     ** operations fails, the return code is set, but the contents
53166     ** of the parent page are still manipulated by thh code below.
53167     ** That is Ok, at this point the parent page is guaranteed to
53168     ** be marked as dirty. Returning an error code will cause a
53169     ** rollback, undoing any changes made to the parent page.
53170     */
53171     if( ISAUTOVACUUM ){
53172       ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
53173       if( szCell>pNew->minLocal ){
53174         ptrmapPutOvflPtr(pNew, pCell, &rc);
53175       }
53176     }
53177   
53178     /* Create a divider cell to insert into pParent. The divider cell
53179     ** consists of a 4-byte page number (the page number of pPage) and
53180     ** a variable length key value (which must be the same value as the
53181     ** largest key on pPage).
53182     **
53183     ** To find the largest key value on pPage, first find the right-most 
53184     ** cell on pPage. The first two fields of this cell are the 
53185     ** record-length (a variable length integer at most 32-bits in size)
53186     ** and the key value (a variable length integer, may have any value).
53187     ** The first of the while(...) loops below skips over the record-length
53188     ** field. The second while(...) loop copies the key value from the
53189     ** cell on pPage into the pSpace buffer.
53190     */
53191     pCell = findCell(pPage, pPage->nCell-1);
53192     pStop = &pCell[9];
53193     while( (*(pCell++)&0x80) && pCell<pStop );
53194     pStop = &pCell[9];
53195     while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
53196
53197     /* Insert the new divider cell into pParent. */
53198     insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
53199                0, pPage->pgno, &rc);
53200
53201     /* Set the right-child pointer of pParent to point to the new page. */
53202     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
53203   
53204     /* Release the reference to the new page. */
53205     releasePage(pNew);
53206   }
53207
53208   return rc;
53209 }
53210 #endif /* SQLITE_OMIT_QUICKBALANCE */
53211
53212 #if 0
53213 /*
53214 ** This function does not contribute anything to the operation of SQLite.
53215 ** it is sometimes activated temporarily while debugging code responsible 
53216 ** for setting pointer-map entries.
53217 */
53218 static int ptrmapCheckPages(MemPage **apPage, int nPage){
53219   int i, j;
53220   for(i=0; i<nPage; i++){
53221     Pgno n;
53222     u8 e;
53223     MemPage *pPage = apPage[i];
53224     BtShared *pBt = pPage->pBt;
53225     assert( pPage->isInit );
53226
53227     for(j=0; j<pPage->nCell; j++){
53228       CellInfo info;
53229       u8 *z;
53230      
53231       z = findCell(pPage, j);
53232       btreeParseCellPtr(pPage, z, &info);
53233       if( info.iOverflow ){
53234         Pgno ovfl = get4byte(&z[info.iOverflow]);
53235         ptrmapGet(pBt, ovfl, &e, &n);
53236         assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
53237       }
53238       if( !pPage->leaf ){
53239         Pgno child = get4byte(z);
53240         ptrmapGet(pBt, child, &e, &n);
53241         assert( n==pPage->pgno && e==PTRMAP_BTREE );
53242       }
53243     }
53244     if( !pPage->leaf ){
53245       Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
53246       ptrmapGet(pBt, child, &e, &n);
53247       assert( n==pPage->pgno && e==PTRMAP_BTREE );
53248     }
53249   }
53250   return 1;
53251 }
53252 #endif
53253
53254 /*
53255 ** This function is used to copy the contents of the b-tree node stored 
53256 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
53257 ** the pointer-map entries for each child page are updated so that the
53258 ** parent page stored in the pointer map is page pTo. If pFrom contained
53259 ** any cells with overflow page pointers, then the corresponding pointer
53260 ** map entries are also updated so that the parent page is page pTo.
53261 **
53262 ** If pFrom is currently carrying any overflow cells (entries in the
53263 ** MemPage.aOvfl[] array), they are not copied to pTo. 
53264 **
53265 ** Before returning, page pTo is reinitialized using btreeInitPage().
53266 **
53267 ** The performance of this function is not critical. It is only used by 
53268 ** the balance_shallower() and balance_deeper() procedures, neither of
53269 ** which are called often under normal circumstances.
53270 */
53271 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
53272   if( (*pRC)==SQLITE_OK ){
53273     BtShared * const pBt = pFrom->pBt;
53274     u8 * const aFrom = pFrom->aData;
53275     u8 * const aTo = pTo->aData;
53276     int const iFromHdr = pFrom->hdrOffset;
53277     int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
53278     int rc;
53279     int iData;
53280   
53281   
53282     assert( pFrom->isInit );
53283     assert( pFrom->nFree>=iToHdr );
53284     assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
53285   
53286     /* Copy the b-tree node content from page pFrom to page pTo. */
53287     iData = get2byte(&aFrom[iFromHdr+5]);
53288     memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
53289     memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
53290   
53291     /* Reinitialize page pTo so that the contents of the MemPage structure
53292     ** match the new data. The initialization of pTo can actually fail under
53293     ** fairly obscure circumstances, even though it is a copy of initialized 
53294     ** page pFrom.
53295     */
53296     pTo->isInit = 0;
53297     rc = btreeInitPage(pTo);
53298     if( rc!=SQLITE_OK ){
53299       *pRC = rc;
53300       return;
53301     }
53302   
53303     /* If this is an auto-vacuum database, update the pointer-map entries
53304     ** for any b-tree or overflow pages that pTo now contains the pointers to.
53305     */
53306     if( ISAUTOVACUUM ){
53307       *pRC = setChildPtrmaps(pTo);
53308     }
53309   }
53310 }
53311
53312 /*
53313 ** This routine redistributes cells on the iParentIdx'th child of pParent
53314 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
53315 ** same amount of free space. Usually a single sibling on either side of the
53316 ** page are used in the balancing, though both siblings might come from one
53317 ** side if the page is the first or last child of its parent. If the page 
53318 ** has fewer than 2 siblings (something which can only happen if the page
53319 ** is a root page or a child of a root page) then all available siblings
53320 ** participate in the balancing.
53321 **
53322 ** The number of siblings of the page might be increased or decreased by 
53323 ** one or two in an effort to keep pages nearly full but not over full. 
53324 **
53325 ** Note that when this routine is called, some of the cells on the page
53326 ** might not actually be stored in MemPage.aData[]. This can happen
53327 ** if the page is overfull. This routine ensures that all cells allocated
53328 ** to the page and its siblings fit into MemPage.aData[] before returning.
53329 **
53330 ** In the course of balancing the page and its siblings, cells may be
53331 ** inserted into or removed from the parent page (pParent). Doing so
53332 ** may cause the parent page to become overfull or underfull. If this
53333 ** happens, it is the responsibility of the caller to invoke the correct
53334 ** balancing routine to fix this problem (see the balance() routine). 
53335 **
53336 ** If this routine fails for any reason, it might leave the database
53337 ** in a corrupted state. So if this routine fails, the database should
53338 ** be rolled back.
53339 **
53340 ** The third argument to this function, aOvflSpace, is a pointer to a
53341 ** buffer big enough to hold one page. If while inserting cells into the parent
53342 ** page (pParent) the parent page becomes overfull, this buffer is
53343 ** used to store the parent's overflow cells. Because this function inserts
53344 ** a maximum of four divider cells into the parent page, and the maximum
53345 ** size of a cell stored within an internal node is always less than 1/4
53346 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
53347 ** enough for all overflow cells.
53348 **
53349 ** If aOvflSpace is set to a null pointer, this function returns 
53350 ** SQLITE_NOMEM.
53351 */
53352 static int balance_nonroot(
53353   MemPage *pParent,               /* Parent page of siblings being balanced */
53354   int iParentIdx,                 /* Index of "the page" in pParent */
53355   u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
53356   int isRoot                      /* True if pParent is a root-page */
53357 ){
53358   BtShared *pBt;               /* The whole database */
53359   int nCell = 0;               /* Number of cells in apCell[] */
53360   int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
53361   int nNew = 0;                /* Number of pages in apNew[] */
53362   int nOld;                    /* Number of pages in apOld[] */
53363   int i, j, k;                 /* Loop counters */
53364   int nxDiv;                   /* Next divider slot in pParent->aCell[] */
53365   int rc = SQLITE_OK;          /* The return code */
53366   u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
53367   int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
53368   int usableSpace;             /* Bytes in pPage beyond the header */
53369   int pageFlags;               /* Value of pPage->aData[0] */
53370   int subtotal;                /* Subtotal of bytes in cells on one page */
53371   int iSpace1 = 0;             /* First unused byte of aSpace1[] */
53372   int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
53373   int szScratch;               /* Size of scratch memory requested */
53374   MemPage *apOld[NB];          /* pPage and up to two siblings */
53375   MemPage *apCopy[NB];         /* Private copies of apOld[] pages */
53376   MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
53377   u8 *pRight;                  /* Location in parent of right-sibling pointer */
53378   u8 *apDiv[NB-1];             /* Divider cells in pParent */
53379   int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
53380   int szNew[NB+2];             /* Combined size of cells place on i-th page */
53381   u8 **apCell = 0;             /* All cells begin balanced */
53382   u16 *szCell;                 /* Local size of all cells in apCell[] */
53383   u8 *aSpace1;                 /* Space for copies of dividers cells */
53384   Pgno pgno;                   /* Temp var to store a page number in */
53385
53386   pBt = pParent->pBt;
53387   assert( sqlite3_mutex_held(pBt->mutex) );
53388   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
53389
53390 #if 0
53391   TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
53392 #endif
53393
53394   /* At this point pParent may have at most one overflow cell. And if
53395   ** this overflow cell is present, it must be the cell with 
53396   ** index iParentIdx. This scenario comes about when this function
53397   ** is called (indirectly) from sqlite3BtreeDelete().
53398   */
53399   assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
53400   assert( pParent->nOverflow==0 || pParent->aOvfl[0].idx==iParentIdx );
53401
53402   if( !aOvflSpace ){
53403     return SQLITE_NOMEM;
53404   }
53405
53406   /* Find the sibling pages to balance. Also locate the cells in pParent 
53407   ** that divide the siblings. An attempt is made to find NN siblings on 
53408   ** either side of pPage. More siblings are taken from one side, however, 
53409   ** if there are fewer than NN siblings on the other side. If pParent
53410   ** has NB or fewer children then all children of pParent are taken.  
53411   **
53412   ** This loop also drops the divider cells from the parent page. This
53413   ** way, the remainder of the function does not have to deal with any
53414   ** overflow cells in the parent page, since if any existed they will
53415   ** have already been removed.
53416   */
53417   i = pParent->nOverflow + pParent->nCell;
53418   if( i<2 ){
53419     nxDiv = 0;
53420     nOld = i+1;
53421   }else{
53422     nOld = 3;
53423     if( iParentIdx==0 ){                 
53424       nxDiv = 0;
53425     }else if( iParentIdx==i ){
53426       nxDiv = i-2;
53427     }else{
53428       nxDiv = iParentIdx-1;
53429     }
53430     i = 2;
53431   }
53432   if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
53433     pRight = &pParent->aData[pParent->hdrOffset+8];
53434   }else{
53435     pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
53436   }
53437   pgno = get4byte(pRight);
53438   while( 1 ){
53439     rc = getAndInitPage(pBt, pgno, &apOld[i]);
53440     if( rc ){
53441       memset(apOld, 0, (i+1)*sizeof(MemPage*));
53442       goto balance_cleanup;
53443     }
53444     nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
53445     if( (i--)==0 ) break;
53446
53447     if( i+nxDiv==pParent->aOvfl[0].idx && pParent->nOverflow ){
53448       apDiv[i] = pParent->aOvfl[0].pCell;
53449       pgno = get4byte(apDiv[i]);
53450       szNew[i] = cellSizePtr(pParent, apDiv[i]);
53451       pParent->nOverflow = 0;
53452     }else{
53453       apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
53454       pgno = get4byte(apDiv[i]);
53455       szNew[i] = cellSizePtr(pParent, apDiv[i]);
53456
53457       /* Drop the cell from the parent page. apDiv[i] still points to
53458       ** the cell within the parent, even though it has been dropped.
53459       ** This is safe because dropping a cell only overwrites the first
53460       ** four bytes of it, and this function does not need the first
53461       ** four bytes of the divider cell. So the pointer is safe to use
53462       ** later on.  
53463       **
53464       ** Unless SQLite is compiled in secure-delete mode. In this case,
53465       ** the dropCell() routine will overwrite the entire cell with zeroes.
53466       ** In this case, temporarily copy the cell into the aOvflSpace[]
53467       ** buffer. It will be copied out again as soon as the aSpace[] buffer
53468       ** is allocated.  */
53469       if( pBt->secureDelete ){
53470         int iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
53471         if( (iOff+szNew[i])>(int)pBt->usableSize ){
53472           rc = SQLITE_CORRUPT_BKPT;
53473           memset(apOld, 0, (i+1)*sizeof(MemPage*));
53474           goto balance_cleanup;
53475         }else{
53476           memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
53477           apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
53478         }
53479       }
53480       dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
53481     }
53482   }
53483
53484   /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
53485   ** alignment */
53486   nMaxCells = (nMaxCells + 3)&~3;
53487
53488   /*
53489   ** Allocate space for memory structures
53490   */
53491   k = pBt->pageSize + ROUND8(sizeof(MemPage));
53492   szScratch =
53493        nMaxCells*sizeof(u8*)                       /* apCell */
53494      + nMaxCells*sizeof(u16)                       /* szCell */
53495      + pBt->pageSize                               /* aSpace1 */
53496      + k*nOld;                                     /* Page copies (apCopy) */
53497   apCell = sqlite3ScratchMalloc( szScratch ); 
53498   if( apCell==0 ){
53499     rc = SQLITE_NOMEM;
53500     goto balance_cleanup;
53501   }
53502   szCell = (u16*)&apCell[nMaxCells];
53503   aSpace1 = (u8*)&szCell[nMaxCells];
53504   assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
53505
53506   /*
53507   ** Load pointers to all cells on sibling pages and the divider cells
53508   ** into the local apCell[] array.  Make copies of the divider cells
53509   ** into space obtained from aSpace1[] and remove the the divider Cells
53510   ** from pParent.
53511   **
53512   ** If the siblings are on leaf pages, then the child pointers of the
53513   ** divider cells are stripped from the cells before they are copied
53514   ** into aSpace1[].  In this way, all cells in apCell[] are without
53515   ** child pointers.  If siblings are not leaves, then all cell in
53516   ** apCell[] include child pointers.  Either way, all cells in apCell[]
53517   ** are alike.
53518   **
53519   ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
53520   **       leafData:  1 if pPage holds key+data and pParent holds only keys.
53521   */
53522   leafCorrection = apOld[0]->leaf*4;
53523   leafData = apOld[0]->hasData;
53524   for(i=0; i<nOld; i++){
53525     int limit;
53526     
53527     /* Before doing anything else, take a copy of the i'th original sibling
53528     ** The rest of this function will use data from the copies rather
53529     ** that the original pages since the original pages will be in the
53530     ** process of being overwritten.  */
53531     MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
53532     memcpy(pOld, apOld[i], sizeof(MemPage));
53533     pOld->aData = (void*)&pOld[1];
53534     memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
53535
53536     limit = pOld->nCell+pOld->nOverflow;
53537     if( pOld->nOverflow>0 ){
53538       for(j=0; j<limit; j++){
53539         assert( nCell<nMaxCells );
53540         apCell[nCell] = findOverflowCell(pOld, j);
53541         szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
53542         nCell++;
53543       }
53544     }else{
53545       u8 *aData = pOld->aData;
53546       u16 maskPage = pOld->maskPage;
53547       u16 cellOffset = pOld->cellOffset;
53548       for(j=0; j<limit; j++){
53549         assert( nCell<nMaxCells );
53550         apCell[nCell] = findCellv2(aData, maskPage, cellOffset, j);
53551         szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
53552         nCell++;
53553       }
53554     }       
53555     if( i<nOld-1 && !leafData){
53556       u16 sz = (u16)szNew[i];
53557       u8 *pTemp;
53558       assert( nCell<nMaxCells );
53559       szCell[nCell] = sz;
53560       pTemp = &aSpace1[iSpace1];
53561       iSpace1 += sz;
53562       assert( sz<=pBt->maxLocal+23 );
53563       assert( iSpace1 <= (int)pBt->pageSize );
53564       memcpy(pTemp, apDiv[i], sz);
53565       apCell[nCell] = pTemp+leafCorrection;
53566       assert( leafCorrection==0 || leafCorrection==4 );
53567       szCell[nCell] = szCell[nCell] - leafCorrection;
53568       if( !pOld->leaf ){
53569         assert( leafCorrection==0 );
53570         assert( pOld->hdrOffset==0 );
53571         /* The right pointer of the child page pOld becomes the left
53572         ** pointer of the divider cell */
53573         memcpy(apCell[nCell], &pOld->aData[8], 4);
53574       }else{
53575         assert( leafCorrection==4 );
53576         if( szCell[nCell]<4 ){
53577           /* Do not allow any cells smaller than 4 bytes. */
53578           szCell[nCell] = 4;
53579         }
53580       }
53581       nCell++;
53582     }
53583   }
53584
53585   /*
53586   ** Figure out the number of pages needed to hold all nCell cells.
53587   ** Store this number in "k".  Also compute szNew[] which is the total
53588   ** size of all cells on the i-th page and cntNew[] which is the index
53589   ** in apCell[] of the cell that divides page i from page i+1.  
53590   ** cntNew[k] should equal nCell.
53591   **
53592   ** Values computed by this block:
53593   **
53594   **           k: The total number of sibling pages
53595   **    szNew[i]: Spaced used on the i-th sibling page.
53596   **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to
53597   **              the right of the i-th sibling page.
53598   ** usableSpace: Number of bytes of space available on each sibling.
53599   ** 
53600   */
53601   usableSpace = pBt->usableSize - 12 + leafCorrection;
53602   for(subtotal=k=i=0; i<nCell; i++){
53603     assert( i<nMaxCells );
53604     subtotal += szCell[i] + 2;
53605     if( subtotal > usableSpace ){
53606       szNew[k] = subtotal - szCell[i];
53607       cntNew[k] = i;
53608       if( leafData ){ i--; }
53609       subtotal = 0;
53610       k++;
53611       if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
53612     }
53613   }
53614   szNew[k] = subtotal;
53615   cntNew[k] = nCell;
53616   k++;
53617
53618   /*
53619   ** The packing computed by the previous block is biased toward the siblings
53620   ** on the left side.  The left siblings are always nearly full, while the
53621   ** right-most sibling might be nearly empty.  This block of code attempts
53622   ** to adjust the packing of siblings to get a better balance.
53623   **
53624   ** This adjustment is more than an optimization.  The packing above might
53625   ** be so out of balance as to be illegal.  For example, the right-most
53626   ** sibling might be completely empty.  This adjustment is not optional.
53627   */
53628   for(i=k-1; i>0; i--){
53629     int szRight = szNew[i];  /* Size of sibling on the right */
53630     int szLeft = szNew[i-1]; /* Size of sibling on the left */
53631     int r;              /* Index of right-most cell in left sibling */
53632     int d;              /* Index of first cell to the left of right sibling */
53633
53634     r = cntNew[i-1] - 1;
53635     d = r + 1 - leafData;
53636     assert( d<nMaxCells );
53637     assert( r<nMaxCells );
53638     while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
53639       szRight += szCell[d] + 2;
53640       szLeft -= szCell[r] + 2;
53641       cntNew[i-1]--;
53642       r = cntNew[i-1] - 1;
53643       d = r + 1 - leafData;
53644     }
53645     szNew[i] = szRight;
53646     szNew[i-1] = szLeft;
53647   }
53648
53649   /* Either we found one or more cells (cntnew[0])>0) or pPage is
53650   ** a virtual root page.  A virtual root page is when the real root
53651   ** page is page 1 and we are the only child of that page.
53652   */
53653   assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
53654
53655   TRACE(("BALANCE: old: %d %d %d  ",
53656     apOld[0]->pgno, 
53657     nOld>=2 ? apOld[1]->pgno : 0,
53658     nOld>=3 ? apOld[2]->pgno : 0
53659   ));
53660
53661   /*
53662   ** Allocate k new pages.  Reuse old pages where possible.
53663   */
53664   if( apOld[0]->pgno<=1 ){
53665     rc = SQLITE_CORRUPT_BKPT;
53666     goto balance_cleanup;
53667   }
53668   pageFlags = apOld[0]->aData[0];
53669   for(i=0; i<k; i++){
53670     MemPage *pNew;
53671     if( i<nOld ){
53672       pNew = apNew[i] = apOld[i];
53673       apOld[i] = 0;
53674       rc = sqlite3PagerWrite(pNew->pDbPage);
53675       nNew++;
53676       if( rc ) goto balance_cleanup;
53677     }else{
53678       assert( i>0 );
53679       rc = allocateBtreePage(pBt, &pNew, &pgno, pgno, 0);
53680       if( rc ) goto balance_cleanup;
53681       apNew[i] = pNew;
53682       nNew++;
53683
53684       /* Set the pointer-map entry for the new sibling page. */
53685       if( ISAUTOVACUUM ){
53686         ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
53687         if( rc!=SQLITE_OK ){
53688           goto balance_cleanup;
53689         }
53690       }
53691     }
53692   }
53693
53694   /* Free any old pages that were not reused as new pages.
53695   */
53696   while( i<nOld ){
53697     freePage(apOld[i], &rc);
53698     if( rc ) goto balance_cleanup;
53699     releasePage(apOld[i]);
53700     apOld[i] = 0;
53701     i++;
53702   }
53703
53704   /*
53705   ** Put the new pages in accending order.  This helps to
53706   ** keep entries in the disk file in order so that a scan
53707   ** of the table is a linear scan through the file.  That
53708   ** in turn helps the operating system to deliver pages
53709   ** from the disk more rapidly.
53710   **
53711   ** An O(n^2) insertion sort algorithm is used, but since
53712   ** n is never more than NB (a small constant), that should
53713   ** not be a problem.
53714   **
53715   ** When NB==3, this one optimization makes the database
53716   ** about 25% faster for large insertions and deletions.
53717   */
53718   for(i=0; i<k-1; i++){
53719     int minV = apNew[i]->pgno;
53720     int minI = i;
53721     for(j=i+1; j<k; j++){
53722       if( apNew[j]->pgno<(unsigned)minV ){
53723         minI = j;
53724         minV = apNew[j]->pgno;
53725       }
53726     }
53727     if( minI>i ){
53728       MemPage *pT;
53729       pT = apNew[i];
53730       apNew[i] = apNew[minI];
53731       apNew[minI] = pT;
53732     }
53733   }
53734   TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
53735     apNew[0]->pgno, szNew[0],
53736     nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
53737     nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
53738     nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
53739     nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
53740
53741   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
53742   put4byte(pRight, apNew[nNew-1]->pgno);
53743
53744   /*
53745   ** Evenly distribute the data in apCell[] across the new pages.
53746   ** Insert divider cells into pParent as necessary.
53747   */
53748   j = 0;
53749   for(i=0; i<nNew; i++){
53750     /* Assemble the new sibling page. */
53751     MemPage *pNew = apNew[i];
53752     assert( j<nMaxCells );
53753     zeroPage(pNew, pageFlags);
53754     assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
53755     assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
53756     assert( pNew->nOverflow==0 );
53757
53758     j = cntNew[i];
53759
53760     /* If the sibling page assembled above was not the right-most sibling,
53761     ** insert a divider cell into the parent page.
53762     */
53763     assert( i<nNew-1 || j==nCell );
53764     if( j<nCell ){
53765       u8 *pCell;
53766       u8 *pTemp;
53767       int sz;
53768
53769       assert( j<nMaxCells );
53770       pCell = apCell[j];
53771       sz = szCell[j] + leafCorrection;
53772       pTemp = &aOvflSpace[iOvflSpace];
53773       if( !pNew->leaf ){
53774         memcpy(&pNew->aData[8], pCell, 4);
53775       }else if( leafData ){
53776         /* If the tree is a leaf-data tree, and the siblings are leaves, 
53777         ** then there is no divider cell in apCell[]. Instead, the divider 
53778         ** cell consists of the integer key for the right-most cell of 
53779         ** the sibling-page assembled above only.
53780         */
53781         CellInfo info;
53782         j--;
53783         btreeParseCellPtr(pNew, apCell[j], &info);
53784         pCell = pTemp;
53785         sz = 4 + putVarint(&pCell[4], info.nKey);
53786         pTemp = 0;
53787       }else{
53788         pCell -= 4;
53789         /* Obscure case for non-leaf-data trees: If the cell at pCell was
53790         ** previously stored on a leaf node, and its reported size was 4
53791         ** bytes, then it may actually be smaller than this 
53792         ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
53793         ** any cell). But it is important to pass the correct size to 
53794         ** insertCell(), so reparse the cell now.
53795         **
53796         ** Note that this can never happen in an SQLite data file, as all
53797         ** cells are at least 4 bytes. It only happens in b-trees used
53798         ** to evaluate "IN (SELECT ...)" and similar clauses.
53799         */
53800         if( szCell[j]==4 ){
53801           assert(leafCorrection==4);
53802           sz = cellSizePtr(pParent, pCell);
53803         }
53804       }
53805       iOvflSpace += sz;
53806       assert( sz<=pBt->maxLocal+23 );
53807       assert( iOvflSpace <= (int)pBt->pageSize );
53808       insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
53809       if( rc!=SQLITE_OK ) goto balance_cleanup;
53810       assert( sqlite3PagerIswriteable(pParent->pDbPage) );
53811
53812       j++;
53813       nxDiv++;
53814     }
53815   }
53816   assert( j==nCell );
53817   assert( nOld>0 );
53818   assert( nNew>0 );
53819   if( (pageFlags & PTF_LEAF)==0 ){
53820     u8 *zChild = &apCopy[nOld-1]->aData[8];
53821     memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
53822   }
53823
53824   if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
53825     /* The root page of the b-tree now contains no cells. The only sibling
53826     ** page is the right-child of the parent. Copy the contents of the
53827     ** child page into the parent, decreasing the overall height of the
53828     ** b-tree structure by one. This is described as the "balance-shallower"
53829     ** sub-algorithm in some documentation.
53830     **
53831     ** If this is an auto-vacuum database, the call to copyNodeContent() 
53832     ** sets all pointer-map entries corresponding to database image pages 
53833     ** for which the pointer is stored within the content being copied.
53834     **
53835     ** The second assert below verifies that the child page is defragmented
53836     ** (it must be, as it was just reconstructed using assemblePage()). This
53837     ** is important if the parent page happens to be page 1 of the database
53838     ** image.  */
53839     assert( nNew==1 );
53840     assert( apNew[0]->nFree == 
53841         (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2) 
53842     );
53843     copyNodeContent(apNew[0], pParent, &rc);
53844     freePage(apNew[0], &rc);
53845   }else if( ISAUTOVACUUM ){
53846     /* Fix the pointer-map entries for all the cells that were shifted around. 
53847     ** There are several different types of pointer-map entries that need to
53848     ** be dealt with by this routine. Some of these have been set already, but
53849     ** many have not. The following is a summary:
53850     **
53851     **   1) The entries associated with new sibling pages that were not
53852     **      siblings when this function was called. These have already
53853     **      been set. We don't need to worry about old siblings that were
53854     **      moved to the free-list - the freePage() code has taken care
53855     **      of those.
53856     **
53857     **   2) The pointer-map entries associated with the first overflow
53858     **      page in any overflow chains used by new divider cells. These 
53859     **      have also already been taken care of by the insertCell() code.
53860     **
53861     **   3) If the sibling pages are not leaves, then the child pages of
53862     **      cells stored on the sibling pages may need to be updated.
53863     **
53864     **   4) If the sibling pages are not internal intkey nodes, then any
53865     **      overflow pages used by these cells may need to be updated
53866     **      (internal intkey nodes never contain pointers to overflow pages).
53867     **
53868     **   5) If the sibling pages are not leaves, then the pointer-map
53869     **      entries for the right-child pages of each sibling may need
53870     **      to be updated.
53871     **
53872     ** Cases 1 and 2 are dealt with above by other code. The next
53873     ** block deals with cases 3 and 4 and the one after that, case 5. Since
53874     ** setting a pointer map entry is a relatively expensive operation, this
53875     ** code only sets pointer map entries for child or overflow pages that have
53876     ** actually moved between pages.  */
53877     MemPage *pNew = apNew[0];
53878     MemPage *pOld = apCopy[0];
53879     int nOverflow = pOld->nOverflow;
53880     int iNextOld = pOld->nCell + nOverflow;
53881     int iOverflow = (nOverflow ? pOld->aOvfl[0].idx : -1);
53882     j = 0;                             /* Current 'old' sibling page */
53883     k = 0;                             /* Current 'new' sibling page */
53884     for(i=0; i<nCell; i++){
53885       int isDivider = 0;
53886       while( i==iNextOld ){
53887         /* Cell i is the cell immediately following the last cell on old
53888         ** sibling page j. If the siblings are not leaf pages of an
53889         ** intkey b-tree, then cell i was a divider cell. */
53890         pOld = apCopy[++j];
53891         iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
53892         if( pOld->nOverflow ){
53893           nOverflow = pOld->nOverflow;
53894           iOverflow = i + !leafData + pOld->aOvfl[0].idx;
53895         }
53896         isDivider = !leafData;  
53897       }
53898
53899       assert(nOverflow>0 || iOverflow<i );
53900       assert(nOverflow<2 || pOld->aOvfl[0].idx==pOld->aOvfl[1].idx-1);
53901       assert(nOverflow<3 || pOld->aOvfl[1].idx==pOld->aOvfl[2].idx-1);
53902       if( i==iOverflow ){
53903         isDivider = 1;
53904         if( (--nOverflow)>0 ){
53905           iOverflow++;
53906         }
53907       }
53908
53909       if( i==cntNew[k] ){
53910         /* Cell i is the cell immediately following the last cell on new
53911         ** sibling page k. If the siblings are not leaf pages of an
53912         ** intkey b-tree, then cell i is a divider cell.  */
53913         pNew = apNew[++k];
53914         if( !leafData ) continue;
53915       }
53916       assert( j<nOld );
53917       assert( k<nNew );
53918
53919       /* If the cell was originally divider cell (and is not now) or
53920       ** an overflow cell, or if the cell was located on a different sibling
53921       ** page before the balancing, then the pointer map entries associated
53922       ** with any child or overflow pages need to be updated.  */
53923       if( isDivider || pOld->pgno!=pNew->pgno ){
53924         if( !leafCorrection ){
53925           ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
53926         }
53927         if( szCell[i]>pNew->minLocal ){
53928           ptrmapPutOvflPtr(pNew, apCell[i], &rc);
53929         }
53930       }
53931     }
53932
53933     if( !leafCorrection ){
53934       for(i=0; i<nNew; i++){
53935         u32 key = get4byte(&apNew[i]->aData[8]);
53936         ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
53937       }
53938     }
53939
53940 #if 0
53941     /* The ptrmapCheckPages() contains assert() statements that verify that
53942     ** all pointer map pages are set correctly. This is helpful while 
53943     ** debugging. This is usually disabled because a corrupt database may
53944     ** cause an assert() statement to fail.  */
53945     ptrmapCheckPages(apNew, nNew);
53946     ptrmapCheckPages(&pParent, 1);
53947 #endif
53948   }
53949
53950   assert( pParent->isInit );
53951   TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
53952           nOld, nNew, nCell));
53953
53954   /*
53955   ** Cleanup before returning.
53956   */
53957 balance_cleanup:
53958   sqlite3ScratchFree(apCell);
53959   for(i=0; i<nOld; i++){
53960     releasePage(apOld[i]);
53961   }
53962   for(i=0; i<nNew; i++){
53963     releasePage(apNew[i]);
53964   }
53965
53966   return rc;
53967 }
53968
53969
53970 /*
53971 ** This function is called when the root page of a b-tree structure is
53972 ** overfull (has one or more overflow pages).
53973 **
53974 ** A new child page is allocated and the contents of the current root
53975 ** page, including overflow cells, are copied into the child. The root
53976 ** page is then overwritten to make it an empty page with the right-child 
53977 ** pointer pointing to the new page.
53978 **
53979 ** Before returning, all pointer-map entries corresponding to pages 
53980 ** that the new child-page now contains pointers to are updated. The
53981 ** entry corresponding to the new right-child pointer of the root
53982 ** page is also updated.
53983 **
53984 ** If successful, *ppChild is set to contain a reference to the child 
53985 ** page and SQLITE_OK is returned. In this case the caller is required
53986 ** to call releasePage() on *ppChild exactly once. If an error occurs,
53987 ** an error code is returned and *ppChild is set to 0.
53988 */
53989 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
53990   int rc;                        /* Return value from subprocedures */
53991   MemPage *pChild = 0;           /* Pointer to a new child page */
53992   Pgno pgnoChild = 0;            /* Page number of the new child page */
53993   BtShared *pBt = pRoot->pBt;    /* The BTree */
53994
53995   assert( pRoot->nOverflow>0 );
53996   assert( sqlite3_mutex_held(pBt->mutex) );
53997
53998   /* Make pRoot, the root page of the b-tree, writable. Allocate a new 
53999   ** page that will become the new right-child of pPage. Copy the contents
54000   ** of the node stored on pRoot into the new child page.
54001   */
54002   rc = sqlite3PagerWrite(pRoot->pDbPage);
54003   if( rc==SQLITE_OK ){
54004     rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
54005     copyNodeContent(pRoot, pChild, &rc);
54006     if( ISAUTOVACUUM ){
54007       ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
54008     }
54009   }
54010   if( rc ){
54011     *ppChild = 0;
54012     releasePage(pChild);
54013     return rc;
54014   }
54015   assert( sqlite3PagerIswriteable(pChild->pDbPage) );
54016   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
54017   assert( pChild->nCell==pRoot->nCell );
54018
54019   TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
54020
54021   /* Copy the overflow cells from pRoot to pChild */
54022   memcpy(pChild->aOvfl, pRoot->aOvfl, pRoot->nOverflow*sizeof(pRoot->aOvfl[0]));
54023   pChild->nOverflow = pRoot->nOverflow;
54024
54025   /* Zero the contents of pRoot. Then install pChild as the right-child. */
54026   zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
54027   put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
54028
54029   *ppChild = pChild;
54030   return SQLITE_OK;
54031 }
54032
54033 /*
54034 ** The page that pCur currently points to has just been modified in
54035 ** some way. This function figures out if this modification means the
54036 ** tree needs to be balanced, and if so calls the appropriate balancing 
54037 ** routine. Balancing routines are:
54038 **
54039 **   balance_quick()
54040 **   balance_deeper()
54041 **   balance_nonroot()
54042 */
54043 static int balance(BtCursor *pCur){
54044   int rc = SQLITE_OK;
54045   const int nMin = pCur->pBt->usableSize * 2 / 3;
54046   u8 aBalanceQuickSpace[13];
54047   u8 *pFree = 0;
54048
54049   TESTONLY( int balance_quick_called = 0 );
54050   TESTONLY( int balance_deeper_called = 0 );
54051
54052   do {
54053     int iPage = pCur->iPage;
54054     MemPage *pPage = pCur->apPage[iPage];
54055
54056     if( iPage==0 ){
54057       if( pPage->nOverflow ){
54058         /* The root page of the b-tree is overfull. In this case call the
54059         ** balance_deeper() function to create a new child for the root-page
54060         ** and copy the current contents of the root-page to it. The
54061         ** next iteration of the do-loop will balance the child page.
54062         */ 
54063         assert( (balance_deeper_called++)==0 );
54064         rc = balance_deeper(pPage, &pCur->apPage[1]);
54065         if( rc==SQLITE_OK ){
54066           pCur->iPage = 1;
54067           pCur->aiIdx[0] = 0;
54068           pCur->aiIdx[1] = 0;
54069           assert( pCur->apPage[1]->nOverflow );
54070         }
54071       }else{
54072         break;
54073       }
54074     }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
54075       break;
54076     }else{
54077       MemPage * const pParent = pCur->apPage[iPage-1];
54078       int const iIdx = pCur->aiIdx[iPage-1];
54079
54080       rc = sqlite3PagerWrite(pParent->pDbPage);
54081       if( rc==SQLITE_OK ){
54082 #ifndef SQLITE_OMIT_QUICKBALANCE
54083         if( pPage->hasData
54084          && pPage->nOverflow==1
54085          && pPage->aOvfl[0].idx==pPage->nCell
54086          && pParent->pgno!=1
54087          && pParent->nCell==iIdx
54088         ){
54089           /* Call balance_quick() to create a new sibling of pPage on which
54090           ** to store the overflow cell. balance_quick() inserts a new cell
54091           ** into pParent, which may cause pParent overflow. If this
54092           ** happens, the next interation of the do-loop will balance pParent 
54093           ** use either balance_nonroot() or balance_deeper(). Until this
54094           ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
54095           ** buffer. 
54096           **
54097           ** The purpose of the following assert() is to check that only a
54098           ** single call to balance_quick() is made for each call to this
54099           ** function. If this were not verified, a subtle bug involving reuse
54100           ** of the aBalanceQuickSpace[] might sneak in.
54101           */
54102           assert( (balance_quick_called++)==0 );
54103           rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
54104         }else
54105 #endif
54106         {
54107           /* In this case, call balance_nonroot() to redistribute cells
54108           ** between pPage and up to 2 of its sibling pages. This involves
54109           ** modifying the contents of pParent, which may cause pParent to
54110           ** become overfull or underfull. The next iteration of the do-loop
54111           ** will balance the parent page to correct this.
54112           ** 
54113           ** If the parent page becomes overfull, the overflow cell or cells
54114           ** are stored in the pSpace buffer allocated immediately below. 
54115           ** A subsequent iteration of the do-loop will deal with this by
54116           ** calling balance_nonroot() (balance_deeper() may be called first,
54117           ** but it doesn't deal with overflow cells - just moves them to a
54118           ** different page). Once this subsequent call to balance_nonroot() 
54119           ** has completed, it is safe to release the pSpace buffer used by
54120           ** the previous call, as the overflow cell data will have been 
54121           ** copied either into the body of a database page or into the new
54122           ** pSpace buffer passed to the latter call to balance_nonroot().
54123           */
54124           u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
54125           rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1);
54126           if( pFree ){
54127             /* If pFree is not NULL, it points to the pSpace buffer used 
54128             ** by a previous call to balance_nonroot(). Its contents are
54129             ** now stored either on real database pages or within the 
54130             ** new pSpace buffer, so it may be safely freed here. */
54131             sqlite3PageFree(pFree);
54132           }
54133
54134           /* The pSpace buffer will be freed after the next call to
54135           ** balance_nonroot(), or just before this function returns, whichever
54136           ** comes first. */
54137           pFree = pSpace;
54138         }
54139       }
54140
54141       pPage->nOverflow = 0;
54142
54143       /* The next iteration of the do-loop balances the parent page. */
54144       releasePage(pPage);
54145       pCur->iPage--;
54146     }
54147   }while( rc==SQLITE_OK );
54148
54149   if( pFree ){
54150     sqlite3PageFree(pFree);
54151   }
54152   return rc;
54153 }
54154
54155
54156 /*
54157 ** Insert a new record into the BTree.  The key is given by (pKey,nKey)
54158 ** and the data is given by (pData,nData).  The cursor is used only to
54159 ** define what table the record should be inserted into.  The cursor
54160 ** is left pointing at a random location.
54161 **
54162 ** For an INTKEY table, only the nKey value of the key is used.  pKey is
54163 ** ignored.  For a ZERODATA table, the pData and nData are both ignored.
54164 **
54165 ** If the seekResult parameter is non-zero, then a successful call to
54166 ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
54167 ** been performed. seekResult is the search result returned (a negative
54168 ** number if pCur points at an entry that is smaller than (pKey, nKey), or
54169 ** a positive value if pCur points at an etry that is larger than 
54170 ** (pKey, nKey)). 
54171 **
54172 ** If the seekResult parameter is non-zero, then the caller guarantees that
54173 ** cursor pCur is pointing at the existing copy of a row that is to be
54174 ** overwritten.  If the seekResult parameter is 0, then cursor pCur may
54175 ** point to any entry or to no entry at all and so this function has to seek
54176 ** the cursor before the new key can be inserted.
54177 */
54178 SQLITE_PRIVATE int sqlite3BtreeInsert(
54179   BtCursor *pCur,                /* Insert data into the table of this cursor */
54180   const void *pKey, i64 nKey,    /* The key of the new record */
54181   const void *pData, int nData,  /* The data of the new record */
54182   int nZero,                     /* Number of extra 0 bytes to append to data */
54183   int appendBias,                /* True if this is likely an append */
54184   int seekResult                 /* Result of prior MovetoUnpacked() call */
54185 ){
54186   int rc;
54187   int loc = seekResult;          /* -1: before desired location  +1: after */
54188   int szNew = 0;
54189   int idx;
54190   MemPage *pPage;
54191   Btree *p = pCur->pBtree;
54192   BtShared *pBt = p->pBt;
54193   unsigned char *oldCell;
54194   unsigned char *newCell = 0;
54195
54196   if( pCur->eState==CURSOR_FAULT ){
54197     assert( pCur->skipNext!=SQLITE_OK );
54198     return pCur->skipNext;
54199   }
54200
54201   assert( cursorHoldsMutex(pCur) );
54202   assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE && !pBt->readOnly );
54203   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
54204
54205   /* Assert that the caller has been consistent. If this cursor was opened
54206   ** expecting an index b-tree, then the caller should be inserting blob
54207   ** keys with no associated data. If the cursor was opened expecting an
54208   ** intkey table, the caller should be inserting integer keys with a
54209   ** blob of associated data.  */
54210   assert( (pKey==0)==(pCur->pKeyInfo==0) );
54211
54212   /* If this is an insert into a table b-tree, invalidate any incrblob 
54213   ** cursors open on the row being replaced (assuming this is a replace
54214   ** operation - if it is not, the following is a no-op).  */
54215   if( pCur->pKeyInfo==0 ){
54216     invalidateIncrblobCursors(p, nKey, 0);
54217   }
54218
54219   /* Save the positions of any other cursors open on this table.
54220   **
54221   ** In some cases, the call to btreeMoveto() below is a no-op. For
54222   ** example, when inserting data into a table with auto-generated integer
54223   ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the 
54224   ** integer key to use. It then calls this function to actually insert the 
54225   ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
54226   ** that the cursor is already where it needs to be and returns without
54227   ** doing any work. To avoid thwarting these optimizations, it is important
54228   ** not to clear the cursor here.
54229   */
54230   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
54231   if( rc ) return rc;
54232   if( !loc ){
54233     rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
54234     if( rc ) return rc;
54235   }
54236   assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
54237
54238   pPage = pCur->apPage[pCur->iPage];
54239   assert( pPage->intKey || nKey>=0 );
54240   assert( pPage->leaf || !pPage->intKey );
54241
54242   TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
54243           pCur->pgnoRoot, nKey, nData, pPage->pgno,
54244           loc==0 ? "overwrite" : "new entry"));
54245   assert( pPage->isInit );
54246   allocateTempSpace(pBt);
54247   newCell = pBt->pTmpSpace;
54248   if( newCell==0 ) return SQLITE_NOMEM;
54249   rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
54250   if( rc ) goto end_insert;
54251   assert( szNew==cellSizePtr(pPage, newCell) );
54252   assert( szNew <= MX_CELL_SIZE(pBt) );
54253   idx = pCur->aiIdx[pCur->iPage];
54254   if( loc==0 ){
54255     u16 szOld;
54256     assert( idx<pPage->nCell );
54257     rc = sqlite3PagerWrite(pPage->pDbPage);
54258     if( rc ){
54259       goto end_insert;
54260     }
54261     oldCell = findCell(pPage, idx);
54262     if( !pPage->leaf ){
54263       memcpy(newCell, oldCell, 4);
54264     }
54265     szOld = cellSizePtr(pPage, oldCell);
54266     rc = clearCell(pPage, oldCell);
54267     dropCell(pPage, idx, szOld, &rc);
54268     if( rc ) goto end_insert;
54269   }else if( loc<0 && pPage->nCell>0 ){
54270     assert( pPage->leaf );
54271     idx = ++pCur->aiIdx[pCur->iPage];
54272   }else{
54273     assert( pPage->leaf );
54274   }
54275   insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
54276   assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
54277
54278   /* If no error has occured and pPage has an overflow cell, call balance() 
54279   ** to redistribute the cells within the tree. Since balance() may move
54280   ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
54281   ** variables.
54282   **
54283   ** Previous versions of SQLite called moveToRoot() to move the cursor
54284   ** back to the root page as balance() used to invalidate the contents
54285   ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
54286   ** set the cursor state to "invalid". This makes common insert operations
54287   ** slightly faster.
54288   **
54289   ** There is a subtle but important optimization here too. When inserting
54290   ** multiple records into an intkey b-tree using a single cursor (as can
54291   ** happen while processing an "INSERT INTO ... SELECT" statement), it
54292   ** is advantageous to leave the cursor pointing to the last entry in
54293   ** the b-tree if possible. If the cursor is left pointing to the last
54294   ** entry in the table, and the next row inserted has an integer key
54295   ** larger than the largest existing key, it is possible to insert the
54296   ** row without seeking the cursor. This can be a big performance boost.
54297   */
54298   pCur->info.nSize = 0;
54299   pCur->validNKey = 0;
54300   if( rc==SQLITE_OK && pPage->nOverflow ){
54301     rc = balance(pCur);
54302
54303     /* Must make sure nOverflow is reset to zero even if the balance()
54304     ** fails. Internal data structure corruption will result otherwise. 
54305     ** Also, set the cursor state to invalid. This stops saveCursorPosition()
54306     ** from trying to save the current position of the cursor.  */
54307     pCur->apPage[pCur->iPage]->nOverflow = 0;
54308     pCur->eState = CURSOR_INVALID;
54309   }
54310   assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
54311
54312 end_insert:
54313   return rc;
54314 }
54315
54316 /*
54317 ** Delete the entry that the cursor is pointing to.  The cursor
54318 ** is left pointing at a arbitrary location.
54319 */
54320 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
54321   Btree *p = pCur->pBtree;
54322   BtShared *pBt = p->pBt;              
54323   int rc;                              /* Return code */
54324   MemPage *pPage;                      /* Page to delete cell from */
54325   unsigned char *pCell;                /* Pointer to cell to delete */
54326   int iCellIdx;                        /* Index of cell to delete */
54327   int iCellDepth;                      /* Depth of node containing pCell */ 
54328
54329   assert( cursorHoldsMutex(pCur) );
54330   assert( pBt->inTransaction==TRANS_WRITE );
54331   assert( !pBt->readOnly );
54332   assert( pCur->wrFlag );
54333   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
54334   assert( !hasReadConflicts(p, pCur->pgnoRoot) );
54335
54336   if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell) 
54337    || NEVER(pCur->eState!=CURSOR_VALID)
54338   ){
54339     return SQLITE_ERROR;  /* Something has gone awry. */
54340   }
54341
54342   /* If this is a delete operation to remove a row from a table b-tree,
54343   ** invalidate any incrblob cursors open on the row being deleted.  */
54344   if( pCur->pKeyInfo==0 ){
54345     invalidateIncrblobCursors(p, pCur->info.nKey, 0);
54346   }
54347
54348   iCellDepth = pCur->iPage;
54349   iCellIdx = pCur->aiIdx[iCellDepth];
54350   pPage = pCur->apPage[iCellDepth];
54351   pCell = findCell(pPage, iCellIdx);
54352
54353   /* If the page containing the entry to delete is not a leaf page, move
54354   ** the cursor to the largest entry in the tree that is smaller than
54355   ** the entry being deleted. This cell will replace the cell being deleted
54356   ** from the internal node. The 'previous' entry is used for this instead
54357   ** of the 'next' entry, as the previous entry is always a part of the
54358   ** sub-tree headed by the child page of the cell being deleted. This makes
54359   ** balancing the tree following the delete operation easier.  */
54360   if( !pPage->leaf ){
54361     int notUsed;
54362     rc = sqlite3BtreePrevious(pCur, &notUsed);
54363     if( rc ) return rc;
54364   }
54365
54366   /* Save the positions of any other cursors open on this table before
54367   ** making any modifications. Make the page containing the entry to be 
54368   ** deleted writable. Then free any overflow pages associated with the 
54369   ** entry and finally remove the cell itself from within the page.  
54370   */
54371   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
54372   if( rc ) return rc;
54373   rc = sqlite3PagerWrite(pPage->pDbPage);
54374   if( rc ) return rc;
54375   rc = clearCell(pPage, pCell);
54376   dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
54377   if( rc ) return rc;
54378
54379   /* If the cell deleted was not located on a leaf page, then the cursor
54380   ** is currently pointing to the largest entry in the sub-tree headed
54381   ** by the child-page of the cell that was just deleted from an internal
54382   ** node. The cell from the leaf node needs to be moved to the internal
54383   ** node to replace the deleted cell.  */
54384   if( !pPage->leaf ){
54385     MemPage *pLeaf = pCur->apPage[pCur->iPage];
54386     int nCell;
54387     Pgno n = pCur->apPage[iCellDepth+1]->pgno;
54388     unsigned char *pTmp;
54389
54390     pCell = findCell(pLeaf, pLeaf->nCell-1);
54391     nCell = cellSizePtr(pLeaf, pCell);
54392     assert( MX_CELL_SIZE(pBt) >= nCell );
54393
54394     allocateTempSpace(pBt);
54395     pTmp = pBt->pTmpSpace;
54396
54397     rc = sqlite3PagerWrite(pLeaf->pDbPage);
54398     insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
54399     dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
54400     if( rc ) return rc;
54401   }
54402
54403   /* Balance the tree. If the entry deleted was located on a leaf page,
54404   ** then the cursor still points to that page. In this case the first
54405   ** call to balance() repairs the tree, and the if(...) condition is
54406   ** never true.
54407   **
54408   ** Otherwise, if the entry deleted was on an internal node page, then
54409   ** pCur is pointing to the leaf page from which a cell was removed to
54410   ** replace the cell deleted from the internal node. This is slightly
54411   ** tricky as the leaf node may be underfull, and the internal node may
54412   ** be either under or overfull. In this case run the balancing algorithm
54413   ** on the leaf node first. If the balance proceeds far enough up the
54414   ** tree that we can be sure that any problem in the internal node has
54415   ** been corrected, so be it. Otherwise, after balancing the leaf node,
54416   ** walk the cursor up the tree to the internal node and balance it as 
54417   ** well.  */
54418   rc = balance(pCur);
54419   if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
54420     while( pCur->iPage>iCellDepth ){
54421       releasePage(pCur->apPage[pCur->iPage--]);
54422     }
54423     rc = balance(pCur);
54424   }
54425
54426   if( rc==SQLITE_OK ){
54427     moveToRoot(pCur);
54428   }
54429   return rc;
54430 }
54431
54432 /*
54433 ** Create a new BTree table.  Write into *piTable the page
54434 ** number for the root page of the new table.
54435 **
54436 ** The type of type is determined by the flags parameter.  Only the
54437 ** following values of flags are currently in use.  Other values for
54438 ** flags might not work:
54439 **
54440 **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
54441 **     BTREE_ZERODATA                  Used for SQL indices
54442 */
54443 static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
54444   BtShared *pBt = p->pBt;
54445   MemPage *pRoot;
54446   Pgno pgnoRoot;
54447   int rc;
54448   int ptfFlags;          /* Page-type flage for the root page of new table */
54449
54450   assert( sqlite3BtreeHoldsMutex(p) );
54451   assert( pBt->inTransaction==TRANS_WRITE );
54452   assert( !pBt->readOnly );
54453
54454 #ifdef SQLITE_OMIT_AUTOVACUUM
54455   rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
54456   if( rc ){
54457     return rc;
54458   }
54459 #else
54460   if( pBt->autoVacuum ){
54461     Pgno pgnoMove;      /* Move a page here to make room for the root-page */
54462     MemPage *pPageMove; /* The page to move to. */
54463
54464     /* Creating a new table may probably require moving an existing database
54465     ** to make room for the new tables root page. In case this page turns
54466     ** out to be an overflow page, delete all overflow page-map caches
54467     ** held by open cursors.
54468     */
54469     invalidateAllOverflowCache(pBt);
54470
54471     /* Read the value of meta[3] from the database to determine where the
54472     ** root page of the new table should go. meta[3] is the largest root-page
54473     ** created so far, so the new root-page is (meta[3]+1).
54474     */
54475     sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
54476     pgnoRoot++;
54477
54478     /* The new root-page may not be allocated on a pointer-map page, or the
54479     ** PENDING_BYTE page.
54480     */
54481     while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
54482         pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
54483       pgnoRoot++;
54484     }
54485     assert( pgnoRoot>=3 );
54486
54487     /* Allocate a page. The page that currently resides at pgnoRoot will
54488     ** be moved to the allocated page (unless the allocated page happens
54489     ** to reside at pgnoRoot).
54490     */
54491     rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
54492     if( rc!=SQLITE_OK ){
54493       return rc;
54494     }
54495
54496     if( pgnoMove!=pgnoRoot ){
54497       /* pgnoRoot is the page that will be used for the root-page of
54498       ** the new table (assuming an error did not occur). But we were
54499       ** allocated pgnoMove. If required (i.e. if it was not allocated
54500       ** by extending the file), the current page at position pgnoMove
54501       ** is already journaled.
54502       */
54503       u8 eType = 0;
54504       Pgno iPtrPage = 0;
54505
54506       releasePage(pPageMove);
54507
54508       /* Move the page currently at pgnoRoot to pgnoMove. */
54509       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
54510       if( rc!=SQLITE_OK ){
54511         return rc;
54512       }
54513       rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
54514       if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
54515         rc = SQLITE_CORRUPT_BKPT;
54516       }
54517       if( rc!=SQLITE_OK ){
54518         releasePage(pRoot);
54519         return rc;
54520       }
54521       assert( eType!=PTRMAP_ROOTPAGE );
54522       assert( eType!=PTRMAP_FREEPAGE );
54523       rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
54524       releasePage(pRoot);
54525
54526       /* Obtain the page at pgnoRoot */
54527       if( rc!=SQLITE_OK ){
54528         return rc;
54529       }
54530       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
54531       if( rc!=SQLITE_OK ){
54532         return rc;
54533       }
54534       rc = sqlite3PagerWrite(pRoot->pDbPage);
54535       if( rc!=SQLITE_OK ){
54536         releasePage(pRoot);
54537         return rc;
54538       }
54539     }else{
54540       pRoot = pPageMove;
54541     } 
54542
54543     /* Update the pointer-map and meta-data with the new root-page number. */
54544     ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
54545     if( rc ){
54546       releasePage(pRoot);
54547       return rc;
54548     }
54549
54550     /* When the new root page was allocated, page 1 was made writable in
54551     ** order either to increase the database filesize, or to decrement the
54552     ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
54553     */
54554     assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
54555     rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
54556     if( NEVER(rc) ){
54557       releasePage(pRoot);
54558       return rc;
54559     }
54560
54561   }else{
54562     rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
54563     if( rc ) return rc;
54564   }
54565 #endif
54566   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
54567   if( createTabFlags & BTREE_INTKEY ){
54568     ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
54569   }else{
54570     ptfFlags = PTF_ZERODATA | PTF_LEAF;
54571   }
54572   zeroPage(pRoot, ptfFlags);
54573   sqlite3PagerUnref(pRoot->pDbPage);
54574   assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
54575   *piTable = (int)pgnoRoot;
54576   return SQLITE_OK;
54577 }
54578 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
54579   int rc;
54580   sqlite3BtreeEnter(p);
54581   rc = btreeCreateTable(p, piTable, flags);
54582   sqlite3BtreeLeave(p);
54583   return rc;
54584 }
54585
54586 /*
54587 ** Erase the given database page and all its children.  Return
54588 ** the page to the freelist.
54589 */
54590 static int clearDatabasePage(
54591   BtShared *pBt,           /* The BTree that contains the table */
54592   Pgno pgno,               /* Page number to clear */
54593   int freePageFlag,        /* Deallocate page if true */
54594   int *pnChange            /* Add number of Cells freed to this counter */
54595 ){
54596   MemPage *pPage;
54597   int rc;
54598   unsigned char *pCell;
54599   int i;
54600
54601   assert( sqlite3_mutex_held(pBt->mutex) );
54602   if( pgno>btreePagecount(pBt) ){
54603     return SQLITE_CORRUPT_BKPT;
54604   }
54605
54606   rc = getAndInitPage(pBt, pgno, &pPage);
54607   if( rc ) return rc;
54608   for(i=0; i<pPage->nCell; i++){
54609     pCell = findCell(pPage, i);
54610     if( !pPage->leaf ){
54611       rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
54612       if( rc ) goto cleardatabasepage_out;
54613     }
54614     rc = clearCell(pPage, pCell);
54615     if( rc ) goto cleardatabasepage_out;
54616   }
54617   if( !pPage->leaf ){
54618     rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
54619     if( rc ) goto cleardatabasepage_out;
54620   }else if( pnChange ){
54621     assert( pPage->intKey );
54622     *pnChange += pPage->nCell;
54623   }
54624   if( freePageFlag ){
54625     freePage(pPage, &rc);
54626   }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
54627     zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
54628   }
54629
54630 cleardatabasepage_out:
54631   releasePage(pPage);
54632   return rc;
54633 }
54634
54635 /*
54636 ** Delete all information from a single table in the database.  iTable is
54637 ** the page number of the root of the table.  After this routine returns,
54638 ** the root page is empty, but still exists.
54639 **
54640 ** This routine will fail with SQLITE_LOCKED if there are any open
54641 ** read cursors on the table.  Open write cursors are moved to the
54642 ** root of the table.
54643 **
54644 ** If pnChange is not NULL, then table iTable must be an intkey table. The
54645 ** integer value pointed to by pnChange is incremented by the number of
54646 ** entries in the table.
54647 */
54648 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
54649   int rc;
54650   BtShared *pBt = p->pBt;
54651   sqlite3BtreeEnter(p);
54652   assert( p->inTrans==TRANS_WRITE );
54653
54654   /* Invalidate all incrblob cursors open on table iTable (assuming iTable
54655   ** is the root of a table b-tree - if it is not, the following call is
54656   ** a no-op).  */
54657   invalidateIncrblobCursors(p, 0, 1);
54658
54659   rc = saveAllCursors(pBt, (Pgno)iTable, 0);
54660   if( SQLITE_OK==rc ){
54661     rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
54662   }
54663   sqlite3BtreeLeave(p);
54664   return rc;
54665 }
54666
54667 /*
54668 ** Erase all information in a table and add the root of the table to
54669 ** the freelist.  Except, the root of the principle table (the one on
54670 ** page 1) is never added to the freelist.
54671 **
54672 ** This routine will fail with SQLITE_LOCKED if there are any open
54673 ** cursors on the table.
54674 **
54675 ** If AUTOVACUUM is enabled and the page at iTable is not the last
54676 ** root page in the database file, then the last root page 
54677 ** in the database file is moved into the slot formerly occupied by
54678 ** iTable and that last slot formerly occupied by the last root page
54679 ** is added to the freelist instead of iTable.  In this say, all
54680 ** root pages are kept at the beginning of the database file, which
54681 ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the 
54682 ** page number that used to be the last root page in the file before
54683 ** the move.  If no page gets moved, *piMoved is set to 0.
54684 ** The last root page is recorded in meta[3] and the value of
54685 ** meta[3] is updated by this procedure.
54686 */
54687 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
54688   int rc;
54689   MemPage *pPage = 0;
54690   BtShared *pBt = p->pBt;
54691
54692   assert( sqlite3BtreeHoldsMutex(p) );
54693   assert( p->inTrans==TRANS_WRITE );
54694
54695   /* It is illegal to drop a table if any cursors are open on the
54696   ** database. This is because in auto-vacuum mode the backend may
54697   ** need to move another root-page to fill a gap left by the deleted
54698   ** root page. If an open cursor was using this page a problem would 
54699   ** occur.
54700   **
54701   ** This error is caught long before control reaches this point.
54702   */
54703   if( NEVER(pBt->pCursor) ){
54704     sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
54705     return SQLITE_LOCKED_SHAREDCACHE;
54706   }
54707
54708   rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
54709   if( rc ) return rc;
54710   rc = sqlite3BtreeClearTable(p, iTable, 0);
54711   if( rc ){
54712     releasePage(pPage);
54713     return rc;
54714   }
54715
54716   *piMoved = 0;
54717
54718   if( iTable>1 ){
54719 #ifdef SQLITE_OMIT_AUTOVACUUM
54720     freePage(pPage, &rc);
54721     releasePage(pPage);
54722 #else
54723     if( pBt->autoVacuum ){
54724       Pgno maxRootPgno;
54725       sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
54726
54727       if( iTable==maxRootPgno ){
54728         /* If the table being dropped is the table with the largest root-page
54729         ** number in the database, put the root page on the free list. 
54730         */
54731         freePage(pPage, &rc);
54732         releasePage(pPage);
54733         if( rc!=SQLITE_OK ){
54734           return rc;
54735         }
54736       }else{
54737         /* The table being dropped does not have the largest root-page
54738         ** number in the database. So move the page that does into the 
54739         ** gap left by the deleted root-page.
54740         */
54741         MemPage *pMove;
54742         releasePage(pPage);
54743         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
54744         if( rc!=SQLITE_OK ){
54745           return rc;
54746         }
54747         rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
54748         releasePage(pMove);
54749         if( rc!=SQLITE_OK ){
54750           return rc;
54751         }
54752         pMove = 0;
54753         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
54754         freePage(pMove, &rc);
54755         releasePage(pMove);
54756         if( rc!=SQLITE_OK ){
54757           return rc;
54758         }
54759         *piMoved = maxRootPgno;
54760       }
54761
54762       /* Set the new 'max-root-page' value in the database header. This
54763       ** is the old value less one, less one more if that happens to
54764       ** be a root-page number, less one again if that is the
54765       ** PENDING_BYTE_PAGE.
54766       */
54767       maxRootPgno--;
54768       while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
54769              || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
54770         maxRootPgno--;
54771       }
54772       assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
54773
54774       rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
54775     }else{
54776       freePage(pPage, &rc);
54777       releasePage(pPage);
54778     }
54779 #endif
54780   }else{
54781     /* If sqlite3BtreeDropTable was called on page 1.
54782     ** This really never should happen except in a corrupt
54783     ** database. 
54784     */
54785     zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
54786     releasePage(pPage);
54787   }
54788   return rc;  
54789 }
54790 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
54791   int rc;
54792   sqlite3BtreeEnter(p);
54793   rc = btreeDropTable(p, iTable, piMoved);
54794   sqlite3BtreeLeave(p);
54795   return rc;
54796 }
54797
54798
54799 /*
54800 ** This function may only be called if the b-tree connection already
54801 ** has a read or write transaction open on the database.
54802 **
54803 ** Read the meta-information out of a database file.  Meta[0]
54804 ** is the number of free pages currently in the database.  Meta[1]
54805 ** through meta[15] are available for use by higher layers.  Meta[0]
54806 ** is read-only, the others are read/write.
54807 ** 
54808 ** The schema layer numbers meta values differently.  At the schema
54809 ** layer (and the SetCookie and ReadCookie opcodes) the number of
54810 ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
54811 */
54812 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
54813   BtShared *pBt = p->pBt;
54814
54815   sqlite3BtreeEnter(p);
54816   assert( p->inTrans>TRANS_NONE );
54817   assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
54818   assert( pBt->pPage1 );
54819   assert( idx>=0 && idx<=15 );
54820
54821   *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
54822
54823   /* If auto-vacuum is disabled in this build and this is an auto-vacuum
54824   ** database, mark the database as read-only.  */
54825 #ifdef SQLITE_OMIT_AUTOVACUUM
54826   if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ) pBt->readOnly = 1;
54827 #endif
54828
54829   sqlite3BtreeLeave(p);
54830 }
54831
54832 /*
54833 ** Write meta-information back into the database.  Meta[0] is
54834 ** read-only and may not be written.
54835 */
54836 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
54837   BtShared *pBt = p->pBt;
54838   unsigned char *pP1;
54839   int rc;
54840   assert( idx>=1 && idx<=15 );
54841   sqlite3BtreeEnter(p);
54842   assert( p->inTrans==TRANS_WRITE );
54843   assert( pBt->pPage1!=0 );
54844   pP1 = pBt->pPage1->aData;
54845   rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
54846   if( rc==SQLITE_OK ){
54847     put4byte(&pP1[36 + idx*4], iMeta);
54848 #ifndef SQLITE_OMIT_AUTOVACUUM
54849     if( idx==BTREE_INCR_VACUUM ){
54850       assert( pBt->autoVacuum || iMeta==0 );
54851       assert( iMeta==0 || iMeta==1 );
54852       pBt->incrVacuum = (u8)iMeta;
54853     }
54854 #endif
54855   }
54856   sqlite3BtreeLeave(p);
54857   return rc;
54858 }
54859
54860 #ifndef SQLITE_OMIT_BTREECOUNT
54861 /*
54862 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
54863 ** number of entries in the b-tree and write the result to *pnEntry.
54864 **
54865 ** SQLITE_OK is returned if the operation is successfully executed. 
54866 ** Otherwise, if an error is encountered (i.e. an IO error or database
54867 ** corruption) an SQLite error code is returned.
54868 */
54869 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
54870   i64 nEntry = 0;                      /* Value to return in *pnEntry */
54871   int rc;                              /* Return code */
54872   rc = moveToRoot(pCur);
54873
54874   /* Unless an error occurs, the following loop runs one iteration for each
54875   ** page in the B-Tree structure (not including overflow pages). 
54876   */
54877   while( rc==SQLITE_OK ){
54878     int iIdx;                          /* Index of child node in parent */
54879     MemPage *pPage;                    /* Current page of the b-tree */
54880
54881     /* If this is a leaf page or the tree is not an int-key tree, then 
54882     ** this page contains countable entries. Increment the entry counter
54883     ** accordingly.
54884     */
54885     pPage = pCur->apPage[pCur->iPage];
54886     if( pPage->leaf || !pPage->intKey ){
54887       nEntry += pPage->nCell;
54888     }
54889
54890     /* pPage is a leaf node. This loop navigates the cursor so that it 
54891     ** points to the first interior cell that it points to the parent of
54892     ** the next page in the tree that has not yet been visited. The
54893     ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
54894     ** of the page, or to the number of cells in the page if the next page
54895     ** to visit is the right-child of its parent.
54896     **
54897     ** If all pages in the tree have been visited, return SQLITE_OK to the
54898     ** caller.
54899     */
54900     if( pPage->leaf ){
54901       do {
54902         if( pCur->iPage==0 ){
54903           /* All pages of the b-tree have been visited. Return successfully. */
54904           *pnEntry = nEntry;
54905           return SQLITE_OK;
54906         }
54907         moveToParent(pCur);
54908       }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
54909
54910       pCur->aiIdx[pCur->iPage]++;
54911       pPage = pCur->apPage[pCur->iPage];
54912     }
54913
54914     /* Descend to the child node of the cell that the cursor currently 
54915     ** points at. This is the right-child if (iIdx==pPage->nCell).
54916     */
54917     iIdx = pCur->aiIdx[pCur->iPage];
54918     if( iIdx==pPage->nCell ){
54919       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
54920     }else{
54921       rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
54922     }
54923   }
54924
54925   /* An error has occurred. Return an error code. */
54926   return rc;
54927 }
54928 #endif
54929
54930 /*
54931 ** Return the pager associated with a BTree.  This routine is used for
54932 ** testing and debugging only.
54933 */
54934 SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
54935   return p->pBt->pPager;
54936 }
54937
54938 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
54939 /*
54940 ** Append a message to the error message string.
54941 */
54942 static void checkAppendMsg(
54943   IntegrityCk *pCheck,
54944   char *zMsg1,
54945   const char *zFormat,
54946   ...
54947 ){
54948   va_list ap;
54949   if( !pCheck->mxErr ) return;
54950   pCheck->mxErr--;
54951   pCheck->nErr++;
54952   va_start(ap, zFormat);
54953   if( pCheck->errMsg.nChar ){
54954     sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
54955   }
54956   if( zMsg1 ){
54957     sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
54958   }
54959   sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
54960   va_end(ap);
54961   if( pCheck->errMsg.mallocFailed ){
54962     pCheck->mallocFailed = 1;
54963   }
54964 }
54965 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
54966
54967 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
54968 /*
54969 ** Add 1 to the reference count for page iPage.  If this is the second
54970 ** reference to the page, add an error message to pCheck->zErrMsg.
54971 ** Return 1 if there are 2 ore more references to the page and 0 if
54972 ** if this is the first reference to the page.
54973 **
54974 ** Also check that the page number is in bounds.
54975 */
54976 static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
54977   if( iPage==0 ) return 1;
54978   if( iPage>pCheck->nPage ){
54979     checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
54980     return 1;
54981   }
54982   if( pCheck->anRef[iPage]==1 ){
54983     checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
54984     return 1;
54985   }
54986   return  (pCheck->anRef[iPage]++)>1;
54987 }
54988
54989 #ifndef SQLITE_OMIT_AUTOVACUUM
54990 /*
54991 ** Check that the entry in the pointer-map for page iChild maps to 
54992 ** page iParent, pointer type ptrType. If not, append an error message
54993 ** to pCheck.
54994 */
54995 static void checkPtrmap(
54996   IntegrityCk *pCheck,   /* Integrity check context */
54997   Pgno iChild,           /* Child page number */
54998   u8 eType,              /* Expected pointer map type */
54999   Pgno iParent,          /* Expected pointer map parent page number */
55000   char *zContext         /* Context description (used for error msg) */
55001 ){
55002   int rc;
55003   u8 ePtrmapType;
55004   Pgno iPtrmapParent;
55005
55006   rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
55007   if( rc!=SQLITE_OK ){
55008     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
55009     checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
55010     return;
55011   }
55012
55013   if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
55014     checkAppendMsg(pCheck, zContext, 
55015       "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)", 
55016       iChild, eType, iParent, ePtrmapType, iPtrmapParent);
55017   }
55018 }
55019 #endif
55020
55021 /*
55022 ** Check the integrity of the freelist or of an overflow page list.
55023 ** Verify that the number of pages on the list is N.
55024 */
55025 static void checkList(
55026   IntegrityCk *pCheck,  /* Integrity checking context */
55027   int isFreeList,       /* True for a freelist.  False for overflow page list */
55028   int iPage,            /* Page number for first page in the list */
55029   int N,                /* Expected number of pages in the list */
55030   char *zContext        /* Context for error messages */
55031 ){
55032   int i;
55033   int expected = N;
55034   int iFirst = iPage;
55035   while( N-- > 0 && pCheck->mxErr ){
55036     DbPage *pOvflPage;
55037     unsigned char *pOvflData;
55038     if( iPage<1 ){
55039       checkAppendMsg(pCheck, zContext,
55040          "%d of %d pages missing from overflow list starting at %d",
55041           N+1, expected, iFirst);
55042       break;
55043     }
55044     if( checkRef(pCheck, iPage, zContext) ) break;
55045     if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
55046       checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
55047       break;
55048     }
55049     pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
55050     if( isFreeList ){
55051       int n = get4byte(&pOvflData[4]);
55052 #ifndef SQLITE_OMIT_AUTOVACUUM
55053       if( pCheck->pBt->autoVacuum ){
55054         checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
55055       }
55056 #endif
55057       if( n>(int)pCheck->pBt->usableSize/4-2 ){
55058         checkAppendMsg(pCheck, zContext,
55059            "freelist leaf count too big on page %d", iPage);
55060         N--;
55061       }else{
55062         for(i=0; i<n; i++){
55063           Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
55064 #ifndef SQLITE_OMIT_AUTOVACUUM
55065           if( pCheck->pBt->autoVacuum ){
55066             checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
55067           }
55068 #endif
55069           checkRef(pCheck, iFreePage, zContext);
55070         }
55071         N -= n;
55072       }
55073     }
55074 #ifndef SQLITE_OMIT_AUTOVACUUM
55075     else{
55076       /* If this database supports auto-vacuum and iPage is not the last
55077       ** page in this overflow list, check that the pointer-map entry for
55078       ** the following page matches iPage.
55079       */
55080       if( pCheck->pBt->autoVacuum && N>0 ){
55081         i = get4byte(pOvflData);
55082         checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
55083       }
55084     }
55085 #endif
55086     iPage = get4byte(pOvflData);
55087     sqlite3PagerUnref(pOvflPage);
55088   }
55089 }
55090 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
55091
55092 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
55093 /*
55094 ** Do various sanity checks on a single page of a tree.  Return
55095 ** the tree depth.  Root pages return 0.  Parents of root pages
55096 ** return 1, and so forth.
55097 ** 
55098 ** These checks are done:
55099 **
55100 **      1.  Make sure that cells and freeblocks do not overlap
55101 **          but combine to completely cover the page.
55102 **  NO  2.  Make sure cell keys are in order.
55103 **  NO  3.  Make sure no key is less than or equal to zLowerBound.
55104 **  NO  4.  Make sure no key is greater than or equal to zUpperBound.
55105 **      5.  Check the integrity of overflow pages.
55106 **      6.  Recursively call checkTreePage on all children.
55107 **      7.  Verify that the depth of all children is the same.
55108 **      8.  Make sure this page is at least 33% full or else it is
55109 **          the root of the tree.
55110 */
55111 static int checkTreePage(
55112   IntegrityCk *pCheck,  /* Context for the sanity check */
55113   int iPage,            /* Page number of the page to check */
55114   char *zParentContext, /* Parent context */
55115   i64 *pnParentMinKey, 
55116   i64 *pnParentMaxKey
55117 ){
55118   MemPage *pPage;
55119   int i, rc, depth, d2, pgno, cnt;
55120   int hdr, cellStart;
55121   int nCell;
55122   u8 *data;
55123   BtShared *pBt;
55124   int usableSize;
55125   char zContext[100];
55126   char *hit = 0;
55127   i64 nMinKey = 0;
55128   i64 nMaxKey = 0;
55129
55130   sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
55131
55132   /* Check that the page exists
55133   */
55134   pBt = pCheck->pBt;
55135   usableSize = pBt->usableSize;
55136   if( iPage==0 ) return 0;
55137   if( checkRef(pCheck, iPage, zParentContext) ) return 0;
55138   if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
55139     checkAppendMsg(pCheck, zContext,
55140        "unable to get the page. error code=%d", rc);
55141     return 0;
55142   }
55143
55144   /* Clear MemPage.isInit to make sure the corruption detection code in
55145   ** btreeInitPage() is executed.  */
55146   pPage->isInit = 0;
55147   if( (rc = btreeInitPage(pPage))!=0 ){
55148     assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
55149     checkAppendMsg(pCheck, zContext, 
55150                    "btreeInitPage() returns error code %d", rc);
55151     releasePage(pPage);
55152     return 0;
55153   }
55154
55155   /* Check out all the cells.
55156   */
55157   depth = 0;
55158   for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
55159     u8 *pCell;
55160     u32 sz;
55161     CellInfo info;
55162
55163     /* Check payload overflow pages
55164     */
55165     sqlite3_snprintf(sizeof(zContext), zContext,
55166              "On tree page %d cell %d: ", iPage, i);
55167     pCell = findCell(pPage,i);
55168     btreeParseCellPtr(pPage, pCell, &info);
55169     sz = info.nData;
55170     if( !pPage->intKey ) sz += (int)info.nKey;
55171     /* For intKey pages, check that the keys are in order.
55172     */
55173     else if( i==0 ) nMinKey = nMaxKey = info.nKey;
55174     else{
55175       if( info.nKey <= nMaxKey ){
55176         checkAppendMsg(pCheck, zContext, 
55177             "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
55178       }
55179       nMaxKey = info.nKey;
55180     }
55181     assert( sz==info.nPayload );
55182     if( (sz>info.nLocal) 
55183      && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
55184     ){
55185       int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
55186       Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
55187 #ifndef SQLITE_OMIT_AUTOVACUUM
55188       if( pBt->autoVacuum ){
55189         checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
55190       }
55191 #endif
55192       checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
55193     }
55194
55195     /* Check sanity of left child page.
55196     */
55197     if( !pPage->leaf ){
55198       pgno = get4byte(pCell);
55199 #ifndef SQLITE_OMIT_AUTOVACUUM
55200       if( pBt->autoVacuum ){
55201         checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
55202       }
55203 #endif
55204       d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
55205       if( i>0 && d2!=depth ){
55206         checkAppendMsg(pCheck, zContext, "Child page depth differs");
55207       }
55208       depth = d2;
55209     }
55210   }
55211
55212   if( !pPage->leaf ){
55213     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
55214     sqlite3_snprintf(sizeof(zContext), zContext, 
55215                      "On page %d at right child: ", iPage);
55216 #ifndef SQLITE_OMIT_AUTOVACUUM
55217     if( pBt->autoVacuum ){
55218       checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
55219     }
55220 #endif
55221     checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
55222   }
55223  
55224   /* For intKey leaf pages, check that the min/max keys are in order
55225   ** with any left/parent/right pages.
55226   */
55227   if( pPage->leaf && pPage->intKey ){
55228     /* if we are a left child page */
55229     if( pnParentMinKey ){
55230       /* if we are the left most child page */
55231       if( !pnParentMaxKey ){
55232         if( nMaxKey > *pnParentMinKey ){
55233           checkAppendMsg(pCheck, zContext, 
55234               "Rowid %lld out of order (max larger than parent min of %lld)",
55235               nMaxKey, *pnParentMinKey);
55236         }
55237       }else{
55238         if( nMinKey <= *pnParentMinKey ){
55239           checkAppendMsg(pCheck, zContext, 
55240               "Rowid %lld out of order (min less than parent min of %lld)",
55241               nMinKey, *pnParentMinKey);
55242         }
55243         if( nMaxKey > *pnParentMaxKey ){
55244           checkAppendMsg(pCheck, zContext, 
55245               "Rowid %lld out of order (max larger than parent max of %lld)",
55246               nMaxKey, *pnParentMaxKey);
55247         }
55248         *pnParentMinKey = nMaxKey;
55249       }
55250     /* else if we're a right child page */
55251     } else if( pnParentMaxKey ){
55252       if( nMinKey <= *pnParentMaxKey ){
55253         checkAppendMsg(pCheck, zContext, 
55254             "Rowid %lld out of order (min less than parent max of %lld)",
55255             nMinKey, *pnParentMaxKey);
55256       }
55257     }
55258   }
55259
55260   /* Check for complete coverage of the page
55261   */
55262   data = pPage->aData;
55263   hdr = pPage->hdrOffset;
55264   hit = sqlite3PageMalloc( pBt->pageSize );
55265   if( hit==0 ){
55266     pCheck->mallocFailed = 1;
55267   }else{
55268     int contentOffset = get2byteNotZero(&data[hdr+5]);
55269     assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
55270     memset(hit+contentOffset, 0, usableSize-contentOffset);
55271     memset(hit, 1, contentOffset);
55272     nCell = get2byte(&data[hdr+3]);
55273     cellStart = hdr + 12 - 4*pPage->leaf;
55274     for(i=0; i<nCell; i++){
55275       int pc = get2byte(&data[cellStart+i*2]);
55276       u32 size = 65536;
55277       int j;
55278       if( pc<=usableSize-4 ){
55279         size = cellSizePtr(pPage, &data[pc]);
55280       }
55281       if( (int)(pc+size-1)>=usableSize ){
55282         checkAppendMsg(pCheck, 0, 
55283             "Corruption detected in cell %d on page %d",i,iPage);
55284       }else{
55285         for(j=pc+size-1; j>=pc; j--) hit[j]++;
55286       }
55287     }
55288     i = get2byte(&data[hdr+1]);
55289     while( i>0 ){
55290       int size, j;
55291       assert( i<=usableSize-4 );     /* Enforced by btreeInitPage() */
55292       size = get2byte(&data[i+2]);
55293       assert( i+size<=usableSize );  /* Enforced by btreeInitPage() */
55294       for(j=i+size-1; j>=i; j--) hit[j]++;
55295       j = get2byte(&data[i]);
55296       assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
55297       assert( j<=usableSize-4 );   /* Enforced by btreeInitPage() */
55298       i = j;
55299     }
55300     for(i=cnt=0; i<usableSize; i++){
55301       if( hit[i]==0 ){
55302         cnt++;
55303       }else if( hit[i]>1 ){
55304         checkAppendMsg(pCheck, 0,
55305           "Multiple uses for byte %d of page %d", i, iPage);
55306         break;
55307       }
55308     }
55309     if( cnt!=data[hdr+7] ){
55310       checkAppendMsg(pCheck, 0, 
55311           "Fragmentation of %d bytes reported as %d on page %d",
55312           cnt, data[hdr+7], iPage);
55313     }
55314   }
55315   sqlite3PageFree(hit);
55316   releasePage(pPage);
55317   return depth+1;
55318 }
55319 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
55320
55321 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
55322 /*
55323 ** This routine does a complete check of the given BTree file.  aRoot[] is
55324 ** an array of pages numbers were each page number is the root page of
55325 ** a table.  nRoot is the number of entries in aRoot.
55326 **
55327 ** A read-only or read-write transaction must be opened before calling
55328 ** this function.
55329 **
55330 ** Write the number of error seen in *pnErr.  Except for some memory
55331 ** allocation errors,  an error message held in memory obtained from
55332 ** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
55333 ** returned.  If a memory allocation error occurs, NULL is returned.
55334 */
55335 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
55336   Btree *p,     /* The btree to be checked */
55337   int *aRoot,   /* An array of root pages numbers for individual trees */
55338   int nRoot,    /* Number of entries in aRoot[] */
55339   int mxErr,    /* Stop reporting errors after this many */
55340   int *pnErr    /* Write number of errors seen to this variable */
55341 ){
55342   Pgno i;
55343   int nRef;
55344   IntegrityCk sCheck;
55345   BtShared *pBt = p->pBt;
55346   char zErr[100];
55347
55348   sqlite3BtreeEnter(p);
55349   assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
55350   nRef = sqlite3PagerRefcount(pBt->pPager);
55351   sCheck.pBt = pBt;
55352   sCheck.pPager = pBt->pPager;
55353   sCheck.nPage = btreePagecount(sCheck.pBt);
55354   sCheck.mxErr = mxErr;
55355   sCheck.nErr = 0;
55356   sCheck.mallocFailed = 0;
55357   *pnErr = 0;
55358   if( sCheck.nPage==0 ){
55359     sqlite3BtreeLeave(p);
55360     return 0;
55361   }
55362   sCheck.anRef = sqlite3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
55363   if( !sCheck.anRef ){
55364     *pnErr = 1;
55365     sqlite3BtreeLeave(p);
55366     return 0;
55367   }
55368   for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
55369   i = PENDING_BYTE_PAGE(pBt);
55370   if( i<=sCheck.nPage ){
55371     sCheck.anRef[i] = 1;
55372   }
55373   sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
55374   sCheck.errMsg.useMalloc = 2;
55375
55376   /* Check the integrity of the freelist
55377   */
55378   checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
55379             get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
55380
55381   /* Check all the tables.
55382   */
55383   for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
55384     if( aRoot[i]==0 ) continue;
55385 #ifndef SQLITE_OMIT_AUTOVACUUM
55386     if( pBt->autoVacuum && aRoot[i]>1 ){
55387       checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
55388     }
55389 #endif
55390     checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
55391   }
55392
55393   /* Make sure every page in the file is referenced
55394   */
55395   for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
55396 #ifdef SQLITE_OMIT_AUTOVACUUM
55397     if( sCheck.anRef[i]==0 ){
55398       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
55399     }
55400 #else
55401     /* If the database supports auto-vacuum, make sure no tables contain
55402     ** references to pointer-map pages.
55403     */
55404     if( sCheck.anRef[i]==0 && 
55405        (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
55406       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
55407     }
55408     if( sCheck.anRef[i]!=0 && 
55409        (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
55410       checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
55411     }
55412 #endif
55413   }
55414
55415   /* Make sure this analysis did not leave any unref() pages.
55416   ** This is an internal consistency check; an integrity check
55417   ** of the integrity check.
55418   */
55419   if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
55420     checkAppendMsg(&sCheck, 0, 
55421       "Outstanding page count goes from %d to %d during this analysis",
55422       nRef, sqlite3PagerRefcount(pBt->pPager)
55423     );
55424   }
55425
55426   /* Clean  up and report errors.
55427   */
55428   sqlite3BtreeLeave(p);
55429   sqlite3_free(sCheck.anRef);
55430   if( sCheck.mallocFailed ){
55431     sqlite3StrAccumReset(&sCheck.errMsg);
55432     *pnErr = sCheck.nErr+1;
55433     return 0;
55434   }
55435   *pnErr = sCheck.nErr;
55436   if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
55437   return sqlite3StrAccumFinish(&sCheck.errMsg);
55438 }
55439 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
55440
55441 /*
55442 ** Return the full pathname of the underlying database file.
55443 **
55444 ** The pager filename is invariant as long as the pager is
55445 ** open so it is safe to access without the BtShared mutex.
55446 */
55447 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
55448   assert( p->pBt->pPager!=0 );
55449   return sqlite3PagerFilename(p->pBt->pPager);
55450 }
55451
55452 /*
55453 ** Return the pathname of the journal file for this database. The return
55454 ** value of this routine is the same regardless of whether the journal file
55455 ** has been created or not.
55456 **
55457 ** The pager journal filename is invariant as long as the pager is
55458 ** open so it is safe to access without the BtShared mutex.
55459 */
55460 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
55461   assert( p->pBt->pPager!=0 );
55462   return sqlite3PagerJournalname(p->pBt->pPager);
55463 }
55464
55465 /*
55466 ** Return non-zero if a transaction is active.
55467 */
55468 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
55469   assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
55470   return (p && (p->inTrans==TRANS_WRITE));
55471 }
55472
55473 #ifndef SQLITE_OMIT_WAL
55474 /*
55475 ** Run a checkpoint on the Btree passed as the first argument.
55476 **
55477 ** Return SQLITE_LOCKED if this or any other connection has an open 
55478 ** transaction on the shared-cache the argument Btree is connected to.
55479 **
55480 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
55481 */
55482 SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
55483   int rc = SQLITE_OK;
55484   if( p ){
55485     BtShared *pBt = p->pBt;
55486     sqlite3BtreeEnter(p);
55487     if( pBt->inTransaction!=TRANS_NONE ){
55488       rc = SQLITE_LOCKED;
55489     }else{
55490       rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
55491     }
55492     sqlite3BtreeLeave(p);
55493   }
55494   return rc;
55495 }
55496 #endif
55497
55498 /*
55499 ** Return non-zero if a read (or write) transaction is active.
55500 */
55501 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
55502   assert( p );
55503   assert( sqlite3_mutex_held(p->db->mutex) );
55504   return p->inTrans!=TRANS_NONE;
55505 }
55506
55507 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
55508   assert( p );
55509   assert( sqlite3_mutex_held(p->db->mutex) );
55510   return p->nBackup!=0;
55511 }
55512
55513 /*
55514 ** This function returns a pointer to a blob of memory associated with
55515 ** a single shared-btree. The memory is used by client code for its own
55516 ** purposes (for example, to store a high-level schema associated with 
55517 ** the shared-btree). The btree layer manages reference counting issues.
55518 **
55519 ** The first time this is called on a shared-btree, nBytes bytes of memory
55520 ** are allocated, zeroed, and returned to the caller. For each subsequent 
55521 ** call the nBytes parameter is ignored and a pointer to the same blob
55522 ** of memory returned. 
55523 **
55524 ** If the nBytes parameter is 0 and the blob of memory has not yet been
55525 ** allocated, a null pointer is returned. If the blob has already been
55526 ** allocated, it is returned as normal.
55527 **
55528 ** Just before the shared-btree is closed, the function passed as the 
55529 ** xFree argument when the memory allocation was made is invoked on the 
55530 ** blob of allocated memory. The xFree function should not call sqlite3_free()
55531 ** on the memory, the btree layer does that.
55532 */
55533 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
55534   BtShared *pBt = p->pBt;
55535   sqlite3BtreeEnter(p);
55536   if( !pBt->pSchema && nBytes ){
55537     pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
55538     pBt->xFreeSchema = xFree;
55539   }
55540   sqlite3BtreeLeave(p);
55541   return pBt->pSchema;
55542 }
55543
55544 /*
55545 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared 
55546 ** btree as the argument handle holds an exclusive lock on the 
55547 ** sqlite_master table. Otherwise SQLITE_OK.
55548 */
55549 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
55550   int rc;
55551   assert( sqlite3_mutex_held(p->db->mutex) );
55552   sqlite3BtreeEnter(p);
55553   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
55554   assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
55555   sqlite3BtreeLeave(p);
55556   return rc;
55557 }
55558
55559
55560 #ifndef SQLITE_OMIT_SHARED_CACHE
55561 /*
55562 ** Obtain a lock on the table whose root page is iTab.  The
55563 ** lock is a write lock if isWritelock is true or a read lock
55564 ** if it is false.
55565 */
55566 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
55567   int rc = SQLITE_OK;
55568   assert( p->inTrans!=TRANS_NONE );
55569   if( p->sharable ){
55570     u8 lockType = READ_LOCK + isWriteLock;
55571     assert( READ_LOCK+1==WRITE_LOCK );
55572     assert( isWriteLock==0 || isWriteLock==1 );
55573
55574     sqlite3BtreeEnter(p);
55575     rc = querySharedCacheTableLock(p, iTab, lockType);
55576     if( rc==SQLITE_OK ){
55577       rc = setSharedCacheTableLock(p, iTab, lockType);
55578     }
55579     sqlite3BtreeLeave(p);
55580   }
55581   return rc;
55582 }
55583 #endif
55584
55585 #ifndef SQLITE_OMIT_INCRBLOB
55586 /*
55587 ** Argument pCsr must be a cursor opened for writing on an 
55588 ** INTKEY table currently pointing at a valid table entry. 
55589 ** This function modifies the data stored as part of that entry.
55590 **
55591 ** Only the data content may only be modified, it is not possible to 
55592 ** change the length of the data stored. If this function is called with
55593 ** parameters that attempt to write past the end of the existing data,
55594 ** no modifications are made and SQLITE_CORRUPT is returned.
55595 */
55596 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
55597   int rc;
55598   assert( cursorHoldsMutex(pCsr) );
55599   assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
55600   assert( pCsr->isIncrblobHandle );
55601
55602   rc = restoreCursorPosition(pCsr);
55603   if( rc!=SQLITE_OK ){
55604     return rc;
55605   }
55606   assert( pCsr->eState!=CURSOR_REQUIRESEEK );
55607   if( pCsr->eState!=CURSOR_VALID ){
55608     return SQLITE_ABORT;
55609   }
55610
55611   /* Check some assumptions: 
55612   **   (a) the cursor is open for writing,
55613   **   (b) there is a read/write transaction open,
55614   **   (c) the connection holds a write-lock on the table (if required),
55615   **   (d) there are no conflicting read-locks, and
55616   **   (e) the cursor points at a valid row of an intKey table.
55617   */
55618   if( !pCsr->wrFlag ){
55619     return SQLITE_READONLY;
55620   }
55621   assert( !pCsr->pBt->readOnly && pCsr->pBt->inTransaction==TRANS_WRITE );
55622   assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
55623   assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
55624   assert( pCsr->apPage[pCsr->iPage]->intKey );
55625
55626   return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
55627 }
55628
55629 /* 
55630 ** Set a flag on this cursor to cache the locations of pages from the 
55631 ** overflow list for the current row. This is used by cursors opened
55632 ** for incremental blob IO only.
55633 **
55634 ** This function sets a flag only. The actual page location cache
55635 ** (stored in BtCursor.aOverflow[]) is allocated and used by function
55636 ** accessPayload() (the worker function for sqlite3BtreeData() and
55637 ** sqlite3BtreePutData()).
55638 */
55639 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
55640   assert( cursorHoldsMutex(pCur) );
55641   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
55642   invalidateOverflowCache(pCur);
55643   pCur->isIncrblobHandle = 1;
55644 }
55645 #endif
55646
55647 /*
55648 ** Set both the "read version" (single byte at byte offset 18) and 
55649 ** "write version" (single byte at byte offset 19) fields in the database
55650 ** header to iVersion.
55651 */
55652 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
55653   BtShared *pBt = pBtree->pBt;
55654   int rc;                         /* Return code */
55655  
55656   assert( pBtree->inTrans==TRANS_NONE );
55657   assert( iVersion==1 || iVersion==2 );
55658
55659   /* If setting the version fields to 1, do not automatically open the
55660   ** WAL connection, even if the version fields are currently set to 2.
55661   */
55662   pBt->doNotUseWAL = (u8)(iVersion==1);
55663
55664   rc = sqlite3BtreeBeginTrans(pBtree, 0);
55665   if( rc==SQLITE_OK ){
55666     u8 *aData = pBt->pPage1->aData;
55667     if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
55668       rc = sqlite3BtreeBeginTrans(pBtree, 2);
55669       if( rc==SQLITE_OK ){
55670         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
55671         if( rc==SQLITE_OK ){
55672           aData[18] = (u8)iVersion;
55673           aData[19] = (u8)iVersion;
55674         }
55675       }
55676     }
55677   }
55678
55679   pBt->doNotUseWAL = 0;
55680   return rc;
55681 }
55682
55683 /************** End of btree.c ***********************************************/
55684 /************** Begin file backup.c ******************************************/
55685 /*
55686 ** 2009 January 28
55687 **
55688 ** The author disclaims copyright to this source code.  In place of
55689 ** a legal notice, here is a blessing:
55690 **
55691 **    May you do good and not evil.
55692 **    May you find forgiveness for yourself and forgive others.
55693 **    May you share freely, never taking more than you give.
55694 **
55695 *************************************************************************
55696 ** This file contains the implementation of the sqlite3_backup_XXX() 
55697 ** API functions and the related features.
55698 */
55699
55700 /* Macro to find the minimum of two numeric values.
55701 */
55702 #ifndef MIN
55703 # define MIN(x,y) ((x)<(y)?(x):(y))
55704 #endif
55705
55706 /*
55707 ** Structure allocated for each backup operation.
55708 */
55709 struct sqlite3_backup {
55710   sqlite3* pDestDb;        /* Destination database handle */
55711   Btree *pDest;            /* Destination b-tree file */
55712   u32 iDestSchema;         /* Original schema cookie in destination */
55713   int bDestLocked;         /* True once a write-transaction is open on pDest */
55714
55715   Pgno iNext;              /* Page number of the next source page to copy */
55716   sqlite3* pSrcDb;         /* Source database handle */
55717   Btree *pSrc;             /* Source b-tree file */
55718
55719   int rc;                  /* Backup process error code */
55720
55721   /* These two variables are set by every call to backup_step(). They are
55722   ** read by calls to backup_remaining() and backup_pagecount().
55723   */
55724   Pgno nRemaining;         /* Number of pages left to copy */
55725   Pgno nPagecount;         /* Total number of pages to copy */
55726
55727   int isAttached;          /* True once backup has been registered with pager */
55728   sqlite3_backup *pNext;   /* Next backup associated with source pager */
55729 };
55730
55731 /*
55732 ** THREAD SAFETY NOTES:
55733 **
55734 **   Once it has been created using backup_init(), a single sqlite3_backup
55735 **   structure may be accessed via two groups of thread-safe entry points:
55736 **
55737 **     * Via the sqlite3_backup_XXX() API function backup_step() and 
55738 **       backup_finish(). Both these functions obtain the source database
55739 **       handle mutex and the mutex associated with the source BtShared 
55740 **       structure, in that order.
55741 **
55742 **     * Via the BackupUpdate() and BackupRestart() functions, which are
55743 **       invoked by the pager layer to report various state changes in
55744 **       the page cache associated with the source database. The mutex
55745 **       associated with the source database BtShared structure will always 
55746 **       be held when either of these functions are invoked.
55747 **
55748 **   The other sqlite3_backup_XXX() API functions, backup_remaining() and
55749 **   backup_pagecount() are not thread-safe functions. If they are called
55750 **   while some other thread is calling backup_step() or backup_finish(),
55751 **   the values returned may be invalid. There is no way for a call to
55752 **   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
55753 **   or backup_pagecount().
55754 **
55755 **   Depending on the SQLite configuration, the database handles and/or
55756 **   the Btree objects may have their own mutexes that require locking.
55757 **   Non-sharable Btrees (in-memory databases for example), do not have
55758 **   associated mutexes.
55759 */
55760
55761 /*
55762 ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
55763 ** in connection handle pDb. If such a database cannot be found, return
55764 ** a NULL pointer and write an error message to pErrorDb.
55765 **
55766 ** If the "temp" database is requested, it may need to be opened by this 
55767 ** function. If an error occurs while doing so, return 0 and write an 
55768 ** error message to pErrorDb.
55769 */
55770 static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
55771   int i = sqlite3FindDbName(pDb, zDb);
55772
55773   if( i==1 ){
55774     Parse *pParse;
55775     int rc = 0;
55776     pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
55777     if( pParse==0 ){
55778       sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
55779       rc = SQLITE_NOMEM;
55780     }else{
55781       pParse->db = pDb;
55782       if( sqlite3OpenTempDatabase(pParse) ){
55783         sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
55784         rc = SQLITE_ERROR;
55785       }
55786       sqlite3DbFree(pErrorDb, pParse->zErrMsg);
55787       sqlite3StackFree(pErrorDb, pParse);
55788     }
55789     if( rc ){
55790       return 0;
55791     }
55792   }
55793
55794   if( i<0 ){
55795     sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
55796     return 0;
55797   }
55798
55799   return pDb->aDb[i].pBt;
55800 }
55801
55802 /*
55803 ** Attempt to set the page size of the destination to match the page size
55804 ** of the source.
55805 */
55806 static int setDestPgsz(sqlite3_backup *p){
55807   int rc;
55808   rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
55809   return rc;
55810 }
55811
55812 /*
55813 ** Create an sqlite3_backup process to copy the contents of zSrcDb from
55814 ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
55815 ** a pointer to the new sqlite3_backup object.
55816 **
55817 ** If an error occurs, NULL is returned and an error code and error message
55818 ** stored in database handle pDestDb.
55819 */
55820 SQLITE_API sqlite3_backup *sqlite3_backup_init(
55821   sqlite3* pDestDb,                     /* Database to write to */
55822   const char *zDestDb,                  /* Name of database within pDestDb */
55823   sqlite3* pSrcDb,                      /* Database connection to read from */
55824   const char *zSrcDb                    /* Name of database within pSrcDb */
55825 ){
55826   sqlite3_backup *p;                    /* Value to return */
55827
55828   /* Lock the source database handle. The destination database
55829   ** handle is not locked in this routine, but it is locked in
55830   ** sqlite3_backup_step(). The user is required to ensure that no
55831   ** other thread accesses the destination handle for the duration
55832   ** of the backup operation.  Any attempt to use the destination
55833   ** database connection while a backup is in progress may cause
55834   ** a malfunction or a deadlock.
55835   */
55836   sqlite3_mutex_enter(pSrcDb->mutex);
55837   sqlite3_mutex_enter(pDestDb->mutex);
55838
55839   if( pSrcDb==pDestDb ){
55840     sqlite3Error(
55841         pDestDb, SQLITE_ERROR, "source and destination must be distinct"
55842     );
55843     p = 0;
55844   }else {
55845     /* Allocate space for a new sqlite3_backup object...
55846     ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
55847     ** call to sqlite3_backup_init() and is destroyed by a call to
55848     ** sqlite3_backup_finish(). */
55849     p = (sqlite3_backup *)sqlite3_malloc(sizeof(sqlite3_backup));
55850     if( !p ){
55851       sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
55852     }
55853   }
55854
55855   /* If the allocation succeeded, populate the new object. */
55856   if( p ){
55857     memset(p, 0, sizeof(sqlite3_backup));
55858     p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
55859     p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
55860     p->pDestDb = pDestDb;
55861     p->pSrcDb = pSrcDb;
55862     p->iNext = 1;
55863     p->isAttached = 0;
55864
55865     if( 0==p->pSrc || 0==p->pDest || setDestPgsz(p)==SQLITE_NOMEM ){
55866       /* One (or both) of the named databases did not exist or an OOM
55867       ** error was hit.  The error has already been written into the
55868       ** pDestDb handle.  All that is left to do here is free the
55869       ** sqlite3_backup structure.
55870       */
55871       sqlite3_free(p);
55872       p = 0;
55873     }
55874   }
55875   if( p ){
55876     p->pSrc->nBackup++;
55877   }
55878
55879   sqlite3_mutex_leave(pDestDb->mutex);
55880   sqlite3_mutex_leave(pSrcDb->mutex);
55881   return p;
55882 }
55883
55884 /*
55885 ** Argument rc is an SQLite error code. Return true if this error is 
55886 ** considered fatal if encountered during a backup operation. All errors
55887 ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
55888 */
55889 static int isFatalError(int rc){
55890   return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
55891 }
55892
55893 /*
55894 ** Parameter zSrcData points to a buffer containing the data for 
55895 ** page iSrcPg from the source database. Copy this data into the 
55896 ** destination database.
55897 */
55898 static int backupOnePage(sqlite3_backup *p, Pgno iSrcPg, const u8 *zSrcData){
55899   Pager * const pDestPager = sqlite3BtreePager(p->pDest);
55900   const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
55901   int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
55902   const int nCopy = MIN(nSrcPgsz, nDestPgsz);
55903   const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
55904 #ifdef SQLITE_HAS_CODEC
55905   int nSrcReserve = sqlite3BtreeGetReserve(p->pSrc);
55906   int nDestReserve = sqlite3BtreeGetReserve(p->pDest);
55907 #endif
55908
55909   int rc = SQLITE_OK;
55910   i64 iOff;
55911
55912   assert( p->bDestLocked );
55913   assert( !isFatalError(p->rc) );
55914   assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
55915   assert( zSrcData );
55916
55917   /* Catch the case where the destination is an in-memory database and the
55918   ** page sizes of the source and destination differ. 
55919   */
55920   if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
55921     rc = SQLITE_READONLY;
55922   }
55923
55924 #ifdef SQLITE_HAS_CODEC
55925   /* Backup is not possible if the page size of the destination is changing
55926   ** and a codec is in use.
55927   */
55928   if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
55929     rc = SQLITE_READONLY;
55930   }
55931
55932   /* Backup is not possible if the number of bytes of reserve space differ
55933   ** between source and destination.  If there is a difference, try to
55934   ** fix the destination to agree with the source.  If that is not possible,
55935   ** then the backup cannot proceed.
55936   */
55937   if( nSrcReserve!=nDestReserve ){
55938     u32 newPgsz = nSrcPgsz;
55939     rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
55940     if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
55941   }
55942 #endif
55943
55944   /* This loop runs once for each destination page spanned by the source 
55945   ** page. For each iteration, variable iOff is set to the byte offset
55946   ** of the destination page.
55947   */
55948   for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
55949     DbPage *pDestPg = 0;
55950     Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
55951     if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
55952     if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
55953      && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
55954     ){
55955       const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
55956       u8 *zDestData = sqlite3PagerGetData(pDestPg);
55957       u8 *zOut = &zDestData[iOff%nDestPgsz];
55958
55959       /* Copy the data from the source page into the destination page.
55960       ** Then clear the Btree layer MemPage.isInit flag. Both this module
55961       ** and the pager code use this trick (clearing the first byte
55962       ** of the page 'extra' space to invalidate the Btree layers
55963       ** cached parse of the page). MemPage.isInit is marked 
55964       ** "MUST BE FIRST" for this purpose.
55965       */
55966       memcpy(zOut, zIn, nCopy);
55967       ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
55968     }
55969     sqlite3PagerUnref(pDestPg);
55970   }
55971
55972   return rc;
55973 }
55974
55975 /*
55976 ** If pFile is currently larger than iSize bytes, then truncate it to
55977 ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
55978 ** this function is a no-op.
55979 **
55980 ** Return SQLITE_OK if everything is successful, or an SQLite error 
55981 ** code if an error occurs.
55982 */
55983 static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
55984   i64 iCurrent;
55985   int rc = sqlite3OsFileSize(pFile, &iCurrent);
55986   if( rc==SQLITE_OK && iCurrent>iSize ){
55987     rc = sqlite3OsTruncate(pFile, iSize);
55988   }
55989   return rc;
55990 }
55991
55992 /*
55993 ** Register this backup object with the associated source pager for
55994 ** callbacks when pages are changed or the cache invalidated.
55995 */
55996 static void attachBackupObject(sqlite3_backup *p){
55997   sqlite3_backup **pp;
55998   assert( sqlite3BtreeHoldsMutex(p->pSrc) );
55999   pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
56000   p->pNext = *pp;
56001   *pp = p;
56002   p->isAttached = 1;
56003 }
56004
56005 /*
56006 ** Copy nPage pages from the source b-tree to the destination.
56007 */
56008 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
56009   int rc;
56010   int destMode;       /* Destination journal mode */
56011   int pgszSrc = 0;    /* Source page size */
56012   int pgszDest = 0;   /* Destination page size */
56013
56014   sqlite3_mutex_enter(p->pSrcDb->mutex);
56015   sqlite3BtreeEnter(p->pSrc);
56016   if( p->pDestDb ){
56017     sqlite3_mutex_enter(p->pDestDb->mutex);
56018   }
56019
56020   rc = p->rc;
56021   if( !isFatalError(rc) ){
56022     Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
56023     Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
56024     int ii;                            /* Iterator variable */
56025     int nSrcPage = -1;                 /* Size of source db in pages */
56026     int bCloseTrans = 0;               /* True if src db requires unlocking */
56027
56028     /* If the source pager is currently in a write-transaction, return
56029     ** SQLITE_BUSY immediately.
56030     */
56031     if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
56032       rc = SQLITE_BUSY;
56033     }else{
56034       rc = SQLITE_OK;
56035     }
56036
56037     /* Lock the destination database, if it is not locked already. */
56038     if( SQLITE_OK==rc && p->bDestLocked==0
56039      && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2)) 
56040     ){
56041       p->bDestLocked = 1;
56042       sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
56043     }
56044
56045     /* If there is no open read-transaction on the source database, open
56046     ** one now. If a transaction is opened here, then it will be closed
56047     ** before this function exits.
56048     */
56049     if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
56050       rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
56051       bCloseTrans = 1;
56052     }
56053
56054     /* Do not allow backup if the destination database is in WAL mode
56055     ** and the page sizes are different between source and destination */
56056     pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
56057     pgszDest = sqlite3BtreeGetPageSize(p->pDest);
56058     destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
56059     if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
56060       rc = SQLITE_READONLY;
56061     }
56062   
56063     /* Now that there is a read-lock on the source database, query the
56064     ** source pager for the number of pages in the database.
56065     */
56066     nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
56067     assert( nSrcPage>=0 );
56068     for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
56069       const Pgno iSrcPg = p->iNext;                 /* Source page number */
56070       if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
56071         DbPage *pSrcPg;                             /* Source page object */
56072         rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
56073         if( rc==SQLITE_OK ){
56074           rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg));
56075           sqlite3PagerUnref(pSrcPg);
56076         }
56077       }
56078       p->iNext++;
56079     }
56080     if( rc==SQLITE_OK ){
56081       p->nPagecount = nSrcPage;
56082       p->nRemaining = nSrcPage+1-p->iNext;
56083       if( p->iNext>(Pgno)nSrcPage ){
56084         rc = SQLITE_DONE;
56085       }else if( !p->isAttached ){
56086         attachBackupObject(p);
56087       }
56088     }
56089   
56090     /* Update the schema version field in the destination database. This
56091     ** is to make sure that the schema-version really does change in
56092     ** the case where the source and destination databases have the
56093     ** same schema version.
56094     */
56095     if( rc==SQLITE_DONE 
56096      && (rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1))==SQLITE_OK
56097     ){
56098       int nDestTruncate;
56099   
56100       if( p->pDestDb ){
56101         sqlite3ResetInternalSchema(p->pDestDb, -1);
56102       }
56103
56104       /* Set nDestTruncate to the final number of pages in the destination
56105       ** database. The complication here is that the destination page
56106       ** size may be different to the source page size. 
56107       **
56108       ** If the source page size is smaller than the destination page size, 
56109       ** round up. In this case the call to sqlite3OsTruncate() below will
56110       ** fix the size of the file. However it is important to call
56111       ** sqlite3PagerTruncateImage() here so that any pages in the 
56112       ** destination file that lie beyond the nDestTruncate page mark are
56113       ** journalled by PagerCommitPhaseOne() before they are destroyed
56114       ** by the file truncation.
56115       */
56116       assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
56117       assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
56118       if( pgszSrc<pgszDest ){
56119         int ratio = pgszDest/pgszSrc;
56120         nDestTruncate = (nSrcPage+ratio-1)/ratio;
56121         if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
56122           nDestTruncate--;
56123         }
56124       }else{
56125         nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
56126       }
56127       sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
56128
56129       if( pgszSrc<pgszDest ){
56130         /* If the source page-size is smaller than the destination page-size,
56131         ** two extra things may need to happen:
56132         **
56133         **   * The destination may need to be truncated, and
56134         **
56135         **   * Data stored on the pages immediately following the 
56136         **     pending-byte page in the source database may need to be
56137         **     copied into the destination database.
56138         */
56139         const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
56140         sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
56141         i64 iOff;
56142         i64 iEnd;
56143
56144         assert( pFile );
56145         assert( (i64)nDestTruncate*(i64)pgszDest >= iSize || (
56146               nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
56147            && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
56148         ));
56149
56150         /* This call ensures that all data required to recreate the original
56151         ** database has been stored in the journal for pDestPager and the
56152         ** journal synced to disk. So at this point we may safely modify
56153         ** the database file in any way, knowing that if a power failure
56154         ** occurs, the original database will be reconstructed from the 
56155         ** journal file.  */
56156         rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
56157
56158         /* Write the extra pages and truncate the database file as required. */
56159         iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
56160         for(
56161           iOff=PENDING_BYTE+pgszSrc; 
56162           rc==SQLITE_OK && iOff<iEnd; 
56163           iOff+=pgszSrc
56164         ){
56165           PgHdr *pSrcPg = 0;
56166           const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
56167           rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
56168           if( rc==SQLITE_OK ){
56169             u8 *zData = sqlite3PagerGetData(pSrcPg);
56170             rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
56171           }
56172           sqlite3PagerUnref(pSrcPg);
56173         }
56174         if( rc==SQLITE_OK ){
56175           rc = backupTruncateFile(pFile, iSize);
56176         }
56177
56178         /* Sync the database file to disk. */
56179         if( rc==SQLITE_OK ){
56180           rc = sqlite3PagerSync(pDestPager);
56181         }
56182       }else{
56183         rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
56184       }
56185   
56186       /* Finish committing the transaction to the destination database. */
56187       if( SQLITE_OK==rc
56188        && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
56189       ){
56190         rc = SQLITE_DONE;
56191       }
56192     }
56193   
56194     /* If bCloseTrans is true, then this function opened a read transaction
56195     ** on the source database. Close the read transaction here. There is
56196     ** no need to check the return values of the btree methods here, as
56197     ** "committing" a read-only transaction cannot fail.
56198     */
56199     if( bCloseTrans ){
56200       TESTONLY( int rc2 );
56201       TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
56202       TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
56203       assert( rc2==SQLITE_OK );
56204     }
56205   
56206     if( rc==SQLITE_IOERR_NOMEM ){
56207       rc = SQLITE_NOMEM;
56208     }
56209     p->rc = rc;
56210   }
56211   if( p->pDestDb ){
56212     sqlite3_mutex_leave(p->pDestDb->mutex);
56213   }
56214   sqlite3BtreeLeave(p->pSrc);
56215   sqlite3_mutex_leave(p->pSrcDb->mutex);
56216   return rc;
56217 }
56218
56219 /*
56220 ** Release all resources associated with an sqlite3_backup* handle.
56221 */
56222 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
56223   sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
56224   sqlite3_mutex *mutex;                /* Mutex to protect source database */
56225   int rc;                              /* Value to return */
56226
56227   /* Enter the mutexes */
56228   if( p==0 ) return SQLITE_OK;
56229   sqlite3_mutex_enter(p->pSrcDb->mutex);
56230   sqlite3BtreeEnter(p->pSrc);
56231   mutex = p->pSrcDb->mutex;
56232   if( p->pDestDb ){
56233     sqlite3_mutex_enter(p->pDestDb->mutex);
56234   }
56235
56236   /* Detach this backup from the source pager. */
56237   if( p->pDestDb ){
56238     p->pSrc->nBackup--;
56239   }
56240   if( p->isAttached ){
56241     pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
56242     while( *pp!=p ){
56243       pp = &(*pp)->pNext;
56244     }
56245     *pp = p->pNext;
56246   }
56247
56248   /* If a transaction is still open on the Btree, roll it back. */
56249   sqlite3BtreeRollback(p->pDest);
56250
56251   /* Set the error code of the destination database handle. */
56252   rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
56253   sqlite3Error(p->pDestDb, rc, 0);
56254
56255   /* Exit the mutexes and free the backup context structure. */
56256   if( p->pDestDb ){
56257     sqlite3_mutex_leave(p->pDestDb->mutex);
56258   }
56259   sqlite3BtreeLeave(p->pSrc);
56260   if( p->pDestDb ){
56261     /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
56262     ** call to sqlite3_backup_init() and is destroyed by a call to
56263     ** sqlite3_backup_finish(). */
56264     sqlite3_free(p);
56265   }
56266   sqlite3_mutex_leave(mutex);
56267   return rc;
56268 }
56269
56270 /*
56271 ** Return the number of pages still to be backed up as of the most recent
56272 ** call to sqlite3_backup_step().
56273 */
56274 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
56275   return p->nRemaining;
56276 }
56277
56278 /*
56279 ** Return the total number of pages in the source database as of the most 
56280 ** recent call to sqlite3_backup_step().
56281 */
56282 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
56283   return p->nPagecount;
56284 }
56285
56286 /*
56287 ** This function is called after the contents of page iPage of the
56288 ** source database have been modified. If page iPage has already been 
56289 ** copied into the destination database, then the data written to the
56290 ** destination is now invalidated. The destination copy of iPage needs
56291 ** to be updated with the new data before the backup operation is
56292 ** complete.
56293 **
56294 ** It is assumed that the mutex associated with the BtShared object
56295 ** corresponding to the source database is held when this function is
56296 ** called.
56297 */
56298 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
56299   sqlite3_backup *p;                   /* Iterator variable */
56300   for(p=pBackup; p; p=p->pNext){
56301     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
56302     if( !isFatalError(p->rc) && iPage<p->iNext ){
56303       /* The backup process p has already copied page iPage. But now it
56304       ** has been modified by a transaction on the source pager. Copy
56305       ** the new data into the backup.
56306       */
56307       int rc;
56308       assert( p->pDestDb );
56309       sqlite3_mutex_enter(p->pDestDb->mutex);
56310       rc = backupOnePage(p, iPage, aData);
56311       sqlite3_mutex_leave(p->pDestDb->mutex);
56312       assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
56313       if( rc!=SQLITE_OK ){
56314         p->rc = rc;
56315       }
56316     }
56317   }
56318 }
56319
56320 /*
56321 ** Restart the backup process. This is called when the pager layer
56322 ** detects that the database has been modified by an external database
56323 ** connection. In this case there is no way of knowing which of the
56324 ** pages that have been copied into the destination database are still 
56325 ** valid and which are not, so the entire process needs to be restarted.
56326 **
56327 ** It is assumed that the mutex associated with the BtShared object
56328 ** corresponding to the source database is held when this function is
56329 ** called.
56330 */
56331 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
56332   sqlite3_backup *p;                   /* Iterator variable */
56333   for(p=pBackup; p; p=p->pNext){
56334     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
56335     p->iNext = 1;
56336   }
56337 }
56338
56339 #ifndef SQLITE_OMIT_VACUUM
56340 /*
56341 ** Copy the complete content of pBtFrom into pBtTo.  A transaction
56342 ** must be active for both files.
56343 **
56344 ** The size of file pTo may be reduced by this operation. If anything 
56345 ** goes wrong, the transaction on pTo is rolled back. If successful, the 
56346 ** transaction is committed before returning.
56347 */
56348 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
56349   int rc;
56350   sqlite3_backup b;
56351   sqlite3BtreeEnter(pTo);
56352   sqlite3BtreeEnter(pFrom);
56353
56354   /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
56355   ** to 0. This is used by the implementations of sqlite3_backup_step()
56356   ** and sqlite3_backup_finish() to detect that they are being called
56357   ** from this function, not directly by the user.
56358   */
56359   memset(&b, 0, sizeof(b));
56360   b.pSrcDb = pFrom->db;
56361   b.pSrc = pFrom;
56362   b.pDest = pTo;
56363   b.iNext = 1;
56364
56365   /* 0x7FFFFFFF is the hard limit for the number of pages in a database
56366   ** file. By passing this as the number of pages to copy to
56367   ** sqlite3_backup_step(), we can guarantee that the copy finishes 
56368   ** within a single call (unless an error occurs). The assert() statement
56369   ** checks this assumption - (p->rc) should be set to either SQLITE_DONE 
56370   ** or an error code.
56371   */
56372   sqlite3_backup_step(&b, 0x7FFFFFFF);
56373   assert( b.rc!=SQLITE_OK );
56374   rc = sqlite3_backup_finish(&b);
56375   if( rc==SQLITE_OK ){
56376     pTo->pBt->pageSizeFixed = 0;
56377   }
56378
56379   sqlite3BtreeLeave(pFrom);
56380   sqlite3BtreeLeave(pTo);
56381   return rc;
56382 }
56383 #endif /* SQLITE_OMIT_VACUUM */
56384
56385 /************** End of backup.c **********************************************/
56386 /************** Begin file vdbemem.c *****************************************/
56387 /*
56388 ** 2004 May 26
56389 **
56390 ** The author disclaims copyright to this source code.  In place of
56391 ** a legal notice, here is a blessing:
56392 **
56393 **    May you do good and not evil.
56394 **    May you find forgiveness for yourself and forgive others.
56395 **    May you share freely, never taking more than you give.
56396 **
56397 *************************************************************************
56398 **
56399 ** This file contains code use to manipulate "Mem" structure.  A "Mem"
56400 ** stores a single value in the VDBE.  Mem is an opaque structure visible
56401 ** only within the VDBE.  Interface routines refer to a Mem using the
56402 ** name sqlite_value
56403 */
56404
56405 /*
56406 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
56407 ** P if required.
56408 */
56409 #define expandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
56410
56411 /*
56412 ** If pMem is an object with a valid string representation, this routine
56413 ** ensures the internal encoding for the string representation is
56414 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
56415 **
56416 ** If pMem is not a string object, or the encoding of the string
56417 ** representation is already stored using the requested encoding, then this
56418 ** routine is a no-op.
56419 **
56420 ** SQLITE_OK is returned if the conversion is successful (or not required).
56421 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
56422 ** between formats.
56423 */
56424 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
56425   int rc;
56426   assert( (pMem->flags&MEM_RowSet)==0 );
56427   assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
56428            || desiredEnc==SQLITE_UTF16BE );
56429   if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
56430     return SQLITE_OK;
56431   }
56432   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56433 #ifdef SQLITE_OMIT_UTF16
56434   return SQLITE_ERROR;
56435 #else
56436
56437   /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
56438   ** then the encoding of the value may not have changed.
56439   */
56440   rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
56441   assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
56442   assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
56443   assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
56444   return rc;
56445 #endif
56446 }
56447
56448 /*
56449 ** Make sure pMem->z points to a writable allocation of at least 
56450 ** n bytes.
56451 **
56452 ** If the memory cell currently contains string or blob data
56453 ** and the third argument passed to this function is true, the 
56454 ** current content of the cell is preserved. Otherwise, it may
56455 ** be discarded.  
56456 **
56457 ** This function sets the MEM_Dyn flag and clears any xDel callback.
56458 ** It also clears MEM_Ephem and MEM_Static. If the preserve flag is 
56459 ** not set, Mem.n is zeroed.
56460 */
56461 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
56462   assert( 1 >=
56463     ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
56464     (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) + 
56465     ((pMem->flags&MEM_Ephem) ? 1 : 0) + 
56466     ((pMem->flags&MEM_Static) ? 1 : 0)
56467   );
56468   assert( (pMem->flags&MEM_RowSet)==0 );
56469
56470   if( n<32 ) n = 32;
56471   if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
56472     if( preserve && pMem->z==pMem->zMalloc ){
56473       pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
56474       preserve = 0;
56475     }else{
56476       sqlite3DbFree(pMem->db, pMem->zMalloc);
56477       pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
56478     }
56479   }
56480
56481   if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
56482     memcpy(pMem->zMalloc, pMem->z, pMem->n);
56483   }
56484   if( pMem->flags&MEM_Dyn && pMem->xDel ){
56485     pMem->xDel((void *)(pMem->z));
56486   }
56487
56488   pMem->z = pMem->zMalloc;
56489   if( pMem->z==0 ){
56490     pMem->flags = MEM_Null;
56491   }else{
56492     pMem->flags &= ~(MEM_Ephem|MEM_Static);
56493   }
56494   pMem->xDel = 0;
56495   return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
56496 }
56497
56498 /*
56499 ** Make the given Mem object MEM_Dyn.  In other words, make it so
56500 ** that any TEXT or BLOB content is stored in memory obtained from
56501 ** malloc().  In this way, we know that the memory is safe to be
56502 ** overwritten or altered.
56503 **
56504 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
56505 */
56506 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
56507   int f;
56508   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56509   assert( (pMem->flags&MEM_RowSet)==0 );
56510   expandBlob(pMem);
56511   f = pMem->flags;
56512   if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
56513     if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
56514       return SQLITE_NOMEM;
56515     }
56516     pMem->z[pMem->n] = 0;
56517     pMem->z[pMem->n+1] = 0;
56518     pMem->flags |= MEM_Term;
56519 #ifdef SQLITE_DEBUG
56520     pMem->pScopyFrom = 0;
56521 #endif
56522   }
56523
56524   return SQLITE_OK;
56525 }
56526
56527 /*
56528 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
56529 ** blob stored in dynamically allocated space.
56530 */
56531 #ifndef SQLITE_OMIT_INCRBLOB
56532 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
56533   if( pMem->flags & MEM_Zero ){
56534     int nByte;
56535     assert( pMem->flags&MEM_Blob );
56536     assert( (pMem->flags&MEM_RowSet)==0 );
56537     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56538
56539     /* Set nByte to the number of bytes required to store the expanded blob. */
56540     nByte = pMem->n + pMem->u.nZero;
56541     if( nByte<=0 ){
56542       nByte = 1;
56543     }
56544     if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
56545       return SQLITE_NOMEM;
56546     }
56547
56548     memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
56549     pMem->n += pMem->u.nZero;
56550     pMem->flags &= ~(MEM_Zero|MEM_Term);
56551   }
56552   return SQLITE_OK;
56553 }
56554 #endif
56555
56556
56557 /*
56558 ** Make sure the given Mem is \u0000 terminated.
56559 */
56560 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
56561   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56562   if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
56563     return SQLITE_OK;   /* Nothing to do */
56564   }
56565   if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
56566     return SQLITE_NOMEM;
56567   }
56568   pMem->z[pMem->n] = 0;
56569   pMem->z[pMem->n+1] = 0;
56570   pMem->flags |= MEM_Term;
56571   return SQLITE_OK;
56572 }
56573
56574 /*
56575 ** Add MEM_Str to the set of representations for the given Mem.  Numbers
56576 ** are converted using sqlite3_snprintf().  Converting a BLOB to a string
56577 ** is a no-op.
56578 **
56579 ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
56580 **
56581 ** A MEM_Null value will never be passed to this function. This function is
56582 ** used for converting values to text for returning to the user (i.e. via
56583 ** sqlite3_value_text()), or for ensuring that values to be used as btree
56584 ** keys are strings. In the former case a NULL pointer is returned the
56585 ** user and the later is an internal programming error.
56586 */
56587 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
56588   int rc = SQLITE_OK;
56589   int fg = pMem->flags;
56590   const int nByte = 32;
56591
56592   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56593   assert( !(fg&MEM_Zero) );
56594   assert( !(fg&(MEM_Str|MEM_Blob)) );
56595   assert( fg&(MEM_Int|MEM_Real) );
56596   assert( (pMem->flags&MEM_RowSet)==0 );
56597   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
56598
56599
56600   if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
56601     return SQLITE_NOMEM;
56602   }
56603
56604   /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
56605   ** string representation of the value. Then, if the required encoding
56606   ** is UTF-16le or UTF-16be do a translation.
56607   ** 
56608   ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
56609   */
56610   if( fg & MEM_Int ){
56611     sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
56612   }else{
56613     assert( fg & MEM_Real );
56614     sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
56615   }
56616   pMem->n = sqlite3Strlen30(pMem->z);
56617   pMem->enc = SQLITE_UTF8;
56618   pMem->flags |= MEM_Str|MEM_Term;
56619   sqlite3VdbeChangeEncoding(pMem, enc);
56620   return rc;
56621 }
56622
56623 /*
56624 ** Memory cell pMem contains the context of an aggregate function.
56625 ** This routine calls the finalize method for that function.  The
56626 ** result of the aggregate is stored back into pMem.
56627 **
56628 ** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
56629 ** otherwise.
56630 */
56631 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
56632   int rc = SQLITE_OK;
56633   if( ALWAYS(pFunc && pFunc->xFinalize) ){
56634     sqlite3_context ctx;
56635     assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
56636     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56637     memset(&ctx, 0, sizeof(ctx));
56638     ctx.s.flags = MEM_Null;
56639     ctx.s.db = pMem->db;
56640     ctx.pMem = pMem;
56641     ctx.pFunc = pFunc;
56642     pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
56643     assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
56644     sqlite3DbFree(pMem->db, pMem->zMalloc);
56645     memcpy(pMem, &ctx.s, sizeof(ctx.s));
56646     rc = ctx.isError;
56647   }
56648   return rc;
56649 }
56650
56651 /*
56652 ** If the memory cell contains a string value that must be freed by
56653 ** invoking an external callback, free it now. Calling this function
56654 ** does not free any Mem.zMalloc buffer.
56655 */
56656 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
56657   assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
56658   testcase( p->flags & MEM_Agg );
56659   testcase( p->flags & MEM_Dyn );
56660   testcase( p->flags & MEM_RowSet );
56661   testcase( p->flags & MEM_Frame );
56662   if( p->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame) ){
56663     if( p->flags&MEM_Agg ){
56664       sqlite3VdbeMemFinalize(p, p->u.pDef);
56665       assert( (p->flags & MEM_Agg)==0 );
56666       sqlite3VdbeMemRelease(p);
56667     }else if( p->flags&MEM_Dyn && p->xDel ){
56668       assert( (p->flags&MEM_RowSet)==0 );
56669       p->xDel((void *)p->z);
56670       p->xDel = 0;
56671     }else if( p->flags&MEM_RowSet ){
56672       sqlite3RowSetClear(p->u.pRowSet);
56673     }else if( p->flags&MEM_Frame ){
56674       sqlite3VdbeMemSetNull(p);
56675     }
56676   }
56677 }
56678
56679 /*
56680 ** Release any memory held by the Mem. This may leave the Mem in an
56681 ** inconsistent state, for example with (Mem.z==0) and
56682 ** (Mem.type==SQLITE_TEXT).
56683 */
56684 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
56685   sqlite3VdbeMemReleaseExternal(p);
56686   sqlite3DbFree(p->db, p->zMalloc);
56687   p->z = 0;
56688   p->zMalloc = 0;
56689   p->xDel = 0;
56690 }
56691
56692 /*
56693 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
56694 ** If the double is too large, return 0x8000000000000000.
56695 **
56696 ** Most systems appear to do this simply by assigning
56697 ** variables and without the extra range tests.  But
56698 ** there are reports that windows throws an expection
56699 ** if the floating point value is out of range. (See ticket #2880.)
56700 ** Because we do not completely understand the problem, we will
56701 ** take the conservative approach and always do range tests
56702 ** before attempting the conversion.
56703 */
56704 static i64 doubleToInt64(double r){
56705 #ifdef SQLITE_OMIT_FLOATING_POINT
56706   /* When floating-point is omitted, double and int64 are the same thing */
56707   return r;
56708 #else
56709   /*
56710   ** Many compilers we encounter do not define constants for the
56711   ** minimum and maximum 64-bit integers, or they define them
56712   ** inconsistently.  And many do not understand the "LL" notation.
56713   ** So we define our own static constants here using nothing
56714   ** larger than a 32-bit integer constant.
56715   */
56716   static const i64 maxInt = LARGEST_INT64;
56717   static const i64 minInt = SMALLEST_INT64;
56718
56719   if( r<(double)minInt ){
56720     return minInt;
56721   }else if( r>(double)maxInt ){
56722     /* minInt is correct here - not maxInt.  It turns out that assigning
56723     ** a very large positive number to an integer results in a very large
56724     ** negative integer.  This makes no sense, but it is what x86 hardware
56725     ** does so for compatibility we will do the same in software. */
56726     return minInt;
56727   }else{
56728     return (i64)r;
56729   }
56730 #endif
56731 }
56732
56733 /*
56734 ** Return some kind of integer value which is the best we can do
56735 ** at representing the value that *pMem describes as an integer.
56736 ** If pMem is an integer, then the value is exact.  If pMem is
56737 ** a floating-point then the value returned is the integer part.
56738 ** If pMem is a string or blob, then we make an attempt to convert
56739 ** it into a integer and return that.  If pMem represents an
56740 ** an SQL-NULL value, return 0.
56741 **
56742 ** If pMem represents a string value, its encoding might be changed.
56743 */
56744 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
56745   int flags;
56746   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56747   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
56748   flags = pMem->flags;
56749   if( flags & MEM_Int ){
56750     return pMem->u.i;
56751   }else if( flags & MEM_Real ){
56752     return doubleToInt64(pMem->r);
56753   }else if( flags & (MEM_Str|MEM_Blob) ){
56754     i64 value = 0;
56755     assert( pMem->z || pMem->n==0 );
56756     testcase( pMem->z==0 );
56757     sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
56758     return value;
56759   }else{
56760     return 0;
56761   }
56762 }
56763
56764 /*
56765 ** Return the best representation of pMem that we can get into a
56766 ** double.  If pMem is already a double or an integer, return its
56767 ** value.  If it is a string or blob, try to convert it to a double.
56768 ** If it is a NULL, return 0.0.
56769 */
56770 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
56771   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56772   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
56773   if( pMem->flags & MEM_Real ){
56774     return pMem->r;
56775   }else if( pMem->flags & MEM_Int ){
56776     return (double)pMem->u.i;
56777   }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
56778     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
56779     double val = (double)0;
56780     sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
56781     return val;
56782   }else{
56783     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
56784     return (double)0;
56785   }
56786 }
56787
56788 /*
56789 ** The MEM structure is already a MEM_Real.  Try to also make it a
56790 ** MEM_Int if we can.
56791 */
56792 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
56793   assert( pMem->flags & MEM_Real );
56794   assert( (pMem->flags & MEM_RowSet)==0 );
56795   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56796   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
56797
56798   pMem->u.i = doubleToInt64(pMem->r);
56799
56800   /* Only mark the value as an integer if
56801   **
56802   **    (1) the round-trip conversion real->int->real is a no-op, and
56803   **    (2) The integer is neither the largest nor the smallest
56804   **        possible integer (ticket #3922)
56805   **
56806   ** The second and third terms in the following conditional enforces
56807   ** the second condition under the assumption that addition overflow causes
56808   ** values to wrap around.  On x86 hardware, the third term is always
56809   ** true and could be omitted.  But we leave it in because other
56810   ** architectures might behave differently.
56811   */
56812   if( pMem->r==(double)pMem->u.i && pMem->u.i>SMALLEST_INT64
56813       && ALWAYS(pMem->u.i<LARGEST_INT64) ){
56814     pMem->flags |= MEM_Int;
56815   }
56816 }
56817
56818 /*
56819 ** Convert pMem to type integer.  Invalidate any prior representations.
56820 */
56821 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
56822   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56823   assert( (pMem->flags & MEM_RowSet)==0 );
56824   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
56825
56826   pMem->u.i = sqlite3VdbeIntValue(pMem);
56827   MemSetTypeFlag(pMem, MEM_Int);
56828   return SQLITE_OK;
56829 }
56830
56831 /*
56832 ** Convert pMem so that it is of type MEM_Real.
56833 ** Invalidate any prior representations.
56834 */
56835 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
56836   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56837   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
56838
56839   pMem->r = sqlite3VdbeRealValue(pMem);
56840   MemSetTypeFlag(pMem, MEM_Real);
56841   return SQLITE_OK;
56842 }
56843
56844 /*
56845 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
56846 ** Invalidate any prior representations.
56847 **
56848 ** Every effort is made to force the conversion, even if the input
56849 ** is a string that does not look completely like a number.  Convert
56850 ** as much of the string as we can and ignore the rest.
56851 */
56852 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
56853   if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
56854     assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
56855     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
56856     if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
56857       MemSetTypeFlag(pMem, MEM_Int);
56858     }else{
56859       pMem->r = sqlite3VdbeRealValue(pMem);
56860       MemSetTypeFlag(pMem, MEM_Real);
56861       sqlite3VdbeIntegerAffinity(pMem);
56862     }
56863   }
56864   assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
56865   pMem->flags &= ~(MEM_Str|MEM_Blob);
56866   return SQLITE_OK;
56867 }
56868
56869 /*
56870 ** Delete any previous value and set the value stored in *pMem to NULL.
56871 */
56872 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
56873   if( pMem->flags & MEM_Frame ){
56874     VdbeFrame *pFrame = pMem->u.pFrame;
56875     pFrame->pParent = pFrame->v->pDelFrame;
56876     pFrame->v->pDelFrame = pFrame;
56877   }
56878   if( pMem->flags & MEM_RowSet ){
56879     sqlite3RowSetClear(pMem->u.pRowSet);
56880   }
56881   MemSetTypeFlag(pMem, MEM_Null);
56882   pMem->type = SQLITE_NULL;
56883 }
56884
56885 /*
56886 ** Delete any previous value and set the value to be a BLOB of length
56887 ** n containing all zeros.
56888 */
56889 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
56890   sqlite3VdbeMemRelease(pMem);
56891   pMem->flags = MEM_Blob|MEM_Zero;
56892   pMem->type = SQLITE_BLOB;
56893   pMem->n = 0;
56894   if( n<0 ) n = 0;
56895   pMem->u.nZero = n;
56896   pMem->enc = SQLITE_UTF8;
56897
56898 #ifdef SQLITE_OMIT_INCRBLOB
56899   sqlite3VdbeMemGrow(pMem, n, 0);
56900   if( pMem->z ){
56901     pMem->n = n;
56902     memset(pMem->z, 0, n);
56903   }
56904 #endif
56905 }
56906
56907 /*
56908 ** Delete any previous value and set the value stored in *pMem to val,
56909 ** manifest type INTEGER.
56910 */
56911 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
56912   sqlite3VdbeMemRelease(pMem);
56913   pMem->u.i = val;
56914   pMem->flags = MEM_Int;
56915   pMem->type = SQLITE_INTEGER;
56916 }
56917
56918 #ifndef SQLITE_OMIT_FLOATING_POINT
56919 /*
56920 ** Delete any previous value and set the value stored in *pMem to val,
56921 ** manifest type REAL.
56922 */
56923 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
56924   if( sqlite3IsNaN(val) ){
56925     sqlite3VdbeMemSetNull(pMem);
56926   }else{
56927     sqlite3VdbeMemRelease(pMem);
56928     pMem->r = val;
56929     pMem->flags = MEM_Real;
56930     pMem->type = SQLITE_FLOAT;
56931   }
56932 }
56933 #endif
56934
56935 /*
56936 ** Delete any previous value and set the value of pMem to be an
56937 ** empty boolean index.
56938 */
56939 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
56940   sqlite3 *db = pMem->db;
56941   assert( db!=0 );
56942   assert( (pMem->flags & MEM_RowSet)==0 );
56943   sqlite3VdbeMemRelease(pMem);
56944   pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
56945   if( db->mallocFailed ){
56946     pMem->flags = MEM_Null;
56947   }else{
56948     assert( pMem->zMalloc );
56949     pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, 
56950                                        sqlite3DbMallocSize(db, pMem->zMalloc));
56951     assert( pMem->u.pRowSet!=0 );
56952     pMem->flags = MEM_RowSet;
56953   }
56954 }
56955
56956 /*
56957 ** Return true if the Mem object contains a TEXT or BLOB that is
56958 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
56959 */
56960 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
56961   assert( p->db!=0 );
56962   if( p->flags & (MEM_Str|MEM_Blob) ){
56963     int n = p->n;
56964     if( p->flags & MEM_Zero ){
56965       n += p->u.nZero;
56966     }
56967     return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
56968   }
56969   return 0; 
56970 }
56971
56972 #ifdef SQLITE_DEBUG
56973 /*
56974 ** This routine prepares a memory cell for modication by breaking
56975 ** its link to a shallow copy and by marking any current shallow
56976 ** copies of this cell as invalid.
56977 **
56978 ** This is used for testing and debugging only - to make sure shallow
56979 ** copies are not misused.
56980 */
56981 SQLITE_PRIVATE void sqlite3VdbeMemPrepareToChange(Vdbe *pVdbe, Mem *pMem){
56982   int i;
56983   Mem *pX;
56984   for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
56985     if( pX->pScopyFrom==pMem ){
56986       pX->flags |= MEM_Invalid;
56987       pX->pScopyFrom = 0;
56988     }
56989   }
56990   pMem->pScopyFrom = 0;
56991 }
56992 #endif /* SQLITE_DEBUG */
56993
56994 /*
56995 ** Size of struct Mem not including the Mem.zMalloc member.
56996 */
56997 #define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
56998
56999 /*
57000 ** Make an shallow copy of pFrom into pTo.  Prior contents of
57001 ** pTo are freed.  The pFrom->z field is not duplicated.  If
57002 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
57003 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
57004 */
57005 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
57006   assert( (pFrom->flags & MEM_RowSet)==0 );
57007   sqlite3VdbeMemReleaseExternal(pTo);
57008   memcpy(pTo, pFrom, MEMCELLSIZE);
57009   pTo->xDel = 0;
57010   if( (pFrom->flags&MEM_Static)==0 ){
57011     pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
57012     assert( srcType==MEM_Ephem || srcType==MEM_Static );
57013     pTo->flags |= srcType;
57014   }
57015 }
57016
57017 /*
57018 ** Make a full copy of pFrom into pTo.  Prior contents of pTo are
57019 ** freed before the copy is made.
57020 */
57021 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
57022   int rc = SQLITE_OK;
57023
57024   assert( (pFrom->flags & MEM_RowSet)==0 );
57025   sqlite3VdbeMemReleaseExternal(pTo);
57026   memcpy(pTo, pFrom, MEMCELLSIZE);
57027   pTo->flags &= ~MEM_Dyn;
57028
57029   if( pTo->flags&(MEM_Str|MEM_Blob) ){
57030     if( 0==(pFrom->flags&MEM_Static) ){
57031       pTo->flags |= MEM_Ephem;
57032       rc = sqlite3VdbeMemMakeWriteable(pTo);
57033     }
57034   }
57035
57036   return rc;
57037 }
57038
57039 /*
57040 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
57041 ** freed. If pFrom contains ephemeral data, a copy is made.
57042 **
57043 ** pFrom contains an SQL NULL when this routine returns.
57044 */
57045 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
57046   assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
57047   assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
57048   assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
57049
57050   sqlite3VdbeMemRelease(pTo);
57051   memcpy(pTo, pFrom, sizeof(Mem));
57052   pFrom->flags = MEM_Null;
57053   pFrom->xDel = 0;
57054   pFrom->zMalloc = 0;
57055 }
57056
57057 /*
57058 ** Change the value of a Mem to be a string or a BLOB.
57059 **
57060 ** The memory management strategy depends on the value of the xDel
57061 ** parameter. If the value passed is SQLITE_TRANSIENT, then the 
57062 ** string is copied into a (possibly existing) buffer managed by the 
57063 ** Mem structure. Otherwise, any existing buffer is freed and the
57064 ** pointer copied.
57065 **
57066 ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
57067 ** size limit) then no memory allocation occurs.  If the string can be
57068 ** stored without allocating memory, then it is.  If a memory allocation
57069 ** is required to store the string, then value of pMem is unchanged.  In
57070 ** either case, SQLITE_TOOBIG is returned.
57071 */
57072 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
57073   Mem *pMem,          /* Memory cell to set to string value */
57074   const char *z,      /* String pointer */
57075   int n,              /* Bytes in string, or negative */
57076   u8 enc,             /* Encoding of z.  0 for BLOBs */
57077   void (*xDel)(void*) /* Destructor function */
57078 ){
57079   int nByte = n;      /* New value for pMem->n */
57080   int iLimit;         /* Maximum allowed string or blob size */
57081   u16 flags = 0;      /* New value for pMem->flags */
57082
57083   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57084   assert( (pMem->flags & MEM_RowSet)==0 );
57085
57086   /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
57087   if( !z ){
57088     sqlite3VdbeMemSetNull(pMem);
57089     return SQLITE_OK;
57090   }
57091
57092   if( pMem->db ){
57093     iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
57094   }else{
57095     iLimit = SQLITE_MAX_LENGTH;
57096   }
57097   flags = (enc==0?MEM_Blob:MEM_Str);
57098   if( nByte<0 ){
57099     assert( enc!=0 );
57100     if( enc==SQLITE_UTF8 ){
57101       for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
57102     }else{
57103       for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
57104     }
57105     flags |= MEM_Term;
57106   }
57107
57108   /* The following block sets the new values of Mem.z and Mem.xDel. It
57109   ** also sets a flag in local variable "flags" to indicate the memory
57110   ** management (one of MEM_Dyn or MEM_Static).
57111   */
57112   if( xDel==SQLITE_TRANSIENT ){
57113     int nAlloc = nByte;
57114     if( flags&MEM_Term ){
57115       nAlloc += (enc==SQLITE_UTF8?1:2);
57116     }
57117     if( nByte>iLimit ){
57118       return SQLITE_TOOBIG;
57119     }
57120     if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
57121       return SQLITE_NOMEM;
57122     }
57123     memcpy(pMem->z, z, nAlloc);
57124   }else if( xDel==SQLITE_DYNAMIC ){
57125     sqlite3VdbeMemRelease(pMem);
57126     pMem->zMalloc = pMem->z = (char *)z;
57127     pMem->xDel = 0;
57128   }else{
57129     sqlite3VdbeMemRelease(pMem);
57130     pMem->z = (char *)z;
57131     pMem->xDel = xDel;
57132     flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
57133   }
57134
57135   pMem->n = nByte;
57136   pMem->flags = flags;
57137   pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
57138   pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
57139
57140 #ifndef SQLITE_OMIT_UTF16
57141   if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
57142     return SQLITE_NOMEM;
57143   }
57144 #endif
57145
57146   if( nByte>iLimit ){
57147     return SQLITE_TOOBIG;
57148   }
57149
57150   return SQLITE_OK;
57151 }
57152
57153 /*
57154 ** Compare the values contained by the two memory cells, returning
57155 ** negative, zero or positive if pMem1 is less than, equal to, or greater
57156 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
57157 ** and reals) sorted numerically, followed by text ordered by the collating
57158 ** sequence pColl and finally blob's ordered by memcmp().
57159 **
57160 ** Two NULL values are considered equal by this function.
57161 */
57162 SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
57163   int rc;
57164   int f1, f2;
57165   int combined_flags;
57166
57167   f1 = pMem1->flags;
57168   f2 = pMem2->flags;
57169   combined_flags = f1|f2;
57170   assert( (combined_flags & MEM_RowSet)==0 );
57171  
57172   /* If one value is NULL, it is less than the other. If both values
57173   ** are NULL, return 0.
57174   */
57175   if( combined_flags&MEM_Null ){
57176     return (f2&MEM_Null) - (f1&MEM_Null);
57177   }
57178
57179   /* If one value is a number and the other is not, the number is less.
57180   ** If both are numbers, compare as reals if one is a real, or as integers
57181   ** if both values are integers.
57182   */
57183   if( combined_flags&(MEM_Int|MEM_Real) ){
57184     if( !(f1&(MEM_Int|MEM_Real)) ){
57185       return 1;
57186     }
57187     if( !(f2&(MEM_Int|MEM_Real)) ){
57188       return -1;
57189     }
57190     if( (f1 & f2 & MEM_Int)==0 ){
57191       double r1, r2;
57192       if( (f1&MEM_Real)==0 ){
57193         r1 = (double)pMem1->u.i;
57194       }else{
57195         r1 = pMem1->r;
57196       }
57197       if( (f2&MEM_Real)==0 ){
57198         r2 = (double)pMem2->u.i;
57199       }else{
57200         r2 = pMem2->r;
57201       }
57202       if( r1<r2 ) return -1;
57203       if( r1>r2 ) return 1;
57204       return 0;
57205     }else{
57206       assert( f1&MEM_Int );
57207       assert( f2&MEM_Int );
57208       if( pMem1->u.i < pMem2->u.i ) return -1;
57209       if( pMem1->u.i > pMem2->u.i ) return 1;
57210       return 0;
57211     }
57212   }
57213
57214   /* If one value is a string and the other is a blob, the string is less.
57215   ** If both are strings, compare using the collating functions.
57216   */
57217   if( combined_flags&MEM_Str ){
57218     if( (f1 & MEM_Str)==0 ){
57219       return 1;
57220     }
57221     if( (f2 & MEM_Str)==0 ){
57222       return -1;
57223     }
57224
57225     assert( pMem1->enc==pMem2->enc );
57226     assert( pMem1->enc==SQLITE_UTF8 || 
57227             pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
57228
57229     /* The collation sequence must be defined at this point, even if
57230     ** the user deletes the collation sequence after the vdbe program is
57231     ** compiled (this was not always the case).
57232     */
57233     assert( !pColl || pColl->xCmp );
57234
57235     if( pColl ){
57236       if( pMem1->enc==pColl->enc ){
57237         /* The strings are already in the correct encoding.  Call the
57238         ** comparison function directly */
57239         return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
57240       }else{
57241         const void *v1, *v2;
57242         int n1, n2;
57243         Mem c1;
57244         Mem c2;
57245         memset(&c1, 0, sizeof(c1));
57246         memset(&c2, 0, sizeof(c2));
57247         sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
57248         sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
57249         v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
57250         n1 = v1==0 ? 0 : c1.n;
57251         v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
57252         n2 = v2==0 ? 0 : c2.n;
57253         rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
57254         sqlite3VdbeMemRelease(&c1);
57255         sqlite3VdbeMemRelease(&c2);
57256         return rc;
57257       }
57258     }
57259     /* If a NULL pointer was passed as the collate function, fall through
57260     ** to the blob case and use memcmp().  */
57261   }
57262  
57263   /* Both values must be blobs.  Compare using memcmp().  */
57264   rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
57265   if( rc==0 ){
57266     rc = pMem1->n - pMem2->n;
57267   }
57268   return rc;
57269 }
57270
57271 /*
57272 ** Move data out of a btree key or data field and into a Mem structure.
57273 ** The data or key is taken from the entry that pCur is currently pointing
57274 ** to.  offset and amt determine what portion of the data or key to retrieve.
57275 ** key is true to get the key or false to get data.  The result is written
57276 ** into the pMem element.
57277 **
57278 ** The pMem structure is assumed to be uninitialized.  Any prior content
57279 ** is overwritten without being freed.
57280 **
57281 ** If this routine fails for any reason (malloc returns NULL or unable
57282 ** to read from the disk) then the pMem is left in an inconsistent state.
57283 */
57284 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
57285   BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
57286   int offset,       /* Offset from the start of data to return bytes from. */
57287   int amt,          /* Number of bytes to return. */
57288   int key,          /* If true, retrieve from the btree key, not data. */
57289   Mem *pMem         /* OUT: Return data in this Mem structure. */
57290 ){
57291   char *zData;        /* Data from the btree layer */
57292   int available = 0;  /* Number of bytes available on the local btree page */
57293   int rc = SQLITE_OK; /* Return code */
57294
57295   assert( sqlite3BtreeCursorIsValid(pCur) );
57296
57297   /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert() 
57298   ** that both the BtShared and database handle mutexes are held. */
57299   assert( (pMem->flags & MEM_RowSet)==0 );
57300   if( key ){
57301     zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
57302   }else{
57303     zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
57304   }
57305   assert( zData!=0 );
57306
57307   if( offset+amt<=available && (pMem->flags&MEM_Dyn)==0 ){
57308     sqlite3VdbeMemRelease(pMem);
57309     pMem->z = &zData[offset];
57310     pMem->flags = MEM_Blob|MEM_Ephem;
57311   }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
57312     pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
57313     pMem->enc = 0;
57314     pMem->type = SQLITE_BLOB;
57315     if( key ){
57316       rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
57317     }else{
57318       rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
57319     }
57320     pMem->z[amt] = 0;
57321     pMem->z[amt+1] = 0;
57322     if( rc!=SQLITE_OK ){
57323       sqlite3VdbeMemRelease(pMem);
57324     }
57325   }
57326   pMem->n = amt;
57327
57328   return rc;
57329 }
57330
57331 /* This function is only available internally, it is not part of the
57332 ** external API. It works in a similar way to sqlite3_value_text(),
57333 ** except the data returned is in the encoding specified by the second
57334 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
57335 ** SQLITE_UTF8.
57336 **
57337 ** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
57338 ** If that is the case, then the result must be aligned on an even byte
57339 ** boundary.
57340 */
57341 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
57342   if( !pVal ) return 0;
57343
57344   assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
57345   assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
57346   assert( (pVal->flags & MEM_RowSet)==0 );
57347
57348   if( pVal->flags&MEM_Null ){
57349     return 0;
57350   }
57351   assert( (MEM_Blob>>3) == MEM_Str );
57352   pVal->flags |= (pVal->flags & MEM_Blob)>>3;
57353   expandBlob(pVal);
57354   if( pVal->flags&MEM_Str ){
57355     sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
57356     if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
57357       assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
57358       if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
57359         return 0;
57360       }
57361     }
57362     sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-59893-45467 */
57363   }else{
57364     assert( (pVal->flags&MEM_Blob)==0 );
57365     sqlite3VdbeMemStringify(pVal, enc);
57366     assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
57367   }
57368   assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
57369               || pVal->db->mallocFailed );
57370   if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
57371     return pVal->z;
57372   }else{
57373     return 0;
57374   }
57375 }
57376
57377 /*
57378 ** Create a new sqlite3_value object.
57379 */
57380 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
57381   Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
57382   if( p ){
57383     p->flags = MEM_Null;
57384     p->type = SQLITE_NULL;
57385     p->db = db;
57386   }
57387   return p;
57388 }
57389
57390 /*
57391 ** Create a new sqlite3_value object, containing the value of pExpr.
57392 **
57393 ** This only works for very simple expressions that consist of one constant
57394 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
57395 ** be converted directly into a value, then the value is allocated and
57396 ** a pointer written to *ppVal. The caller is responsible for deallocating
57397 ** the value by passing it to sqlite3ValueFree() later on. If the expression
57398 ** cannot be converted to a value, then *ppVal is set to NULL.
57399 */
57400 SQLITE_PRIVATE int sqlite3ValueFromExpr(
57401   sqlite3 *db,              /* The database connection */
57402   Expr *pExpr,              /* The expression to evaluate */
57403   u8 enc,                   /* Encoding to use */
57404   u8 affinity,              /* Affinity to use */
57405   sqlite3_value **ppVal     /* Write the new value here */
57406 ){
57407   int op;
57408   char *zVal = 0;
57409   sqlite3_value *pVal = 0;
57410   int negInt = 1;
57411   const char *zNeg = "";
57412
57413   if( !pExpr ){
57414     *ppVal = 0;
57415     return SQLITE_OK;
57416   }
57417   op = pExpr->op;
57418
57419   /* op can only be TK_REGISTER if we have compiled with SQLITE_ENABLE_STAT2.
57420   ** The ifdef here is to enable us to achieve 100% branch test coverage even
57421   ** when SQLITE_ENABLE_STAT2 is omitted.
57422   */
57423 #ifdef SQLITE_ENABLE_STAT2
57424   if( op==TK_REGISTER ) op = pExpr->op2;
57425 #else
57426   if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
57427 #endif
57428
57429   /* Handle negative integers in a single step.  This is needed in the
57430   ** case when the value is -9223372036854775808.
57431   */
57432   if( op==TK_UMINUS
57433    && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
57434     pExpr = pExpr->pLeft;
57435     op = pExpr->op;
57436     negInt = -1;
57437     zNeg = "-";
57438   }
57439
57440   if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
57441     pVal = sqlite3ValueNew(db);
57442     if( pVal==0 ) goto no_mem;
57443     if( ExprHasProperty(pExpr, EP_IntValue) ){
57444       sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
57445     }else{
57446       zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
57447       if( zVal==0 ) goto no_mem;
57448       sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
57449       if( op==TK_FLOAT ) pVal->type = SQLITE_FLOAT;
57450     }
57451     if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
57452       sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
57453     }else{
57454       sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
57455     }
57456     if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
57457     if( enc!=SQLITE_UTF8 ){
57458       sqlite3VdbeChangeEncoding(pVal, enc);
57459     }
57460   }else if( op==TK_UMINUS ) {
57461     /* This branch happens for multiple negative signs.  Ex: -(-5) */
57462     if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
57463       sqlite3VdbeMemNumerify(pVal);
57464       if( pVal->u.i==SMALLEST_INT64 ){
57465         pVal->flags &= MEM_Int;
57466         pVal->flags |= MEM_Real;
57467         pVal->r = (double)LARGEST_INT64;
57468       }else{
57469         pVal->u.i = -pVal->u.i;
57470       }
57471       pVal->r = -pVal->r;
57472       sqlite3ValueApplyAffinity(pVal, affinity, enc);
57473     }
57474   }else if( op==TK_NULL ){
57475     pVal = sqlite3ValueNew(db);
57476     if( pVal==0 ) goto no_mem;
57477   }
57478 #ifndef SQLITE_OMIT_BLOB_LITERAL
57479   else if( op==TK_BLOB ){
57480     int nVal;
57481     assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
57482     assert( pExpr->u.zToken[1]=='\'' );
57483     pVal = sqlite3ValueNew(db);
57484     if( !pVal ) goto no_mem;
57485     zVal = &pExpr->u.zToken[2];
57486     nVal = sqlite3Strlen30(zVal)-1;
57487     assert( zVal[nVal]=='\'' );
57488     sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
57489                          0, SQLITE_DYNAMIC);
57490   }
57491 #endif
57492
57493   if( pVal ){
57494     sqlite3VdbeMemStoreType(pVal);
57495   }
57496   *ppVal = pVal;
57497   return SQLITE_OK;
57498
57499 no_mem:
57500   db->mallocFailed = 1;
57501   sqlite3DbFree(db, zVal);
57502   sqlite3ValueFree(pVal);
57503   *ppVal = 0;
57504   return SQLITE_NOMEM;
57505 }
57506
57507 /*
57508 ** Change the string value of an sqlite3_value object
57509 */
57510 SQLITE_PRIVATE void sqlite3ValueSetStr(
57511   sqlite3_value *v,     /* Value to be set */
57512   int n,                /* Length of string z */
57513   const void *z,        /* Text of the new string */
57514   u8 enc,               /* Encoding to use */
57515   void (*xDel)(void*)   /* Destructor for the string */
57516 ){
57517   if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
57518 }
57519
57520 /*
57521 ** Free an sqlite3_value object
57522 */
57523 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
57524   if( !v ) return;
57525   sqlite3VdbeMemRelease((Mem *)v);
57526   sqlite3DbFree(((Mem*)v)->db, v);
57527 }
57528
57529 /*
57530 ** Return the number of bytes in the sqlite3_value object assuming
57531 ** that it uses the encoding "enc"
57532 */
57533 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
57534   Mem *p = (Mem*)pVal;
57535   if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
57536     if( p->flags & MEM_Zero ){
57537       return p->n + p->u.nZero;
57538     }else{
57539       return p->n;
57540     }
57541   }
57542   return 0;
57543 }
57544
57545 /************** End of vdbemem.c *********************************************/
57546 /************** Begin file vdbeaux.c *****************************************/
57547 /*
57548 ** 2003 September 6
57549 **
57550 ** The author disclaims copyright to this source code.  In place of
57551 ** a legal notice, here is a blessing:
57552 **
57553 **    May you do good and not evil.
57554 **    May you find forgiveness for yourself and forgive others.
57555 **    May you share freely, never taking more than you give.
57556 **
57557 *************************************************************************
57558 ** This file contains code used for creating, destroying, and populating
57559 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
57560 ** to version 2.8.7, all this code was combined into the vdbe.c source file.
57561 ** But that file was getting too big so this subroutines were split out.
57562 */
57563
57564
57565
57566 /*
57567 ** When debugging the code generator in a symbolic debugger, one can
57568 ** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed
57569 ** as they are added to the instruction stream.
57570 */
57571 #ifdef SQLITE_DEBUG
57572 SQLITE_PRIVATE int sqlite3VdbeAddopTrace = 0;
57573 #endif
57574
57575
57576 /*
57577 ** Create a new virtual database engine.
57578 */
57579 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
57580   Vdbe *p;
57581   p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
57582   if( p==0 ) return 0;
57583   p->db = db;
57584   if( db->pVdbe ){
57585     db->pVdbe->pPrev = p;
57586   }
57587   p->pNext = db->pVdbe;
57588   p->pPrev = 0;
57589   db->pVdbe = p;
57590   p->magic = VDBE_MAGIC_INIT;
57591   return p;
57592 }
57593
57594 /*
57595 ** Remember the SQL string for a prepared statement.
57596 */
57597 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
57598   assert( isPrepareV2==1 || isPrepareV2==0 );
57599   if( p==0 ) return;
57600 #ifdef SQLITE_OMIT_TRACE
57601   if( !isPrepareV2 ) return;
57602 #endif
57603   assert( p->zSql==0 );
57604   p->zSql = sqlite3DbStrNDup(p->db, z, n);
57605   p->isPrepareV2 = (u8)isPrepareV2;
57606 }
57607
57608 /*
57609 ** Return the SQL associated with a prepared statement
57610 */
57611 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
57612   Vdbe *p = (Vdbe *)pStmt;
57613   return (p && p->isPrepareV2) ? p->zSql : 0;
57614 }
57615
57616 /*
57617 ** Swap all content between two VDBE structures.
57618 */
57619 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
57620   Vdbe tmp, *pTmp;
57621   char *zTmp;
57622   tmp = *pA;
57623   *pA = *pB;
57624   *pB = tmp;
57625   pTmp = pA->pNext;
57626   pA->pNext = pB->pNext;
57627   pB->pNext = pTmp;
57628   pTmp = pA->pPrev;
57629   pA->pPrev = pB->pPrev;
57630   pB->pPrev = pTmp;
57631   zTmp = pA->zSql;
57632   pA->zSql = pB->zSql;
57633   pB->zSql = zTmp;
57634   pB->isPrepareV2 = pA->isPrepareV2;
57635 }
57636
57637 #ifdef SQLITE_DEBUG
57638 /*
57639 ** Turn tracing on or off
57640 */
57641 SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
57642   p->trace = trace;
57643 }
57644 #endif
57645
57646 /*
57647 ** Resize the Vdbe.aOp array so that it is at least one op larger than 
57648 ** it was.
57649 **
57650 ** If an out-of-memory error occurs while resizing the array, return
57651 ** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain 
57652 ** unchanged (this is so that any opcodes already allocated can be 
57653 ** correctly deallocated along with the rest of the Vdbe).
57654 */
57655 static int growOpArray(Vdbe *p){
57656   VdbeOp *pNew;
57657   int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
57658   pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
57659   if( pNew ){
57660     p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
57661     p->aOp = pNew;
57662   }
57663   return (pNew ? SQLITE_OK : SQLITE_NOMEM);
57664 }
57665
57666 /*
57667 ** Add a new instruction to the list of instructions current in the
57668 ** VDBE.  Return the address of the new instruction.
57669 **
57670 ** Parameters:
57671 **
57672 **    p               Pointer to the VDBE
57673 **
57674 **    op              The opcode for this instruction
57675 **
57676 **    p1, p2, p3      Operands
57677 **
57678 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
57679 ** the sqlite3VdbeChangeP4() function to change the value of the P4
57680 ** operand.
57681 */
57682 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
57683   int i;
57684   VdbeOp *pOp;
57685
57686   i = p->nOp;
57687   assert( p->magic==VDBE_MAGIC_INIT );
57688   assert( op>0 && op<0xff );
57689   if( p->nOpAlloc<=i ){
57690     if( growOpArray(p) ){
57691       return 1;
57692     }
57693   }
57694   p->nOp++;
57695   pOp = &p->aOp[i];
57696   pOp->opcode = (u8)op;
57697   pOp->p5 = 0;
57698   pOp->p1 = p1;
57699   pOp->p2 = p2;
57700   pOp->p3 = p3;
57701   pOp->p4.p = 0;
57702   pOp->p4type = P4_NOTUSED;
57703 #ifdef SQLITE_DEBUG
57704   pOp->zComment = 0;
57705   if( sqlite3VdbeAddopTrace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
57706 #endif
57707 #ifdef VDBE_PROFILE
57708   pOp->cycles = 0;
57709   pOp->cnt = 0;
57710 #endif
57711   return i;
57712 }
57713 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
57714   return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
57715 }
57716 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
57717   return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
57718 }
57719 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
57720   return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
57721 }
57722
57723
57724 /*
57725 ** Add an opcode that includes the p4 value as a pointer.
57726 */
57727 SQLITE_PRIVATE int sqlite3VdbeAddOp4(
57728   Vdbe *p,            /* Add the opcode to this VM */
57729   int op,             /* The new opcode */
57730   int p1,             /* The P1 operand */
57731   int p2,             /* The P2 operand */
57732   int p3,             /* The P3 operand */
57733   const char *zP4,    /* The P4 operand */
57734   int p4type          /* P4 operand type */
57735 ){
57736   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
57737   sqlite3VdbeChangeP4(p, addr, zP4, p4type);
57738   return addr;
57739 }
57740
57741 /*
57742 ** Add an OP_ParseSchema opcode.  This routine is broken out from
57743 ** sqlite3VdbeAddOp4() since it needs to also local all btrees.
57744 **
57745 ** The zWhere string must have been obtained from sqlite3_malloc().
57746 ** This routine will take ownership of the allocated memory.
57747 */
57748 SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
57749   int j;
57750   int addr = sqlite3VdbeAddOp3(p, OP_ParseSchema, iDb, 0, 0);
57751   sqlite3VdbeChangeP4(p, addr, zWhere, P4_DYNAMIC);
57752   for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
57753 }
57754
57755 /*
57756 ** Add an opcode that includes the p4 value as an integer.
57757 */
57758 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
57759   Vdbe *p,            /* Add the opcode to this VM */
57760   int op,             /* The new opcode */
57761   int p1,             /* The P1 operand */
57762   int p2,             /* The P2 operand */
57763   int p3,             /* The P3 operand */
57764   int p4              /* The P4 operand as an integer */
57765 ){
57766   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
57767   sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
57768   return addr;
57769 }
57770
57771 /*
57772 ** Create a new symbolic label for an instruction that has yet to be
57773 ** coded.  The symbolic label is really just a negative number.  The
57774 ** label can be used as the P2 value of an operation.  Later, when
57775 ** the label is resolved to a specific address, the VDBE will scan
57776 ** through its operation list and change all values of P2 which match
57777 ** the label into the resolved address.
57778 **
57779 ** The VDBE knows that a P2 value is a label because labels are
57780 ** always negative and P2 values are suppose to be non-negative.
57781 ** Hence, a negative P2 value is a label that has yet to be resolved.
57782 **
57783 ** Zero is returned if a malloc() fails.
57784 */
57785 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
57786   int i;
57787   i = p->nLabel++;
57788   assert( p->magic==VDBE_MAGIC_INIT );
57789   if( i>=p->nLabelAlloc ){
57790     int n = p->nLabelAlloc*2 + 5;
57791     p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
57792                                        n*sizeof(p->aLabel[0]));
57793     p->nLabelAlloc = sqlite3DbMallocSize(p->db, p->aLabel)/sizeof(p->aLabel[0]);
57794   }
57795   if( p->aLabel ){
57796     p->aLabel[i] = -1;
57797   }
57798   return -1-i;
57799 }
57800
57801 /*
57802 ** Resolve label "x" to be the address of the next instruction to
57803 ** be inserted.  The parameter "x" must have been obtained from
57804 ** a prior call to sqlite3VdbeMakeLabel().
57805 */
57806 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
57807   int j = -1-x;
57808   assert( p->magic==VDBE_MAGIC_INIT );
57809   assert( j>=0 && j<p->nLabel );
57810   if( p->aLabel ){
57811     p->aLabel[j] = p->nOp;
57812   }
57813 }
57814
57815 /*
57816 ** Mark the VDBE as one that can only be run one time.
57817 */
57818 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
57819   p->runOnlyOnce = 1;
57820 }
57821
57822 #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
57823
57824 /*
57825 ** The following type and function are used to iterate through all opcodes
57826 ** in a Vdbe main program and each of the sub-programs (triggers) it may 
57827 ** invoke directly or indirectly. It should be used as follows:
57828 **
57829 **   Op *pOp;
57830 **   VdbeOpIter sIter;
57831 **
57832 **   memset(&sIter, 0, sizeof(sIter));
57833 **   sIter.v = v;                            // v is of type Vdbe* 
57834 **   while( (pOp = opIterNext(&sIter)) ){
57835 **     // Do something with pOp
57836 **   }
57837 **   sqlite3DbFree(v->db, sIter.apSub);
57838 ** 
57839 */
57840 typedef struct VdbeOpIter VdbeOpIter;
57841 struct VdbeOpIter {
57842   Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
57843   SubProgram **apSub;        /* Array of subprograms */
57844   int nSub;                  /* Number of entries in apSub */
57845   int iAddr;                 /* Address of next instruction to return */
57846   int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
57847 };
57848 static Op *opIterNext(VdbeOpIter *p){
57849   Vdbe *v = p->v;
57850   Op *pRet = 0;
57851   Op *aOp;
57852   int nOp;
57853
57854   if( p->iSub<=p->nSub ){
57855
57856     if( p->iSub==0 ){
57857       aOp = v->aOp;
57858       nOp = v->nOp;
57859     }else{
57860       aOp = p->apSub[p->iSub-1]->aOp;
57861       nOp = p->apSub[p->iSub-1]->nOp;
57862     }
57863     assert( p->iAddr<nOp );
57864
57865     pRet = &aOp[p->iAddr];
57866     p->iAddr++;
57867     if( p->iAddr==nOp ){
57868       p->iSub++;
57869       p->iAddr = 0;
57870     }
57871   
57872     if( pRet->p4type==P4_SUBPROGRAM ){
57873       int nByte = (p->nSub+1)*sizeof(SubProgram*);
57874       int j;
57875       for(j=0; j<p->nSub; j++){
57876         if( p->apSub[j]==pRet->p4.pProgram ) break;
57877       }
57878       if( j==p->nSub ){
57879         p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
57880         if( !p->apSub ){
57881           pRet = 0;
57882         }else{
57883           p->apSub[p->nSub++] = pRet->p4.pProgram;
57884         }
57885       }
57886     }
57887   }
57888
57889   return pRet;
57890 }
57891
57892 /*
57893 ** Check if the program stored in the VM associated with pParse may
57894 ** throw an ABORT exception (causing the statement, but not entire transaction
57895 ** to be rolled back). This condition is true if the main program or any
57896 ** sub-programs contains any of the following:
57897 **
57898 **   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
57899 **   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
57900 **   *  OP_Destroy
57901 **   *  OP_VUpdate
57902 **   *  OP_VRename
57903 **   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
57904 **
57905 ** Then check that the value of Parse.mayAbort is true if an
57906 ** ABORT may be thrown, or false otherwise. Return true if it does
57907 ** match, or false otherwise. This function is intended to be used as
57908 ** part of an assert statement in the compiler. Similar to:
57909 **
57910 **   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
57911 */
57912 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
57913   int hasAbort = 0;
57914   Op *pOp;
57915   VdbeOpIter sIter;
57916   memset(&sIter, 0, sizeof(sIter));
57917   sIter.v = v;
57918
57919   while( (pOp = opIterNext(&sIter))!=0 ){
57920     int opcode = pOp->opcode;
57921     if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename 
57922 #ifndef SQLITE_OMIT_FOREIGN_KEY
57923      || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1) 
57924 #endif
57925      || ((opcode==OP_Halt || opcode==OP_HaltIfNull) 
57926       && (pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
57927     ){
57928       hasAbort = 1;
57929       break;
57930     }
57931   }
57932   sqlite3DbFree(v->db, sIter.apSub);
57933
57934   /* Return true if hasAbort==mayAbort. Or if a malloc failure occured.
57935   ** If malloc failed, then the while() loop above may not have iterated
57936   ** through all opcodes and hasAbort may be set incorrectly. Return
57937   ** true for this case to prevent the assert() in the callers frame
57938   ** from failing.  */
57939   return ( v->db->mallocFailed || hasAbort==mayAbort );
57940 }
57941 #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
57942
57943 /*
57944 ** Loop through the program looking for P2 values that are negative
57945 ** on jump instructions.  Each such value is a label.  Resolve the
57946 ** label by setting the P2 value to its correct non-zero value.
57947 **
57948 ** This routine is called once after all opcodes have been inserted.
57949 **
57950 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument 
57951 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by 
57952 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
57953 **
57954 ** The Op.opflags field is set on all opcodes.
57955 */
57956 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
57957   int i;
57958   int nMaxArgs = *pMaxFuncArgs;
57959   Op *pOp;
57960   int *aLabel = p->aLabel;
57961   p->readOnly = 1;
57962   for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
57963     u8 opcode = pOp->opcode;
57964
57965     pOp->opflags = sqlite3OpcodeProperty[opcode];
57966     if( opcode==OP_Function || opcode==OP_AggStep ){
57967       if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
57968     }else if( (opcode==OP_Transaction && pOp->p2!=0) || opcode==OP_Vacuum ){
57969       p->readOnly = 0;
57970 #ifndef SQLITE_OMIT_VIRTUALTABLE
57971     }else if( opcode==OP_VUpdate ){
57972       if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
57973     }else if( opcode==OP_VFilter ){
57974       int n;
57975       assert( p->nOp - i >= 3 );
57976       assert( pOp[-1].opcode==OP_Integer );
57977       n = pOp[-1].p1;
57978       if( n>nMaxArgs ) nMaxArgs = n;
57979 #endif
57980     }
57981
57982     if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
57983       assert( -1-pOp->p2<p->nLabel );
57984       pOp->p2 = aLabel[-1-pOp->p2];
57985     }
57986   }
57987   sqlite3DbFree(p->db, p->aLabel);
57988   p->aLabel = 0;
57989
57990   *pMaxFuncArgs = nMaxArgs;
57991 }
57992
57993 /*
57994 ** Return the address of the next instruction to be inserted.
57995 */
57996 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
57997   assert( p->magic==VDBE_MAGIC_INIT );
57998   return p->nOp;
57999 }
58000
58001 /*
58002 ** This function returns a pointer to the array of opcodes associated with
58003 ** the Vdbe passed as the first argument. It is the callers responsibility
58004 ** to arrange for the returned array to be eventually freed using the 
58005 ** vdbeFreeOpArray() function.
58006 **
58007 ** Before returning, *pnOp is set to the number of entries in the returned
58008 ** array. Also, *pnMaxArg is set to the larger of its current value and 
58009 ** the number of entries in the Vdbe.apArg[] array required to execute the 
58010 ** returned program.
58011 */
58012 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
58013   VdbeOp *aOp = p->aOp;
58014   assert( aOp && !p->db->mallocFailed );
58015
58016   /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
58017   assert( p->btreeMask==0 );
58018
58019   resolveP2Values(p, pnMaxArg);
58020   *pnOp = p->nOp;
58021   p->aOp = 0;
58022   return aOp;
58023 }
58024
58025 /*
58026 ** Add a whole list of operations to the operation stack.  Return the
58027 ** address of the first operation added.
58028 */
58029 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
58030   int addr;
58031   assert( p->magic==VDBE_MAGIC_INIT );
58032   if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
58033     return 0;
58034   }
58035   addr = p->nOp;
58036   if( ALWAYS(nOp>0) ){
58037     int i;
58038     VdbeOpList const *pIn = aOp;
58039     for(i=0; i<nOp; i++, pIn++){
58040       int p2 = pIn->p2;
58041       VdbeOp *pOut = &p->aOp[i+addr];
58042       pOut->opcode = pIn->opcode;
58043       pOut->p1 = pIn->p1;
58044       if( p2<0 && (sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){
58045         pOut->p2 = addr + ADDR(p2);
58046       }else{
58047         pOut->p2 = p2;
58048       }
58049       pOut->p3 = pIn->p3;
58050       pOut->p4type = P4_NOTUSED;
58051       pOut->p4.p = 0;
58052       pOut->p5 = 0;
58053 #ifdef SQLITE_DEBUG
58054       pOut->zComment = 0;
58055       if( sqlite3VdbeAddopTrace ){
58056         sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
58057       }
58058 #endif
58059     }
58060     p->nOp += nOp;
58061   }
58062   return addr;
58063 }
58064
58065 /*
58066 ** Change the value of the P1 operand for a specific instruction.
58067 ** This routine is useful when a large program is loaded from a
58068 ** static array using sqlite3VdbeAddOpList but we want to make a
58069 ** few minor changes to the program.
58070 */
58071 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
58072   assert( p!=0 );
58073   assert( addr>=0 );
58074   if( p->nOp>addr ){
58075     p->aOp[addr].p1 = val;
58076   }
58077 }
58078
58079 /*
58080 ** Change the value of the P2 operand for a specific instruction.
58081 ** This routine is useful for setting a jump destination.
58082 */
58083 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
58084   assert( p!=0 );
58085   assert( addr>=0 );
58086   if( p->nOp>addr ){
58087     p->aOp[addr].p2 = val;
58088   }
58089 }
58090
58091 /*
58092 ** Change the value of the P3 operand for a specific instruction.
58093 */
58094 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, int addr, int val){
58095   assert( p!=0 );
58096   assert( addr>=0 );
58097   if( p->nOp>addr ){
58098     p->aOp[addr].p3 = val;
58099   }
58100 }
58101
58102 /*
58103 ** Change the value of the P5 operand for the most recently
58104 ** added operation.
58105 */
58106 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
58107   assert( p!=0 );
58108   if( p->aOp ){
58109     assert( p->nOp>0 );
58110     p->aOp[p->nOp-1].p5 = val;
58111   }
58112 }
58113
58114 /*
58115 ** Change the P2 operand of instruction addr so that it points to
58116 ** the address of the next instruction to be coded.
58117 */
58118 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
58119   assert( addr>=0 );
58120   sqlite3VdbeChangeP2(p, addr, p->nOp);
58121 }
58122
58123
58124 /*
58125 ** If the input FuncDef structure is ephemeral, then free it.  If
58126 ** the FuncDef is not ephermal, then do nothing.
58127 */
58128 static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
58129   if( ALWAYS(pDef) && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
58130     sqlite3DbFree(db, pDef);
58131   }
58132 }
58133
58134 static void vdbeFreeOpArray(sqlite3 *, Op *, int);
58135
58136 /*
58137 ** Delete a P4 value if necessary.
58138 */
58139 static void freeP4(sqlite3 *db, int p4type, void *p4){
58140   if( p4 ){
58141     assert( db );
58142     switch( p4type ){
58143       case P4_REAL:
58144       case P4_INT64:
58145       case P4_DYNAMIC:
58146       case P4_KEYINFO:
58147       case P4_INTARRAY:
58148       case P4_KEYINFO_HANDOFF: {
58149         sqlite3DbFree(db, p4);
58150         break;
58151       }
58152       case P4_MPRINTF: {
58153         if( db->pnBytesFreed==0 ) sqlite3_free(p4);
58154         break;
58155       }
58156       case P4_VDBEFUNC: {
58157         VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
58158         freeEphemeralFunction(db, pVdbeFunc->pFunc);
58159         if( db->pnBytesFreed==0 ) sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
58160         sqlite3DbFree(db, pVdbeFunc);
58161         break;
58162       }
58163       case P4_FUNCDEF: {
58164         freeEphemeralFunction(db, (FuncDef*)p4);
58165         break;
58166       }
58167       case P4_MEM: {
58168         if( db->pnBytesFreed==0 ){
58169           sqlite3ValueFree((sqlite3_value*)p4);
58170         }else{
58171           Mem *p = (Mem*)p4;
58172           sqlite3DbFree(db, p->zMalloc);
58173           sqlite3DbFree(db, p);
58174         }
58175         break;
58176       }
58177       case P4_VTAB : {
58178         if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
58179         break;
58180       }
58181     }
58182   }
58183 }
58184
58185 /*
58186 ** Free the space allocated for aOp and any p4 values allocated for the
58187 ** opcodes contained within. If aOp is not NULL it is assumed to contain 
58188 ** nOp entries. 
58189 */
58190 static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
58191   if( aOp ){
58192     Op *pOp;
58193     for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
58194       freeP4(db, pOp->p4type, pOp->p4.p);
58195 #ifdef SQLITE_DEBUG
58196       sqlite3DbFree(db, pOp->zComment);
58197 #endif     
58198     }
58199   }
58200   sqlite3DbFree(db, aOp);
58201 }
58202
58203 /*
58204 ** Link the SubProgram object passed as the second argument into the linked
58205 ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
58206 ** objects when the VM is no longer required.
58207 */
58208 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
58209   p->pNext = pVdbe->pProgram;
58210   pVdbe->pProgram = p;
58211 }
58212
58213 /*
58214 ** Change N opcodes starting at addr to No-ops.
58215 */
58216 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr, int N){
58217   if( p->aOp ){
58218     VdbeOp *pOp = &p->aOp[addr];
58219     sqlite3 *db = p->db;
58220     while( N-- ){
58221       freeP4(db, pOp->p4type, pOp->p4.p);
58222       memset(pOp, 0, sizeof(pOp[0]));
58223       pOp->opcode = OP_Noop;
58224       pOp++;
58225     }
58226   }
58227 }
58228
58229 /*
58230 ** Change the value of the P4 operand for a specific instruction.
58231 ** This routine is useful when a large program is loaded from a
58232 ** static array using sqlite3VdbeAddOpList but we want to make a
58233 ** few minor changes to the program.
58234 **
58235 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
58236 ** the string is made into memory obtained from sqlite3_malloc().
58237 ** A value of n==0 means copy bytes of zP4 up to and including the
58238 ** first null byte.  If n>0 then copy n+1 bytes of zP4.
58239 **
58240 ** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
58241 ** A copy is made of the KeyInfo structure into memory obtained from
58242 ** sqlite3_malloc, to be freed when the Vdbe is finalized.
58243 ** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
58244 ** stored in memory that the caller has obtained from sqlite3_malloc. The 
58245 ** caller should not free the allocation, it will be freed when the Vdbe is
58246 ** finalized.
58247 ** 
58248 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
58249 ** to a string or structure that is guaranteed to exist for the lifetime of
58250 ** the Vdbe. In these cases we can just copy the pointer.
58251 **
58252 ** If addr<0 then change P4 on the most recently inserted instruction.
58253 */
58254 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
58255   Op *pOp;
58256   sqlite3 *db;
58257   assert( p!=0 );
58258   db = p->db;
58259   assert( p->magic==VDBE_MAGIC_INIT );
58260   if( p->aOp==0 || db->mallocFailed ){
58261     if ( n!=P4_KEYINFO && n!=P4_VTAB ) {
58262       freeP4(db, n, (void*)*(char**)&zP4);
58263     }
58264     return;
58265   }
58266   assert( p->nOp>0 );
58267   assert( addr<p->nOp );
58268   if( addr<0 ){
58269     addr = p->nOp - 1;
58270   }
58271   pOp = &p->aOp[addr];
58272   freeP4(db, pOp->p4type, pOp->p4.p);
58273   pOp->p4.p = 0;
58274   if( n==P4_INT32 ){
58275     /* Note: this cast is safe, because the origin data point was an int
58276     ** that was cast to a (const char *). */
58277     pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
58278     pOp->p4type = P4_INT32;
58279   }else if( zP4==0 ){
58280     pOp->p4.p = 0;
58281     pOp->p4type = P4_NOTUSED;
58282   }else if( n==P4_KEYINFO ){
58283     KeyInfo *pKeyInfo;
58284     int nField, nByte;
58285
58286     nField = ((KeyInfo*)zP4)->nField;
58287     nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
58288     pKeyInfo = sqlite3DbMallocRaw(0, nByte);
58289     pOp->p4.pKeyInfo = pKeyInfo;
58290     if( pKeyInfo ){
58291       u8 *aSortOrder;
58292       memcpy((char*)pKeyInfo, zP4, nByte - nField);
58293       aSortOrder = pKeyInfo->aSortOrder;
58294       if( aSortOrder ){
58295         pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
58296         memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
58297       }
58298       pOp->p4type = P4_KEYINFO;
58299     }else{
58300       p->db->mallocFailed = 1;
58301       pOp->p4type = P4_NOTUSED;
58302     }
58303   }else if( n==P4_KEYINFO_HANDOFF ){
58304     pOp->p4.p = (void*)zP4;
58305     pOp->p4type = P4_KEYINFO;
58306   }else if( n==P4_VTAB ){
58307     pOp->p4.p = (void*)zP4;
58308     pOp->p4type = P4_VTAB;
58309     sqlite3VtabLock((VTable *)zP4);
58310     assert( ((VTable *)zP4)->db==p->db );
58311   }else if( n<0 ){
58312     pOp->p4.p = (void*)zP4;
58313     pOp->p4type = (signed char)n;
58314   }else{
58315     if( n==0 ) n = sqlite3Strlen30(zP4);
58316     pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
58317     pOp->p4type = P4_DYNAMIC;
58318   }
58319 }
58320
58321 #ifndef NDEBUG
58322 /*
58323 ** Change the comment on the the most recently coded instruction.  Or
58324 ** insert a No-op and add the comment to that new instruction.  This
58325 ** makes the code easier to read during debugging.  None of this happens
58326 ** in a production build.
58327 */
58328 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
58329   va_list ap;
58330   if( !p ) return;
58331   assert( p->nOp>0 || p->aOp==0 );
58332   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
58333   if( p->nOp ){
58334     char **pz = &p->aOp[p->nOp-1].zComment;
58335     va_start(ap, zFormat);
58336     sqlite3DbFree(p->db, *pz);
58337     *pz = sqlite3VMPrintf(p->db, zFormat, ap);
58338     va_end(ap);
58339   }
58340 }
58341 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
58342   va_list ap;
58343   if( !p ) return;
58344   sqlite3VdbeAddOp0(p, OP_Noop);
58345   assert( p->nOp>0 || p->aOp==0 );
58346   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
58347   if( p->nOp ){
58348     char **pz = &p->aOp[p->nOp-1].zComment;
58349     va_start(ap, zFormat);
58350     sqlite3DbFree(p->db, *pz);
58351     *pz = sqlite3VMPrintf(p->db, zFormat, ap);
58352     va_end(ap);
58353   }
58354 }
58355 #endif  /* NDEBUG */
58356
58357 /*
58358 ** Return the opcode for a given address.  If the address is -1, then
58359 ** return the most recently inserted opcode.
58360 **
58361 ** If a memory allocation error has occurred prior to the calling of this
58362 ** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
58363 ** is readable but not writable, though it is cast to a writable value.
58364 ** The return of a dummy opcode allows the call to continue functioning
58365 ** after a OOM fault without having to check to see if the return from 
58366 ** this routine is a valid pointer.  But because the dummy.opcode is 0,
58367 ** dummy will never be written to.  This is verified by code inspection and
58368 ** by running with Valgrind.
58369 **
58370 ** About the #ifdef SQLITE_OMIT_TRACE:  Normally, this routine is never called
58371 ** unless p->nOp>0.  This is because in the absense of SQLITE_OMIT_TRACE,
58372 ** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
58373 ** a new VDBE is created.  So we are free to set addr to p->nOp-1 without
58374 ** having to double-check to make sure that the result is non-negative. But
58375 ** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
58376 ** check the value of p->nOp-1 before continuing.
58377 */
58378 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
58379   /* C89 specifies that the constant "dummy" will be initialized to all
58380   ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
58381   static const VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
58382   assert( p->magic==VDBE_MAGIC_INIT );
58383   if( addr<0 ){
58384 #ifdef SQLITE_OMIT_TRACE
58385     if( p->nOp==0 ) return (VdbeOp*)&dummy;
58386 #endif
58387     addr = p->nOp - 1;
58388   }
58389   assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
58390   if( p->db->mallocFailed ){
58391     return (VdbeOp*)&dummy;
58392   }else{
58393     return &p->aOp[addr];
58394   }
58395 }
58396
58397 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
58398      || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
58399 /*
58400 ** Compute a string that describes the P4 parameter for an opcode.
58401 ** Use zTemp for any required temporary buffer space.
58402 */
58403 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
58404   char *zP4 = zTemp;
58405   assert( nTemp>=20 );
58406   switch( pOp->p4type ){
58407     case P4_KEYINFO_STATIC:
58408     case P4_KEYINFO: {
58409       int i, j;
58410       KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
58411       sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
58412       i = sqlite3Strlen30(zTemp);
58413       for(j=0; j<pKeyInfo->nField; j++){
58414         CollSeq *pColl = pKeyInfo->aColl[j];
58415         if( pColl ){
58416           int n = sqlite3Strlen30(pColl->zName);
58417           if( i+n>nTemp-6 ){
58418             memcpy(&zTemp[i],",...",4);
58419             break;
58420           }
58421           zTemp[i++] = ',';
58422           if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
58423             zTemp[i++] = '-';
58424           }
58425           memcpy(&zTemp[i], pColl->zName,n+1);
58426           i += n;
58427         }else if( i+4<nTemp-6 ){
58428           memcpy(&zTemp[i],",nil",4);
58429           i += 4;
58430         }
58431       }
58432       zTemp[i++] = ')';
58433       zTemp[i] = 0;
58434       assert( i<nTemp );
58435       break;
58436     }
58437     case P4_COLLSEQ: {
58438       CollSeq *pColl = pOp->p4.pColl;
58439       sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
58440       break;
58441     }
58442     case P4_FUNCDEF: {
58443       FuncDef *pDef = pOp->p4.pFunc;
58444       sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
58445       break;
58446     }
58447     case P4_INT64: {
58448       sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
58449       break;
58450     }
58451     case P4_INT32: {
58452       sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
58453       break;
58454     }
58455     case P4_REAL: {
58456       sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
58457       break;
58458     }
58459     case P4_MEM: {
58460       Mem *pMem = pOp->p4.pMem;
58461       assert( (pMem->flags & MEM_Null)==0 );
58462       if( pMem->flags & MEM_Str ){
58463         zP4 = pMem->z;
58464       }else if( pMem->flags & MEM_Int ){
58465         sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
58466       }else if( pMem->flags & MEM_Real ){
58467         sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
58468       }else{
58469         assert( pMem->flags & MEM_Blob );
58470         zP4 = "(blob)";
58471       }
58472       break;
58473     }
58474 #ifndef SQLITE_OMIT_VIRTUALTABLE
58475     case P4_VTAB: {
58476       sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
58477       sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
58478       break;
58479     }
58480 #endif
58481     case P4_INTARRAY: {
58482       sqlite3_snprintf(nTemp, zTemp, "intarray");
58483       break;
58484     }
58485     case P4_SUBPROGRAM: {
58486       sqlite3_snprintf(nTemp, zTemp, "program");
58487       break;
58488     }
58489     default: {
58490       zP4 = pOp->p4.z;
58491       if( zP4==0 ){
58492         zP4 = zTemp;
58493         zTemp[0] = 0;
58494       }
58495     }
58496   }
58497   assert( zP4!=0 );
58498   return zP4;
58499 }
58500 #endif
58501
58502 /*
58503 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
58504 **
58505 ** The prepared statements need to know in advance the complete set of
58506 ** attached databases that they will be using.  A mask of these databases
58507 ** is maintained in p->btreeMask and is used for locking and other purposes.
58508 */
58509 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
58510   assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
58511   assert( i<(int)sizeof(p->btreeMask)*8 );
58512   p->btreeMask |= ((yDbMask)1)<<i;
58513   if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
58514     p->lockMask |= ((yDbMask)1)<<i;
58515   }
58516 }
58517
58518 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
58519 /*
58520 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
58521 ** this routine obtains the mutex associated with each BtShared structure
58522 ** that may be accessed by the VM passed as an argument. In doing so it also
58523 ** sets the BtShared.db member of each of the BtShared structures, ensuring
58524 ** that the correct busy-handler callback is invoked if required.
58525 **
58526 ** If SQLite is not threadsafe but does support shared-cache mode, then
58527 ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
58528 ** of all of BtShared structures accessible via the database handle 
58529 ** associated with the VM.
58530 **
58531 ** If SQLite is not threadsafe and does not support shared-cache mode, this
58532 ** function is a no-op.
58533 **
58534 ** The p->btreeMask field is a bitmask of all btrees that the prepared 
58535 ** statement p will ever use.  Let N be the number of bits in p->btreeMask
58536 ** corresponding to btrees that use shared cache.  Then the runtime of
58537 ** this routine is N*N.  But as N is rarely more than 1, this should not
58538 ** be a problem.
58539 */
58540 SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
58541   int i;
58542   yDbMask mask;
58543   sqlite3 *db;
58544   Db *aDb;
58545   int nDb;
58546   if( p->lockMask==0 ) return;  /* The common case */
58547   db = p->db;
58548   aDb = db->aDb;
58549   nDb = db->nDb;
58550   for(i=0, mask=1; i<nDb; i++, mask += mask){
58551     if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
58552       sqlite3BtreeEnter(aDb[i].pBt);
58553     }
58554   }
58555 }
58556 #endif
58557
58558 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
58559 /*
58560 ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
58561 */
58562 SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
58563   int i;
58564   yDbMask mask;
58565   sqlite3 *db;
58566   Db *aDb;
58567   int nDb;
58568   if( p->lockMask==0 ) return;  /* The common case */
58569   db = p->db;
58570   aDb = db->aDb;
58571   nDb = db->nDb;
58572   for(i=0, mask=1; i<nDb; i++, mask += mask){
58573     if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
58574       sqlite3BtreeLeave(aDb[i].pBt);
58575     }
58576   }
58577 }
58578 #endif
58579
58580 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
58581 /*
58582 ** Print a single opcode.  This routine is used for debugging only.
58583 */
58584 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
58585   char *zP4;
58586   char zPtr[50];
58587   static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
58588   if( pOut==0 ) pOut = stdout;
58589   zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
58590   fprintf(pOut, zFormat1, pc, 
58591       sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
58592 #ifdef SQLITE_DEBUG
58593       pOp->zComment ? pOp->zComment : ""
58594 #else
58595       ""
58596 #endif
58597   );
58598   fflush(pOut);
58599 }
58600 #endif
58601
58602 /*
58603 ** Release an array of N Mem elements
58604 */
58605 static void releaseMemArray(Mem *p, int N){
58606   if( p && N ){
58607     Mem *pEnd;
58608     sqlite3 *db = p->db;
58609     u8 malloc_failed = db->mallocFailed;
58610     if( db->pnBytesFreed ){
58611       for(pEnd=&p[N]; p<pEnd; p++){
58612         sqlite3DbFree(db, p->zMalloc);
58613       }
58614       return;
58615     }
58616     for(pEnd=&p[N]; p<pEnd; p++){
58617       assert( (&p[1])==pEnd || p[0].db==p[1].db );
58618
58619       /* This block is really an inlined version of sqlite3VdbeMemRelease()
58620       ** that takes advantage of the fact that the memory cell value is 
58621       ** being set to NULL after releasing any dynamic resources.
58622       **
58623       ** The justification for duplicating code is that according to 
58624       ** callgrind, this causes a certain test case to hit the CPU 4.7 
58625       ** percent less (x86 linux, gcc version 4.1.2, -O6) than if 
58626       ** sqlite3MemRelease() were called from here. With -O2, this jumps
58627       ** to 6.6 percent. The test case is inserting 1000 rows into a table 
58628       ** with no indexes using a single prepared INSERT statement, bind() 
58629       ** and reset(). Inserts are grouped into a transaction.
58630       */
58631       if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
58632         sqlite3VdbeMemRelease(p);
58633       }else if( p->zMalloc ){
58634         sqlite3DbFree(db, p->zMalloc);
58635         p->zMalloc = 0;
58636       }
58637
58638       p->flags = MEM_Null;
58639     }
58640     db->mallocFailed = malloc_failed;
58641   }
58642 }
58643
58644 /*
58645 ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
58646 ** allocated by the OP_Program opcode in sqlite3VdbeExec().
58647 */
58648 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
58649   int i;
58650   Mem *aMem = VdbeFrameMem(p);
58651   VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
58652   for(i=0; i<p->nChildCsr; i++){
58653     sqlite3VdbeFreeCursor(p->v, apCsr[i]);
58654   }
58655   releaseMemArray(aMem, p->nChildMem);
58656   sqlite3DbFree(p->v->db, p);
58657 }
58658
58659 #ifndef SQLITE_OMIT_EXPLAIN
58660 /*
58661 ** Give a listing of the program in the virtual machine.
58662 **
58663 ** The interface is the same as sqlite3VdbeExec().  But instead of
58664 ** running the code, it invokes the callback once for each instruction.
58665 ** This feature is used to implement "EXPLAIN".
58666 **
58667 ** When p->explain==1, each instruction is listed.  When
58668 ** p->explain==2, only OP_Explain instructions are listed and these
58669 ** are shown in a different format.  p->explain==2 is used to implement
58670 ** EXPLAIN QUERY PLAN.
58671 **
58672 ** When p->explain==1, first the main program is listed, then each of
58673 ** the trigger subprograms are listed one by one.
58674 */
58675 SQLITE_PRIVATE int sqlite3VdbeList(
58676   Vdbe *p                   /* The VDBE */
58677 ){
58678   int nRow;                            /* Stop when row count reaches this */
58679   int nSub = 0;                        /* Number of sub-vdbes seen so far */
58680   SubProgram **apSub = 0;              /* Array of sub-vdbes */
58681   Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
58682   sqlite3 *db = p->db;                 /* The database connection */
58683   int i;                               /* Loop counter */
58684   int rc = SQLITE_OK;                  /* Return code */
58685   Mem *pMem = p->pResultSet = &p->aMem[1];  /* First Mem of result set */
58686
58687   assert( p->explain );
58688   assert( p->magic==VDBE_MAGIC_RUN );
58689   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
58690
58691   /* Even though this opcode does not use dynamic strings for
58692   ** the result, result columns may become dynamic if the user calls
58693   ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
58694   */
58695   releaseMemArray(pMem, 8);
58696
58697   if( p->rc==SQLITE_NOMEM ){
58698     /* This happens if a malloc() inside a call to sqlite3_column_text() or
58699     ** sqlite3_column_text16() failed.  */
58700     db->mallocFailed = 1;
58701     return SQLITE_ERROR;
58702   }
58703
58704   /* When the number of output rows reaches nRow, that means the
58705   ** listing has finished and sqlite3_step() should return SQLITE_DONE.
58706   ** nRow is the sum of the number of rows in the main program, plus
58707   ** the sum of the number of rows in all trigger subprograms encountered
58708   ** so far.  The nRow value will increase as new trigger subprograms are
58709   ** encountered, but p->pc will eventually catch up to nRow.
58710   */
58711   nRow = p->nOp;
58712   if( p->explain==1 ){
58713     /* The first 8 memory cells are used for the result set.  So we will
58714     ** commandeer the 9th cell to use as storage for an array of pointers
58715     ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
58716     ** cells.  */
58717     assert( p->nMem>9 );
58718     pSub = &p->aMem[9];
58719     if( pSub->flags&MEM_Blob ){
58720       /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
58721       ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
58722       nSub = pSub->n/sizeof(Vdbe*);
58723       apSub = (SubProgram **)pSub->z;
58724     }
58725     for(i=0; i<nSub; i++){
58726       nRow += apSub[i]->nOp;
58727     }
58728   }
58729
58730   do{
58731     i = p->pc++;
58732   }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
58733   if( i>=nRow ){
58734     p->rc = SQLITE_OK;
58735     rc = SQLITE_DONE;
58736   }else if( db->u1.isInterrupted ){
58737     p->rc = SQLITE_INTERRUPT;
58738     rc = SQLITE_ERROR;
58739     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
58740   }else{
58741     char *z;
58742     Op *pOp;
58743     if( i<p->nOp ){
58744       /* The output line number is small enough that we are still in the
58745       ** main program. */
58746       pOp = &p->aOp[i];
58747     }else{
58748       /* We are currently listing subprograms.  Figure out which one and
58749       ** pick up the appropriate opcode. */
58750       int j;
58751       i -= p->nOp;
58752       for(j=0; i>=apSub[j]->nOp; j++){
58753         i -= apSub[j]->nOp;
58754       }
58755       pOp = &apSub[j]->aOp[i];
58756     }
58757     if( p->explain==1 ){
58758       pMem->flags = MEM_Int;
58759       pMem->type = SQLITE_INTEGER;
58760       pMem->u.i = i;                                /* Program counter */
58761       pMem++;
58762   
58763       pMem->flags = MEM_Static|MEM_Str|MEM_Term;
58764       pMem->z = (char*)sqlite3OpcodeName(pOp->opcode);  /* Opcode */
58765       assert( pMem->z!=0 );
58766       pMem->n = sqlite3Strlen30(pMem->z);
58767       pMem->type = SQLITE_TEXT;
58768       pMem->enc = SQLITE_UTF8;
58769       pMem++;
58770
58771       /* When an OP_Program opcode is encounter (the only opcode that has
58772       ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
58773       ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
58774       ** has not already been seen.
58775       */
58776       if( pOp->p4type==P4_SUBPROGRAM ){
58777         int nByte = (nSub+1)*sizeof(SubProgram*);
58778         int j;
58779         for(j=0; j<nSub; j++){
58780           if( apSub[j]==pOp->p4.pProgram ) break;
58781         }
58782         if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, 1) ){
58783           apSub = (SubProgram **)pSub->z;
58784           apSub[nSub++] = pOp->p4.pProgram;
58785           pSub->flags |= MEM_Blob;
58786           pSub->n = nSub*sizeof(SubProgram*);
58787         }
58788       }
58789     }
58790
58791     pMem->flags = MEM_Int;
58792     pMem->u.i = pOp->p1;                          /* P1 */
58793     pMem->type = SQLITE_INTEGER;
58794     pMem++;
58795
58796     pMem->flags = MEM_Int;
58797     pMem->u.i = pOp->p2;                          /* P2 */
58798     pMem->type = SQLITE_INTEGER;
58799     pMem++;
58800
58801     pMem->flags = MEM_Int;
58802     pMem->u.i = pOp->p3;                          /* P3 */
58803     pMem->type = SQLITE_INTEGER;
58804     pMem++;
58805
58806     if( sqlite3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
58807       assert( p->db->mallocFailed );
58808       return SQLITE_ERROR;
58809     }
58810     pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
58811     z = displayP4(pOp, pMem->z, 32);
58812     if( z!=pMem->z ){
58813       sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
58814     }else{
58815       assert( pMem->z!=0 );
58816       pMem->n = sqlite3Strlen30(pMem->z);
58817       pMem->enc = SQLITE_UTF8;
58818     }
58819     pMem->type = SQLITE_TEXT;
58820     pMem++;
58821
58822     if( p->explain==1 ){
58823       if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
58824         assert( p->db->mallocFailed );
58825         return SQLITE_ERROR;
58826       }
58827       pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
58828       pMem->n = 2;
58829       sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
58830       pMem->type = SQLITE_TEXT;
58831       pMem->enc = SQLITE_UTF8;
58832       pMem++;
58833   
58834 #ifdef SQLITE_DEBUG
58835       if( pOp->zComment ){
58836         pMem->flags = MEM_Str|MEM_Term;
58837         pMem->z = pOp->zComment;
58838         pMem->n = sqlite3Strlen30(pMem->z);
58839         pMem->enc = SQLITE_UTF8;
58840         pMem->type = SQLITE_TEXT;
58841       }else
58842 #endif
58843       {
58844         pMem->flags = MEM_Null;                       /* Comment */
58845         pMem->type = SQLITE_NULL;
58846       }
58847     }
58848
58849     p->nResColumn = 8 - 4*(p->explain-1);
58850     p->rc = SQLITE_OK;
58851     rc = SQLITE_ROW;
58852   }
58853   return rc;
58854 }
58855 #endif /* SQLITE_OMIT_EXPLAIN */
58856
58857 #ifdef SQLITE_DEBUG
58858 /*
58859 ** Print the SQL that was used to generate a VDBE program.
58860 */
58861 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
58862   int nOp = p->nOp;
58863   VdbeOp *pOp;
58864   if( nOp<1 ) return;
58865   pOp = &p->aOp[0];
58866   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
58867     const char *z = pOp->p4.z;
58868     while( sqlite3Isspace(*z) ) z++;
58869     printf("SQL: [%s]\n", z);
58870   }
58871 }
58872 #endif
58873
58874 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
58875 /*
58876 ** Print an IOTRACE message showing SQL content.
58877 */
58878 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
58879   int nOp = p->nOp;
58880   VdbeOp *pOp;
58881   if( sqlite3IoTrace==0 ) return;
58882   if( nOp<1 ) return;
58883   pOp = &p->aOp[0];
58884   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
58885     int i, j;
58886     char z[1000];
58887     sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
58888     for(i=0; sqlite3Isspace(z[i]); i++){}
58889     for(j=0; z[i]; i++){
58890       if( sqlite3Isspace(z[i]) ){
58891         if( z[i-1]!=' ' ){
58892           z[j++] = ' ';
58893         }
58894       }else{
58895         z[j++] = z[i];
58896       }
58897     }
58898     z[j] = 0;
58899     sqlite3IoTrace("SQL %s\n", z);
58900   }
58901 }
58902 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
58903
58904 /*
58905 ** Allocate space from a fixed size buffer and return a pointer to
58906 ** that space.  If insufficient space is available, return NULL.
58907 **
58908 ** The pBuf parameter is the initial value of a pointer which will
58909 ** receive the new memory.  pBuf is normally NULL.  If pBuf is not
58910 ** NULL, it means that memory space has already been allocated and that
58911 ** this routine should not allocate any new memory.  When pBuf is not
58912 ** NULL simply return pBuf.  Only allocate new memory space when pBuf
58913 ** is NULL.
58914 **
58915 ** nByte is the number of bytes of space needed.
58916 **
58917 ** *ppFrom points to available space and pEnd points to the end of the
58918 ** available space.  When space is allocated, *ppFrom is advanced past
58919 ** the end of the allocated space.
58920 **
58921 ** *pnByte is a counter of the number of bytes of space that have failed
58922 ** to allocate.  If there is insufficient space in *ppFrom to satisfy the
58923 ** request, then increment *pnByte by the amount of the request.
58924 */
58925 static void *allocSpace(
58926   void *pBuf,          /* Where return pointer will be stored */
58927   int nByte,           /* Number of bytes to allocate */
58928   u8 **ppFrom,         /* IN/OUT: Allocate from *ppFrom */
58929   u8 *pEnd,            /* Pointer to 1 byte past the end of *ppFrom buffer */
58930   int *pnByte          /* If allocation cannot be made, increment *pnByte */
58931 ){
58932   assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
58933   if( pBuf ) return pBuf;
58934   nByte = ROUND8(nByte);
58935   if( &(*ppFrom)[nByte] <= pEnd ){
58936     pBuf = (void*)*ppFrom;
58937     *ppFrom += nByte;
58938   }else{
58939     *pnByte += nByte;
58940   }
58941   return pBuf;
58942 }
58943
58944 /*
58945 ** Rewind the VDBE back to the beginning in preparation for
58946 ** running it.
58947 */
58948 SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
58949 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
58950   int i;
58951 #endif
58952   assert( p!=0 );
58953   assert( p->magic==VDBE_MAGIC_INIT );
58954
58955   /* There should be at least one opcode.
58956   */
58957   assert( p->nOp>0 );
58958
58959   /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
58960   p->magic = VDBE_MAGIC_RUN;
58961
58962 #ifdef SQLITE_DEBUG
58963   for(i=1; i<p->nMem; i++){
58964     assert( p->aMem[i].db==p->db );
58965   }
58966 #endif
58967   p->pc = -1;
58968   p->rc = SQLITE_OK;
58969   p->errorAction = OE_Abort;
58970   p->magic = VDBE_MAGIC_RUN;
58971   p->nChange = 0;
58972   p->cacheCtr = 1;
58973   p->minWriteFileFormat = 255;
58974   p->iStatement = 0;
58975   p->nFkConstraint = 0;
58976 #ifdef VDBE_PROFILE
58977   for(i=0; i<p->nOp; i++){
58978     p->aOp[i].cnt = 0;
58979     p->aOp[i].cycles = 0;
58980   }
58981 #endif
58982 }
58983
58984 /*
58985 ** Prepare a virtual machine for execution for the first time after
58986 ** creating the virtual machine.  This involves things such
58987 ** as allocating stack space and initializing the program counter.
58988 ** After the VDBE has be prepped, it can be executed by one or more
58989 ** calls to sqlite3VdbeExec().  
58990 **
58991 ** This function may be called exact once on a each virtual machine.
58992 ** After this routine is called the VM has been "packaged" and is ready
58993 ** to run.  After this routine is called, futher calls to 
58994 ** sqlite3VdbeAddOp() functions are prohibited.  This routine disconnects
58995 ** the Vdbe from the Parse object that helped generate it so that the
58996 ** the Vdbe becomes an independent entity and the Parse object can be
58997 ** destroyed.
58998 **
58999 ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
59000 ** to its initial state after it has been run.
59001 */
59002 SQLITE_PRIVATE void sqlite3VdbeMakeReady(
59003   Vdbe *p,                       /* The VDBE */
59004   Parse *pParse                  /* Parsing context */
59005 ){
59006   sqlite3 *db;                   /* The database connection */
59007   int nVar;                      /* Number of parameters */
59008   int nMem;                      /* Number of VM memory registers */
59009   int nCursor;                   /* Number of cursors required */
59010   int nArg;                      /* Number of arguments in subprograms */
59011   int n;                         /* Loop counter */
59012   u8 *zCsr;                      /* Memory available for allocation */
59013   u8 *zEnd;                      /* First byte past allocated memory */
59014   int nByte;                     /* How much extra memory is needed */
59015
59016   assert( p!=0 );
59017   assert( p->nOp>0 );
59018   assert( pParse!=0 );
59019   assert( p->magic==VDBE_MAGIC_INIT );
59020   db = p->db;
59021   assert( db->mallocFailed==0 );
59022   nVar = pParse->nVar;
59023   nMem = pParse->nMem;
59024   nCursor = pParse->nTab;
59025   nArg = pParse->nMaxArg;
59026   
59027   /* For each cursor required, also allocate a memory cell. Memory
59028   ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
59029   ** the vdbe program. Instead they are used to allocate space for
59030   ** VdbeCursor/BtCursor structures. The blob of memory associated with 
59031   ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
59032   ** stores the blob of memory associated with cursor 1, etc.
59033   **
59034   ** See also: allocateCursor().
59035   */
59036   nMem += nCursor;
59037
59038   /* Allocate space for memory registers, SQL variables, VDBE cursors and 
59039   ** an array to marshal SQL function arguments in.
59040   */
59041   zCsr = (u8*)&p->aOp[p->nOp];       /* Memory avaliable for allocation */
59042   zEnd = (u8*)&p->aOp[p->nOpAlloc];  /* First byte past end of zCsr[] */
59043
59044   resolveP2Values(p, &nArg);
59045   p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
59046   if( pParse->explain && nMem<10 ){
59047     nMem = 10;
59048   }
59049   memset(zCsr, 0, zEnd-zCsr);
59050   zCsr += (zCsr - (u8*)0)&7;
59051   assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
59052   p->expired = 0;
59053
59054   /* Memory for registers, parameters, cursor, etc, is allocated in two
59055   ** passes.  On the first pass, we try to reuse unused space at the 
59056   ** end of the opcode array.  If we are unable to satisfy all memory
59057   ** requirements by reusing the opcode array tail, then the second
59058   ** pass will fill in the rest using a fresh allocation.  
59059   **
59060   ** This two-pass approach that reuses as much memory as possible from
59061   ** the leftover space at the end of the opcode array can significantly
59062   ** reduce the amount of memory held by a prepared statement.
59063   */
59064   do {
59065     nByte = 0;
59066     p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
59067     p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
59068     p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
59069     p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
59070     p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
59071                           &zCsr, zEnd, &nByte);
59072     if( nByte ){
59073       p->pFree = sqlite3DbMallocZero(db, nByte);
59074     }
59075     zCsr = p->pFree;
59076     zEnd = &zCsr[nByte];
59077   }while( nByte && !db->mallocFailed );
59078
59079   p->nCursor = (u16)nCursor;
59080   if( p->aVar ){
59081     p->nVar = (ynVar)nVar;
59082     for(n=0; n<nVar; n++){
59083       p->aVar[n].flags = MEM_Null;
59084       p->aVar[n].db = db;
59085     }
59086   }
59087   if( p->azVar ){
59088     p->nzVar = pParse->nzVar;
59089     memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0]));
59090     memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0]));
59091   }
59092   if( p->aMem ){
59093     p->aMem--;                      /* aMem[] goes from 1..nMem */
59094     p->nMem = nMem;                 /*       not from 0..nMem-1 */
59095     for(n=1; n<=nMem; n++){
59096       p->aMem[n].flags = MEM_Null;
59097       p->aMem[n].db = db;
59098     }
59099   }
59100   p->explain = pParse->explain;
59101   sqlite3VdbeRewind(p);
59102 }
59103
59104 /*
59105 ** Close a VDBE cursor and release all the resources that cursor 
59106 ** happens to hold.
59107 */
59108 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
59109   if( pCx==0 ){
59110     return;
59111   }
59112   if( pCx->pBt ){
59113     sqlite3BtreeClose(pCx->pBt);
59114     /* The pCx->pCursor will be close automatically, if it exists, by
59115     ** the call above. */
59116   }else if( pCx->pCursor ){
59117     sqlite3BtreeCloseCursor(pCx->pCursor);
59118   }
59119 #ifndef SQLITE_OMIT_VIRTUALTABLE
59120   if( pCx->pVtabCursor ){
59121     sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
59122     const sqlite3_module *pModule = pCx->pModule;
59123     p->inVtabMethod = 1;
59124     pModule->xClose(pVtabCursor);
59125     p->inVtabMethod = 0;
59126   }
59127 #endif
59128 }
59129
59130 /*
59131 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
59132 ** is used, for example, when a trigger sub-program is halted to restore
59133 ** control to the main program.
59134 */
59135 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
59136   Vdbe *v = pFrame->v;
59137   v->aOp = pFrame->aOp;
59138   v->nOp = pFrame->nOp;
59139   v->aMem = pFrame->aMem;
59140   v->nMem = pFrame->nMem;
59141   v->apCsr = pFrame->apCsr;
59142   v->nCursor = pFrame->nCursor;
59143   v->db->lastRowid = pFrame->lastRowid;
59144   v->nChange = pFrame->nChange;
59145   return pFrame->pc;
59146 }
59147
59148 /*
59149 ** Close all cursors.
59150 **
59151 ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory 
59152 ** cell array. This is necessary as the memory cell array may contain
59153 ** pointers to VdbeFrame objects, which may in turn contain pointers to
59154 ** open cursors.
59155 */
59156 static void closeAllCursors(Vdbe *p){
59157   if( p->pFrame ){
59158     VdbeFrame *pFrame;
59159     for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
59160     sqlite3VdbeFrameRestore(pFrame);
59161   }
59162   p->pFrame = 0;
59163   p->nFrame = 0;
59164
59165   if( p->apCsr ){
59166     int i;
59167     for(i=0; i<p->nCursor; i++){
59168       VdbeCursor *pC = p->apCsr[i];
59169       if( pC ){
59170         sqlite3VdbeFreeCursor(p, pC);
59171         p->apCsr[i] = 0;
59172       }
59173     }
59174   }
59175   if( p->aMem ){
59176     releaseMemArray(&p->aMem[1], p->nMem);
59177   }
59178   while( p->pDelFrame ){
59179     VdbeFrame *pDel = p->pDelFrame;
59180     p->pDelFrame = pDel->pParent;
59181     sqlite3VdbeFrameDelete(pDel);
59182   }
59183 }
59184
59185 /*
59186 ** Clean up the VM after execution.
59187 **
59188 ** This routine will automatically close any cursors, lists, and/or
59189 ** sorters that were left open.  It also deletes the values of
59190 ** variables in the aVar[] array.
59191 */
59192 static void Cleanup(Vdbe *p){
59193   sqlite3 *db = p->db;
59194
59195 #ifdef SQLITE_DEBUG
59196   /* Execute assert() statements to ensure that the Vdbe.apCsr[] and 
59197   ** Vdbe.aMem[] arrays have already been cleaned up.  */
59198   int i;
59199   for(i=0; i<p->nCursor; i++) assert( p->apCsr==0 || p->apCsr[i]==0 );
59200   for(i=1; i<=p->nMem; i++) assert( p->aMem==0 || p->aMem[i].flags==MEM_Null );
59201 #endif
59202
59203   sqlite3DbFree(db, p->zErrMsg);
59204   p->zErrMsg = 0;
59205   p->pResultSet = 0;
59206 }
59207
59208 /*
59209 ** Set the number of result columns that will be returned by this SQL
59210 ** statement. This is now set at compile time, rather than during
59211 ** execution of the vdbe program so that sqlite3_column_count() can
59212 ** be called on an SQL statement before sqlite3_step().
59213 */
59214 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
59215   Mem *pColName;
59216   int n;
59217   sqlite3 *db = p->db;
59218
59219   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
59220   sqlite3DbFree(db, p->aColName);
59221   n = nResColumn*COLNAME_N;
59222   p->nResColumn = (u16)nResColumn;
59223   p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
59224   if( p->aColName==0 ) return;
59225   while( n-- > 0 ){
59226     pColName->flags = MEM_Null;
59227     pColName->db = p->db;
59228     pColName++;
59229   }
59230 }
59231
59232 /*
59233 ** Set the name of the idx'th column to be returned by the SQL statement.
59234 ** zName must be a pointer to a nul terminated string.
59235 **
59236 ** This call must be made after a call to sqlite3VdbeSetNumCols().
59237 **
59238 ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
59239 ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
59240 ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
59241 */
59242 SQLITE_PRIVATE int sqlite3VdbeSetColName(
59243   Vdbe *p,                         /* Vdbe being configured */
59244   int idx,                         /* Index of column zName applies to */
59245   int var,                         /* One of the COLNAME_* constants */
59246   const char *zName,               /* Pointer to buffer containing name */
59247   void (*xDel)(void*)              /* Memory management strategy for zName */
59248 ){
59249   int rc;
59250   Mem *pColName;
59251   assert( idx<p->nResColumn );
59252   assert( var<COLNAME_N );
59253   if( p->db->mallocFailed ){
59254     assert( !zName || xDel!=SQLITE_DYNAMIC );
59255     return SQLITE_NOMEM;
59256   }
59257   assert( p->aColName!=0 );
59258   pColName = &(p->aColName[idx+var*p->nResColumn]);
59259   rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
59260   assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
59261   return rc;
59262 }
59263
59264 /*
59265 ** A read or write transaction may or may not be active on database handle
59266 ** db. If a transaction is active, commit it. If there is a
59267 ** write-transaction spanning more than one database file, this routine
59268 ** takes care of the master journal trickery.
59269 */
59270 static int vdbeCommit(sqlite3 *db, Vdbe *p){
59271   int i;
59272   int nTrans = 0;  /* Number of databases with an active write-transaction */
59273   int rc = SQLITE_OK;
59274   int needXcommit = 0;
59275
59276 #ifdef SQLITE_OMIT_VIRTUALTABLE
59277   /* With this option, sqlite3VtabSync() is defined to be simply 
59278   ** SQLITE_OK so p is not used. 
59279   */
59280   UNUSED_PARAMETER(p);
59281 #endif
59282
59283   /* Before doing anything else, call the xSync() callback for any
59284   ** virtual module tables written in this transaction. This has to
59285   ** be done before determining whether a master journal file is 
59286   ** required, as an xSync() callback may add an attached database
59287   ** to the transaction.
59288   */
59289   rc = sqlite3VtabSync(db, &p->zErrMsg);
59290
59291   /* This loop determines (a) if the commit hook should be invoked and
59292   ** (b) how many database files have open write transactions, not 
59293   ** including the temp database. (b) is important because if more than 
59294   ** one database file has an open write transaction, a master journal
59295   ** file is required for an atomic commit.
59296   */ 
59297   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
59298     Btree *pBt = db->aDb[i].pBt;
59299     if( sqlite3BtreeIsInTrans(pBt) ){
59300       needXcommit = 1;
59301       if( i!=1 ) nTrans++;
59302       rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
59303     }
59304   }
59305   if( rc!=SQLITE_OK ){
59306     return rc;
59307   }
59308
59309   /* If there are any write-transactions at all, invoke the commit hook */
59310   if( needXcommit && db->xCommitCallback ){
59311     rc = db->xCommitCallback(db->pCommitArg);
59312     if( rc ){
59313       return SQLITE_CONSTRAINT;
59314     }
59315   }
59316
59317   /* The simple case - no more than one database file (not counting the
59318   ** TEMP database) has a transaction active.   There is no need for the
59319   ** master-journal.
59320   **
59321   ** If the return value of sqlite3BtreeGetFilename() is a zero length
59322   ** string, it means the main database is :memory: or a temp file.  In 
59323   ** that case we do not support atomic multi-file commits, so use the 
59324   ** simple case then too.
59325   */
59326   if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
59327    || nTrans<=1
59328   ){
59329     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
59330       Btree *pBt = db->aDb[i].pBt;
59331       if( pBt ){
59332         rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
59333       }
59334     }
59335
59336     /* Do the commit only if all databases successfully complete phase 1. 
59337     ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
59338     ** IO error while deleting or truncating a journal file. It is unlikely,
59339     ** but could happen. In this case abandon processing and return the error.
59340     */
59341     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
59342       Btree *pBt = db->aDb[i].pBt;
59343       if( pBt ){
59344         rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
59345       }
59346     }
59347     if( rc==SQLITE_OK ){
59348       sqlite3VtabCommit(db);
59349     }
59350   }
59351
59352   /* The complex case - There is a multi-file write-transaction active.
59353   ** This requires a master journal file to ensure the transaction is
59354   ** committed atomicly.
59355   */
59356 #ifndef SQLITE_OMIT_DISKIO
59357   else{
59358     sqlite3_vfs *pVfs = db->pVfs;
59359     int needSync = 0;
59360     char *zMaster = 0;   /* File-name for the master journal */
59361     char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
59362     sqlite3_file *pMaster = 0;
59363     i64 offset = 0;
59364     int res;
59365
59366     /* Select a master journal file name */
59367     do {
59368       u32 iRandom;
59369       sqlite3DbFree(db, zMaster);
59370       sqlite3_randomness(sizeof(iRandom), &iRandom);
59371       zMaster = sqlite3MPrintf(db, "%s-mj%08X", zMainFile, iRandom&0x7fffffff);
59372       if( !zMaster ){
59373         return SQLITE_NOMEM;
59374       }
59375       sqlite3FileSuffix3(zMainFile, zMaster);
59376       rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
59377     }while( rc==SQLITE_OK && res );
59378     if( rc==SQLITE_OK ){
59379       /* Open the master journal. */
59380       rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster, 
59381           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
59382           SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
59383       );
59384     }
59385     if( rc!=SQLITE_OK ){
59386       sqlite3DbFree(db, zMaster);
59387       return rc;
59388     }
59389  
59390     /* Write the name of each database file in the transaction into the new
59391     ** master journal file. If an error occurs at this point close
59392     ** and delete the master journal file. All the individual journal files
59393     ** still have 'null' as the master journal pointer, so they will roll
59394     ** back independently if a failure occurs.
59395     */
59396     for(i=0; i<db->nDb; i++){
59397       Btree *pBt = db->aDb[i].pBt;
59398       if( sqlite3BtreeIsInTrans(pBt) ){
59399         char const *zFile = sqlite3BtreeGetJournalname(pBt);
59400         if( zFile==0 ){
59401           continue;  /* Ignore TEMP and :memory: databases */
59402         }
59403         assert( zFile[0]!=0 );
59404         if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
59405           needSync = 1;
59406         }
59407         rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
59408         offset += sqlite3Strlen30(zFile)+1;
59409         if( rc!=SQLITE_OK ){
59410           sqlite3OsCloseFree(pMaster);
59411           sqlite3OsDelete(pVfs, zMaster, 0);
59412           sqlite3DbFree(db, zMaster);
59413           return rc;
59414         }
59415       }
59416     }
59417
59418     /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
59419     ** flag is set this is not required.
59420     */
59421     if( needSync 
59422      && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
59423      && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
59424     ){
59425       sqlite3OsCloseFree(pMaster);
59426       sqlite3OsDelete(pVfs, zMaster, 0);
59427       sqlite3DbFree(db, zMaster);
59428       return rc;
59429     }
59430
59431     /* Sync all the db files involved in the transaction. The same call
59432     ** sets the master journal pointer in each individual journal. If
59433     ** an error occurs here, do not delete the master journal file.
59434     **
59435     ** If the error occurs during the first call to
59436     ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
59437     ** master journal file will be orphaned. But we cannot delete it,
59438     ** in case the master journal file name was written into the journal
59439     ** file before the failure occurred.
59440     */
59441     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
59442       Btree *pBt = db->aDb[i].pBt;
59443       if( pBt ){
59444         rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
59445       }
59446     }
59447     sqlite3OsCloseFree(pMaster);
59448     assert( rc!=SQLITE_BUSY );
59449     if( rc!=SQLITE_OK ){
59450       sqlite3DbFree(db, zMaster);
59451       return rc;
59452     }
59453
59454     /* Delete the master journal file. This commits the transaction. After
59455     ** doing this the directory is synced again before any individual
59456     ** transaction files are deleted.
59457     */
59458     rc = sqlite3OsDelete(pVfs, zMaster, 1);
59459     sqlite3DbFree(db, zMaster);
59460     zMaster = 0;
59461     if( rc ){
59462       return rc;
59463     }
59464
59465     /* All files and directories have already been synced, so the following
59466     ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
59467     ** deleting or truncating journals. If something goes wrong while
59468     ** this is happening we don't really care. The integrity of the
59469     ** transaction is already guaranteed, but some stray 'cold' journals
59470     ** may be lying around. Returning an error code won't help matters.
59471     */
59472     disable_simulated_io_errors();
59473     sqlite3BeginBenignMalloc();
59474     for(i=0; i<db->nDb; i++){ 
59475       Btree *pBt = db->aDb[i].pBt;
59476       if( pBt ){
59477         sqlite3BtreeCommitPhaseTwo(pBt, 1);
59478       }
59479     }
59480     sqlite3EndBenignMalloc();
59481     enable_simulated_io_errors();
59482
59483     sqlite3VtabCommit(db);
59484   }
59485 #endif
59486
59487   return rc;
59488 }
59489
59490 /* 
59491 ** This routine checks that the sqlite3.activeVdbeCnt count variable
59492 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
59493 ** currently active. An assertion fails if the two counts do not match.
59494 ** This is an internal self-check only - it is not an essential processing
59495 ** step.
59496 **
59497 ** This is a no-op if NDEBUG is defined.
59498 */
59499 #ifndef NDEBUG
59500 static void checkActiveVdbeCnt(sqlite3 *db){
59501   Vdbe *p;
59502   int cnt = 0;
59503   int nWrite = 0;
59504   p = db->pVdbe;
59505   while( p ){
59506     if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
59507       cnt++;
59508       if( p->readOnly==0 ) nWrite++;
59509     }
59510     p = p->pNext;
59511   }
59512   assert( cnt==db->activeVdbeCnt );
59513   assert( nWrite==db->writeVdbeCnt );
59514 }
59515 #else
59516 #define checkActiveVdbeCnt(x)
59517 #endif
59518
59519 /*
59520 ** For every Btree that in database connection db which 
59521 ** has been modified, "trip" or invalidate each cursor in
59522 ** that Btree might have been modified so that the cursor
59523 ** can never be used again.  This happens when a rollback
59524 *** occurs.  We have to trip all the other cursors, even
59525 ** cursor from other VMs in different database connections,
59526 ** so that none of them try to use the data at which they
59527 ** were pointing and which now may have been changed due
59528 ** to the rollback.
59529 **
59530 ** Remember that a rollback can delete tables complete and
59531 ** reorder rootpages.  So it is not sufficient just to save
59532 ** the state of the cursor.  We have to invalidate the cursor
59533 ** so that it is never used again.
59534 */
59535 static void invalidateCursorsOnModifiedBtrees(sqlite3 *db){
59536   int i;
59537   for(i=0; i<db->nDb; i++){
59538     Btree *p = db->aDb[i].pBt;
59539     if( p && sqlite3BtreeIsInTrans(p) ){
59540       sqlite3BtreeTripAllCursors(p, SQLITE_ABORT);
59541     }
59542   }
59543 }
59544
59545 /*
59546 ** If the Vdbe passed as the first argument opened a statement-transaction,
59547 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
59548 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
59549 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the 
59550 ** statement transaction is commtted.
59551 **
59552 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned. 
59553 ** Otherwise SQLITE_OK.
59554 */
59555 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
59556   sqlite3 *const db = p->db;
59557   int rc = SQLITE_OK;
59558
59559   /* If p->iStatement is greater than zero, then this Vdbe opened a 
59560   ** statement transaction that should be closed here. The only exception
59561   ** is that an IO error may have occured, causing an emergency rollback.
59562   ** In this case (db->nStatement==0), and there is nothing to do.
59563   */
59564   if( db->nStatement && p->iStatement ){
59565     int i;
59566     const int iSavepoint = p->iStatement-1;
59567
59568     assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
59569     assert( db->nStatement>0 );
59570     assert( p->iStatement==(db->nStatement+db->nSavepoint) );
59571
59572     for(i=0; i<db->nDb; i++){ 
59573       int rc2 = SQLITE_OK;
59574       Btree *pBt = db->aDb[i].pBt;
59575       if( pBt ){
59576         if( eOp==SAVEPOINT_ROLLBACK ){
59577           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
59578         }
59579         if( rc2==SQLITE_OK ){
59580           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
59581         }
59582         if( rc==SQLITE_OK ){
59583           rc = rc2;
59584         }
59585       }
59586     }
59587     db->nStatement--;
59588     p->iStatement = 0;
59589
59590     if( rc==SQLITE_OK ){
59591       if( eOp==SAVEPOINT_ROLLBACK ){
59592         rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
59593       }
59594       if( rc==SQLITE_OK ){
59595         rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
59596       }
59597     }
59598
59599     /* If the statement transaction is being rolled back, also restore the 
59600     ** database handles deferred constraint counter to the value it had when 
59601     ** the statement transaction was opened.  */
59602     if( eOp==SAVEPOINT_ROLLBACK ){
59603       db->nDeferredCons = p->nStmtDefCons;
59604     }
59605   }
59606   return rc;
59607 }
59608
59609 /*
59610 ** This function is called when a transaction opened by the database 
59611 ** handle associated with the VM passed as an argument is about to be 
59612 ** committed. If there are outstanding deferred foreign key constraint
59613 ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
59614 **
59615 ** If there are outstanding FK violations and this function returns 
59616 ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT and write
59617 ** an error message to it. Then return SQLITE_ERROR.
59618 */
59619 #ifndef SQLITE_OMIT_FOREIGN_KEY
59620 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
59621   sqlite3 *db = p->db;
59622   if( (deferred && db->nDeferredCons>0) || (!deferred && p->nFkConstraint>0) ){
59623     p->rc = SQLITE_CONSTRAINT;
59624     p->errorAction = OE_Abort;
59625     sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed");
59626     return SQLITE_ERROR;
59627   }
59628   return SQLITE_OK;
59629 }
59630 #endif
59631
59632 /*
59633 ** This routine is called the when a VDBE tries to halt.  If the VDBE
59634 ** has made changes and is in autocommit mode, then commit those
59635 ** changes.  If a rollback is needed, then do the rollback.
59636 **
59637 ** This routine is the only way to move the state of a VM from
59638 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
59639 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
59640 **
59641 ** Return an error code.  If the commit could not complete because of
59642 ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
59643 ** means the close did not happen and needs to be repeated.
59644 */
59645 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
59646   int rc;                         /* Used to store transient return codes */
59647   sqlite3 *db = p->db;
59648
59649   /* This function contains the logic that determines if a statement or
59650   ** transaction will be committed or rolled back as a result of the
59651   ** execution of this virtual machine. 
59652   **
59653   ** If any of the following errors occur:
59654   **
59655   **     SQLITE_NOMEM
59656   **     SQLITE_IOERR
59657   **     SQLITE_FULL
59658   **     SQLITE_INTERRUPT
59659   **
59660   ** Then the internal cache might have been left in an inconsistent
59661   ** state.  We need to rollback the statement transaction, if there is
59662   ** one, or the complete transaction if there is no statement transaction.
59663   */
59664
59665   if( p->db->mallocFailed ){
59666     p->rc = SQLITE_NOMEM;
59667   }
59668   closeAllCursors(p);
59669   if( p->magic!=VDBE_MAGIC_RUN ){
59670     return SQLITE_OK;
59671   }
59672   checkActiveVdbeCnt(db);
59673
59674   /* No commit or rollback needed if the program never started */
59675   if( p->pc>=0 ){
59676     int mrc;   /* Primary error code from p->rc */
59677     int eStatementOp = 0;
59678     int isSpecialError;            /* Set to true if a 'special' error */
59679
59680     /* Lock all btrees used by the statement */
59681     sqlite3VdbeEnter(p);
59682
59683     /* Check for one of the special errors */
59684     mrc = p->rc & 0xff;
59685     assert( p->rc!=SQLITE_IOERR_BLOCKED );  /* This error no longer exists */
59686     isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
59687                      || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
59688     if( isSpecialError ){
59689       /* If the query was read-only and the error code is SQLITE_INTERRUPT, 
59690       ** no rollback is necessary. Otherwise, at least a savepoint 
59691       ** transaction must be rolled back to restore the database to a 
59692       ** consistent state.
59693       **
59694       ** Even if the statement is read-only, it is important to perform
59695       ** a statement or transaction rollback operation. If the error 
59696       ** occured while writing to the journal, sub-journal or database
59697       ** file as part of an effort to free up cache space (see function
59698       ** pagerStress() in pager.c), the rollback is required to restore 
59699       ** the pager to a consistent state.
59700       */
59701       if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
59702         if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
59703           eStatementOp = SAVEPOINT_ROLLBACK;
59704         }else{
59705           /* We are forced to roll back the active transaction. Before doing
59706           ** so, abort any other statements this handle currently has active.
59707           */
59708           invalidateCursorsOnModifiedBtrees(db);
59709           sqlite3RollbackAll(db);
59710           sqlite3CloseSavepoints(db);
59711           db->autoCommit = 1;
59712         }
59713       }
59714     }
59715
59716     /* Check for immediate foreign key violations. */
59717     if( p->rc==SQLITE_OK ){
59718       sqlite3VdbeCheckFk(p, 0);
59719     }
59720   
59721     /* If the auto-commit flag is set and this is the only active writer 
59722     ** VM, then we do either a commit or rollback of the current transaction. 
59723     **
59724     ** Note: This block also runs if one of the special errors handled 
59725     ** above has occurred. 
59726     */
59727     if( !sqlite3VtabInSync(db) 
59728      && db->autoCommit 
59729      && db->writeVdbeCnt==(p->readOnly==0) 
59730     ){
59731       if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
59732         rc = sqlite3VdbeCheckFk(p, 1);
59733         if( rc!=SQLITE_OK ){
59734           if( NEVER(p->readOnly) ){
59735             sqlite3VdbeLeave(p);
59736             return SQLITE_ERROR;
59737           }
59738           rc = SQLITE_CONSTRAINT;
59739         }else{ 
59740           /* The auto-commit flag is true, the vdbe program was successful 
59741           ** or hit an 'OR FAIL' constraint and there are no deferred foreign
59742           ** key constraints to hold up the transaction. This means a commit 
59743           ** is required. */
59744           rc = vdbeCommit(db, p);
59745         }
59746         if( rc==SQLITE_BUSY && p->readOnly ){
59747           sqlite3VdbeLeave(p);
59748           return SQLITE_BUSY;
59749         }else if( rc!=SQLITE_OK ){
59750           p->rc = rc;
59751           sqlite3RollbackAll(db);
59752         }else{
59753           db->nDeferredCons = 0;
59754           sqlite3CommitInternalChanges(db);
59755         }
59756       }else{
59757         sqlite3RollbackAll(db);
59758       }
59759       db->nStatement = 0;
59760     }else if( eStatementOp==0 ){
59761       if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
59762         eStatementOp = SAVEPOINT_RELEASE;
59763       }else if( p->errorAction==OE_Abort ){
59764         eStatementOp = SAVEPOINT_ROLLBACK;
59765       }else{
59766         invalidateCursorsOnModifiedBtrees(db);
59767         sqlite3RollbackAll(db);
59768         sqlite3CloseSavepoints(db);
59769         db->autoCommit = 1;
59770       }
59771     }
59772   
59773     /* If eStatementOp is non-zero, then a statement transaction needs to
59774     ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
59775     ** do so. If this operation returns an error, and the current statement
59776     ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
59777     ** current statement error code.
59778     */
59779     if( eStatementOp ){
59780       rc = sqlite3VdbeCloseStatement(p, eStatementOp);
59781       if( rc ){
59782         if( p->rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT ){
59783           p->rc = rc;
59784           sqlite3DbFree(db, p->zErrMsg);
59785           p->zErrMsg = 0;
59786         }
59787         invalidateCursorsOnModifiedBtrees(db);
59788         sqlite3RollbackAll(db);
59789         sqlite3CloseSavepoints(db);
59790         db->autoCommit = 1;
59791       }
59792     }
59793   
59794     /* If this was an INSERT, UPDATE or DELETE and no statement transaction
59795     ** has been rolled back, update the database connection change-counter. 
59796     */
59797     if( p->changeCntOn ){
59798       if( eStatementOp!=SAVEPOINT_ROLLBACK ){
59799         sqlite3VdbeSetChanges(db, p->nChange);
59800       }else{
59801         sqlite3VdbeSetChanges(db, 0);
59802       }
59803       p->nChange = 0;
59804     }
59805   
59806     /* Rollback or commit any schema changes that occurred. */
59807     if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
59808       sqlite3ResetInternalSchema(db, -1);
59809       db->flags = (db->flags | SQLITE_InternChanges);
59810     }
59811
59812     /* Release the locks */
59813     sqlite3VdbeLeave(p);
59814   }
59815
59816   /* We have successfully halted and closed the VM.  Record this fact. */
59817   if( p->pc>=0 ){
59818     db->activeVdbeCnt--;
59819     if( !p->readOnly ){
59820       db->writeVdbeCnt--;
59821     }
59822     assert( db->activeVdbeCnt>=db->writeVdbeCnt );
59823   }
59824   p->magic = VDBE_MAGIC_HALT;
59825   checkActiveVdbeCnt(db);
59826   if( p->db->mallocFailed ){
59827     p->rc = SQLITE_NOMEM;
59828   }
59829
59830   /* If the auto-commit flag is set to true, then any locks that were held
59831   ** by connection db have now been released. Call sqlite3ConnectionUnlocked() 
59832   ** to invoke any required unlock-notify callbacks.
59833   */
59834   if( db->autoCommit ){
59835     sqlite3ConnectionUnlocked(db);
59836   }
59837
59838   assert( db->activeVdbeCnt>0 || db->autoCommit==0 || db->nStatement==0 );
59839   return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
59840 }
59841
59842
59843 /*
59844 ** Each VDBE holds the result of the most recent sqlite3_step() call
59845 ** in p->rc.  This routine sets that result back to SQLITE_OK.
59846 */
59847 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
59848   p->rc = SQLITE_OK;
59849 }
59850
59851 /*
59852 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
59853 ** Write any error messages into *pzErrMsg.  Return the result code.
59854 **
59855 ** After this routine is run, the VDBE should be ready to be executed
59856 ** again.
59857 **
59858 ** To look at it another way, this routine resets the state of the
59859 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
59860 ** VDBE_MAGIC_INIT.
59861 */
59862 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
59863   sqlite3 *db;
59864   db = p->db;
59865
59866   /* If the VM did not run to completion or if it encountered an
59867   ** error, then it might not have been halted properly.  So halt
59868   ** it now.
59869   */
59870   sqlite3VdbeHalt(p);
59871
59872   /* If the VDBE has be run even partially, then transfer the error code
59873   ** and error message from the VDBE into the main database structure.  But
59874   ** if the VDBE has just been set to run but has not actually executed any
59875   ** instructions yet, leave the main database error information unchanged.
59876   */
59877   if( p->pc>=0 ){
59878     if( p->zErrMsg ){
59879       sqlite3BeginBenignMalloc();
59880       sqlite3ValueSetStr(db->pErr,-1,p->zErrMsg,SQLITE_UTF8,SQLITE_TRANSIENT);
59881       sqlite3EndBenignMalloc();
59882       db->errCode = p->rc;
59883       sqlite3DbFree(db, p->zErrMsg);
59884       p->zErrMsg = 0;
59885     }else if( p->rc ){
59886       sqlite3Error(db, p->rc, 0);
59887     }else{
59888       sqlite3Error(db, SQLITE_OK, 0);
59889     }
59890     if( p->runOnlyOnce ) p->expired = 1;
59891   }else if( p->rc && p->expired ){
59892     /* The expired flag was set on the VDBE before the first call
59893     ** to sqlite3_step(). For consistency (since sqlite3_step() was
59894     ** called), set the database error in this case as well.
59895     */
59896     sqlite3Error(db, p->rc, 0);
59897     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
59898     sqlite3DbFree(db, p->zErrMsg);
59899     p->zErrMsg = 0;
59900   }
59901
59902   /* Reclaim all memory used by the VDBE
59903   */
59904   Cleanup(p);
59905
59906   /* Save profiling information from this VDBE run.
59907   */
59908 #ifdef VDBE_PROFILE
59909   {
59910     FILE *out = fopen("vdbe_profile.out", "a");
59911     if( out ){
59912       int i;
59913       fprintf(out, "---- ");
59914       for(i=0; i<p->nOp; i++){
59915         fprintf(out, "%02x", p->aOp[i].opcode);
59916       }
59917       fprintf(out, "\n");
59918       for(i=0; i<p->nOp; i++){
59919         fprintf(out, "%6d %10lld %8lld ",
59920            p->aOp[i].cnt,
59921            p->aOp[i].cycles,
59922            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
59923         );
59924         sqlite3VdbePrintOp(out, i, &p->aOp[i]);
59925       }
59926       fclose(out);
59927     }
59928   }
59929 #endif
59930   p->magic = VDBE_MAGIC_INIT;
59931   return p->rc & db->errMask;
59932 }
59933  
59934 /*
59935 ** Clean up and delete a VDBE after execution.  Return an integer which is
59936 ** the result code.  Write any error message text into *pzErrMsg.
59937 */
59938 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
59939   int rc = SQLITE_OK;
59940   if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
59941     rc = sqlite3VdbeReset(p);
59942     assert( (rc & p->db->errMask)==rc );
59943   }
59944   sqlite3VdbeDelete(p);
59945   return rc;
59946 }
59947
59948 /*
59949 ** Call the destructor for each auxdata entry in pVdbeFunc for which
59950 ** the corresponding bit in mask is clear.  Auxdata entries beyond 31
59951 ** are always destroyed.  To destroy all auxdata entries, call this
59952 ** routine with mask==0.
59953 */
59954 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
59955   int i;
59956   for(i=0; i<pVdbeFunc->nAux; i++){
59957     struct AuxData *pAux = &pVdbeFunc->apAux[i];
59958     if( (i>31 || !(mask&(((u32)1)<<i))) && pAux->pAux ){
59959       if( pAux->xDelete ){
59960         pAux->xDelete(pAux->pAux);
59961       }
59962       pAux->pAux = 0;
59963     }
59964   }
59965 }
59966
59967 /*
59968 ** Free all memory associated with the Vdbe passed as the second argument.
59969 ** The difference between this function and sqlite3VdbeDelete() is that
59970 ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
59971 ** the database connection.
59972 */
59973 SQLITE_PRIVATE void sqlite3VdbeDeleteObject(sqlite3 *db, Vdbe *p){
59974   SubProgram *pSub, *pNext;
59975   int i;
59976   assert( p->db==0 || p->db==db );
59977   releaseMemArray(p->aVar, p->nVar);
59978   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
59979   for(pSub=p->pProgram; pSub; pSub=pNext){
59980     pNext = pSub->pNext;
59981     vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
59982     sqlite3DbFree(db, pSub);
59983   }
59984   for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
59985   vdbeFreeOpArray(db, p->aOp, p->nOp);
59986   sqlite3DbFree(db, p->aLabel);
59987   sqlite3DbFree(db, p->aColName);
59988   sqlite3DbFree(db, p->zSql);
59989   sqlite3DbFree(db, p->pFree);
59990   sqlite3DbFree(db, p);
59991 }
59992
59993 /*
59994 ** Delete an entire VDBE.
59995 */
59996 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
59997   sqlite3 *db;
59998
59999   if( NEVER(p==0) ) return;
60000   db = p->db;
60001   if( p->pPrev ){
60002     p->pPrev->pNext = p->pNext;
60003   }else{
60004     assert( db->pVdbe==p );
60005     db->pVdbe = p->pNext;
60006   }
60007   if( p->pNext ){
60008     p->pNext->pPrev = p->pPrev;
60009   }
60010   p->magic = VDBE_MAGIC_DEAD;
60011   p->db = 0;
60012   sqlite3VdbeDeleteObject(db, p);
60013 }
60014
60015 /*
60016 ** Make sure the cursor p is ready to read or write the row to which it
60017 ** was last positioned.  Return an error code if an OOM fault or I/O error
60018 ** prevents us from positioning the cursor to its correct position.
60019 **
60020 ** If a MoveTo operation is pending on the given cursor, then do that
60021 ** MoveTo now.  If no move is pending, check to see if the row has been
60022 ** deleted out from under the cursor and if it has, mark the row as
60023 ** a NULL row.
60024 **
60025 ** If the cursor is already pointing to the correct row and that row has
60026 ** not been deleted out from under the cursor, then this routine is a no-op.
60027 */
60028 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
60029   if( p->deferredMoveto ){
60030     int res, rc;
60031 #ifdef SQLITE_TEST
60032     extern int sqlite3_search_count;
60033 #endif
60034     assert( p->isTable );
60035     rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
60036     if( rc ) return rc;
60037     p->lastRowid = p->movetoTarget;
60038     if( res!=0 ) return SQLITE_CORRUPT_BKPT;
60039     p->rowidIsValid = 1;
60040 #ifdef SQLITE_TEST
60041     sqlite3_search_count++;
60042 #endif
60043     p->deferredMoveto = 0;
60044     p->cacheStatus = CACHE_STALE;
60045   }else if( ALWAYS(p->pCursor) ){
60046     int hasMoved;
60047     int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
60048     if( rc ) return rc;
60049     if( hasMoved ){
60050       p->cacheStatus = CACHE_STALE;
60051       p->nullRow = 1;
60052     }
60053   }
60054   return SQLITE_OK;
60055 }
60056
60057 /*
60058 ** The following functions:
60059 **
60060 ** sqlite3VdbeSerialType()
60061 ** sqlite3VdbeSerialTypeLen()
60062 ** sqlite3VdbeSerialLen()
60063 ** sqlite3VdbeSerialPut()
60064 ** sqlite3VdbeSerialGet()
60065 **
60066 ** encapsulate the code that serializes values for storage in SQLite
60067 ** data and index records. Each serialized value consists of a
60068 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
60069 ** integer, stored as a varint.
60070 **
60071 ** In an SQLite index record, the serial type is stored directly before
60072 ** the blob of data that it corresponds to. In a table record, all serial
60073 ** types are stored at the start of the record, and the blobs of data at
60074 ** the end. Hence these functions allow the caller to handle the
60075 ** serial-type and data blob seperately.
60076 **
60077 ** The following table describes the various storage classes for data:
60078 **
60079 **   serial type        bytes of data      type
60080 **   --------------     ---------------    ---------------
60081 **      0                     0            NULL
60082 **      1                     1            signed integer
60083 **      2                     2            signed integer
60084 **      3                     3            signed integer
60085 **      4                     4            signed integer
60086 **      5                     6            signed integer
60087 **      6                     8            signed integer
60088 **      7                     8            IEEE float
60089 **      8                     0            Integer constant 0
60090 **      9                     0            Integer constant 1
60091 **     10,11                               reserved for expansion
60092 **    N>=12 and even       (N-12)/2        BLOB
60093 **    N>=13 and odd        (N-13)/2        text
60094 **
60095 ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
60096 ** of SQLite will not understand those serial types.
60097 */
60098
60099 /*
60100 ** Return the serial-type for the value stored in pMem.
60101 */
60102 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
60103   int flags = pMem->flags;
60104   int n;
60105
60106   if( flags&MEM_Null ){
60107     return 0;
60108   }
60109   if( flags&MEM_Int ){
60110     /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
60111 #   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
60112     i64 i = pMem->u.i;
60113     u64 u;
60114     if( file_format>=4 && (i&1)==i ){
60115       return 8+(u32)i;
60116     }
60117     if( i<0 ){
60118       if( i<(-MAX_6BYTE) ) return 6;
60119       /* Previous test prevents:  u = -(-9223372036854775808) */
60120       u = -i;
60121     }else{
60122       u = i;
60123     }
60124     if( u<=127 ) return 1;
60125     if( u<=32767 ) return 2;
60126     if( u<=8388607 ) return 3;
60127     if( u<=2147483647 ) return 4;
60128     if( u<=MAX_6BYTE ) return 5;
60129     return 6;
60130   }
60131   if( flags&MEM_Real ){
60132     return 7;
60133   }
60134   assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
60135   n = pMem->n;
60136   if( flags & MEM_Zero ){
60137     n += pMem->u.nZero;
60138   }
60139   assert( n>=0 );
60140   return ((n*2) + 12 + ((flags&MEM_Str)!=0));
60141 }
60142
60143 /*
60144 ** Return the length of the data corresponding to the supplied serial-type.
60145 */
60146 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
60147   if( serial_type>=12 ){
60148     return (serial_type-12)/2;
60149   }else{
60150     static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
60151     return aSize[serial_type];
60152   }
60153 }
60154
60155 /*
60156 ** If we are on an architecture with mixed-endian floating 
60157 ** points (ex: ARM7) then swap the lower 4 bytes with the 
60158 ** upper 4 bytes.  Return the result.
60159 **
60160 ** For most architectures, this is a no-op.
60161 **
60162 ** (later):  It is reported to me that the mixed-endian problem
60163 ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
60164 ** that early versions of GCC stored the two words of a 64-bit
60165 ** float in the wrong order.  And that error has been propagated
60166 ** ever since.  The blame is not necessarily with GCC, though.
60167 ** GCC might have just copying the problem from a prior compiler.
60168 ** I am also told that newer versions of GCC that follow a different
60169 ** ABI get the byte order right.
60170 **
60171 ** Developers using SQLite on an ARM7 should compile and run their
60172 ** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
60173 ** enabled, some asserts below will ensure that the byte order of
60174 ** floating point values is correct.
60175 **
60176 ** (2007-08-30)  Frank van Vugt has studied this problem closely
60177 ** and has send his findings to the SQLite developers.  Frank
60178 ** writes that some Linux kernels offer floating point hardware
60179 ** emulation that uses only 32-bit mantissas instead of a full 
60180 ** 48-bits as required by the IEEE standard.  (This is the
60181 ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
60182 ** byte swapping becomes very complicated.  To avoid problems,
60183 ** the necessary byte swapping is carried out using a 64-bit integer
60184 ** rather than a 64-bit float.  Frank assures us that the code here
60185 ** works for him.  We, the developers, have no way to independently
60186 ** verify this, but Frank seems to know what he is talking about
60187 ** so we trust him.
60188 */
60189 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
60190 static u64 floatSwap(u64 in){
60191   union {
60192     u64 r;
60193     u32 i[2];
60194   } u;
60195   u32 t;
60196
60197   u.r = in;
60198   t = u.i[0];
60199   u.i[0] = u.i[1];
60200   u.i[1] = t;
60201   return u.r;
60202 }
60203 # define swapMixedEndianFloat(X)  X = floatSwap(X)
60204 #else
60205 # define swapMixedEndianFloat(X)
60206 #endif
60207
60208 /*
60209 ** Write the serialized data blob for the value stored in pMem into 
60210 ** buf. It is assumed that the caller has allocated sufficient space.
60211 ** Return the number of bytes written.
60212 **
60213 ** nBuf is the amount of space left in buf[].  nBuf must always be
60214 ** large enough to hold the entire field.  Except, if the field is
60215 ** a blob with a zero-filled tail, then buf[] might be just the right
60216 ** size to hold everything except for the zero-filled tail.  If buf[]
60217 ** is only big enough to hold the non-zero prefix, then only write that
60218 ** prefix into buf[].  But if buf[] is large enough to hold both the
60219 ** prefix and the tail then write the prefix and set the tail to all
60220 ** zeros.
60221 **
60222 ** Return the number of bytes actually written into buf[].  The number
60223 ** of bytes in the zero-filled tail is included in the return value only
60224 ** if those bytes were zeroed in buf[].
60225 */ 
60226 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
60227   u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
60228   u32 len;
60229
60230   /* Integer and Real */
60231   if( serial_type<=7 && serial_type>0 ){
60232     u64 v;
60233     u32 i;
60234     if( serial_type==7 ){
60235       assert( sizeof(v)==sizeof(pMem->r) );
60236       memcpy(&v, &pMem->r, sizeof(v));
60237       swapMixedEndianFloat(v);
60238     }else{
60239       v = pMem->u.i;
60240     }
60241     len = i = sqlite3VdbeSerialTypeLen(serial_type);
60242     assert( len<=(u32)nBuf );
60243     while( i-- ){
60244       buf[i] = (u8)(v&0xFF);
60245       v >>= 8;
60246     }
60247     return len;
60248   }
60249
60250   /* String or blob */
60251   if( serial_type>=12 ){
60252     assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
60253              == (int)sqlite3VdbeSerialTypeLen(serial_type) );
60254     assert( pMem->n<=nBuf );
60255     len = pMem->n;
60256     memcpy(buf, pMem->z, len);
60257     if( pMem->flags & MEM_Zero ){
60258       len += pMem->u.nZero;
60259       assert( nBuf>=0 );
60260       if( len > (u32)nBuf ){
60261         len = (u32)nBuf;
60262       }
60263       memset(&buf[pMem->n], 0, len-pMem->n);
60264     }
60265     return len;
60266   }
60267
60268   /* NULL or constants 0 or 1 */
60269   return 0;
60270 }
60271
60272 /*
60273 ** Deserialize the data blob pointed to by buf as serial type serial_type
60274 ** and store the result in pMem.  Return the number of bytes read.
60275 */ 
60276 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
60277   const unsigned char *buf,     /* Buffer to deserialize from */
60278   u32 serial_type,              /* Serial type to deserialize */
60279   Mem *pMem                     /* Memory cell to write value into */
60280 ){
60281   switch( serial_type ){
60282     case 10:   /* Reserved for future use */
60283     case 11:   /* Reserved for future use */
60284     case 0: {  /* NULL */
60285       pMem->flags = MEM_Null;
60286       break;
60287     }
60288     case 1: { /* 1-byte signed integer */
60289       pMem->u.i = (signed char)buf[0];
60290       pMem->flags = MEM_Int;
60291       return 1;
60292     }
60293     case 2: { /* 2-byte signed integer */
60294       pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
60295       pMem->flags = MEM_Int;
60296       return 2;
60297     }
60298     case 3: { /* 3-byte signed integer */
60299       pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
60300       pMem->flags = MEM_Int;
60301       return 3;
60302     }
60303     case 4: { /* 4-byte signed integer */
60304       pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
60305       pMem->flags = MEM_Int;
60306       return 4;
60307     }
60308     case 5: { /* 6-byte signed integer */
60309       u64 x = (((signed char)buf[0])<<8) | buf[1];
60310       u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
60311       x = (x<<32) | y;
60312       pMem->u.i = *(i64*)&x;
60313       pMem->flags = MEM_Int;
60314       return 6;
60315     }
60316     case 6:   /* 8-byte signed integer */
60317     case 7: { /* IEEE floating point */
60318       u64 x;
60319       u32 y;
60320 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
60321       /* Verify that integers and floating point values use the same
60322       ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
60323       ** defined that 64-bit floating point values really are mixed
60324       ** endian.
60325       */
60326       static const u64 t1 = ((u64)0x3ff00000)<<32;
60327       static const double r1 = 1.0;
60328       u64 t2 = t1;
60329       swapMixedEndianFloat(t2);
60330       assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
60331 #endif
60332
60333       x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
60334       y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
60335       x = (x<<32) | y;
60336       if( serial_type==6 ){
60337         pMem->u.i = *(i64*)&x;
60338         pMem->flags = MEM_Int;
60339       }else{
60340         assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
60341         swapMixedEndianFloat(x);
60342         memcpy(&pMem->r, &x, sizeof(x));
60343         pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
60344       }
60345       return 8;
60346     }
60347     case 8:    /* Integer 0 */
60348     case 9: {  /* Integer 1 */
60349       pMem->u.i = serial_type-8;
60350       pMem->flags = MEM_Int;
60351       return 0;
60352     }
60353     default: {
60354       u32 len = (serial_type-12)/2;
60355       pMem->z = (char *)buf;
60356       pMem->n = len;
60357       pMem->xDel = 0;
60358       if( serial_type&0x01 ){
60359         pMem->flags = MEM_Str | MEM_Ephem;
60360       }else{
60361         pMem->flags = MEM_Blob | MEM_Ephem;
60362       }
60363       return len;
60364     }
60365   }
60366   return 0;
60367 }
60368
60369
60370 /*
60371 ** Given the nKey-byte encoding of a record in pKey[], parse the
60372 ** record into a UnpackedRecord structure.  Return a pointer to
60373 ** that structure.
60374 **
60375 ** The calling function might provide szSpace bytes of memory
60376 ** space at pSpace.  This space can be used to hold the returned
60377 ** VDbeParsedRecord structure if it is large enough.  If it is
60378 ** not big enough, space is obtained from sqlite3_malloc().
60379 **
60380 ** The returned structure should be closed by a call to
60381 ** sqlite3VdbeDeleteUnpackedRecord().
60382 */ 
60383 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(
60384   KeyInfo *pKeyInfo,     /* Information about the record format */
60385   int nKey,              /* Size of the binary record */
60386   const void *pKey,      /* The binary record */
60387   char *pSpace,          /* Unaligned space available to hold the object */
60388   int szSpace            /* Size of pSpace[] in bytes */
60389 ){
60390   const unsigned char *aKey = (const unsigned char *)pKey;
60391   UnpackedRecord *p;  /* The unpacked record that we will return */
60392   int nByte;          /* Memory space needed to hold p, in bytes */
60393   int d;
60394   u32 idx;
60395   u16 u;              /* Unsigned loop counter */
60396   u32 szHdr;
60397   Mem *pMem;
60398   int nOff;           /* Increase pSpace by this much to 8-byte align it */
60399   
60400   /*
60401   ** We want to shift the pointer pSpace up such that it is 8-byte aligned.
60402   ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift 
60403   ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
60404   */
60405   nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
60406   pSpace += nOff;
60407   szSpace -= nOff;
60408   nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
60409   if( nByte>szSpace ){
60410     p = sqlite3DbMallocRaw(pKeyInfo->db, nByte);
60411     if( p==0 ) return 0;
60412     p->flags = UNPACKED_NEED_FREE | UNPACKED_NEED_DESTROY;
60413   }else{
60414     p = (UnpackedRecord*)pSpace;
60415     p->flags = UNPACKED_NEED_DESTROY;
60416   }
60417   p->pKeyInfo = pKeyInfo;
60418   p->nField = pKeyInfo->nField + 1;
60419   p->aMem = pMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
60420   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
60421   idx = getVarint32(aKey, szHdr);
60422   d = szHdr;
60423   u = 0;
60424   while( idx<szHdr && u<p->nField && d<=nKey ){
60425     u32 serial_type;
60426
60427     idx += getVarint32(&aKey[idx], serial_type);
60428     pMem->enc = pKeyInfo->enc;
60429     pMem->db = pKeyInfo->db;
60430     /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
60431     pMem->zMalloc = 0;
60432     d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
60433     pMem++;
60434     u++;
60435   }
60436   assert( u<=pKeyInfo->nField + 1 );
60437   p->nField = u;
60438   return (void*)p;
60439 }
60440
60441 /*
60442 ** This routine destroys a UnpackedRecord object.
60443 */
60444 SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord *p){
60445 #ifdef SQLITE_DEBUG
60446   int i;
60447   Mem *pMem;
60448
60449   assert( p!=0 );
60450   assert( p->flags & UNPACKED_NEED_DESTROY );
60451   for(i=0, pMem=p->aMem; i<p->nField; i++, pMem++){
60452     /* The unpacked record is always constructed by the
60453     ** sqlite3VdbeUnpackRecord() function above, which makes all
60454     ** strings and blobs static.  And none of the elements are
60455     ** ever transformed, so there is never anything to delete.
60456     */
60457     if( NEVER(pMem->zMalloc) ) sqlite3VdbeMemRelease(pMem);
60458   }
60459 #endif
60460   if( p->flags & UNPACKED_NEED_FREE ){
60461     sqlite3DbFree(p->pKeyInfo->db, p);
60462   }
60463 }
60464
60465 /*
60466 ** This function compares the two table rows or index records
60467 ** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
60468 ** or positive integer if key1 is less than, equal to or 
60469 ** greater than key2.  The {nKey1, pKey1} key must be a blob
60470 ** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
60471 ** key must be a parsed key such as obtained from
60472 ** sqlite3VdbeParseRecord.
60473 **
60474 ** Key1 and Key2 do not have to contain the same number of fields.
60475 ** The key with fewer fields is usually compares less than the 
60476 ** longer key.  However if the UNPACKED_INCRKEY flags in pPKey2 is set
60477 ** and the common prefixes are equal, then key1 is less than key2.
60478 ** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
60479 ** equal, then the keys are considered to be equal and
60480 ** the parts beyond the common prefix are ignored.
60481 **
60482 ** If the UNPACKED_IGNORE_ROWID flag is set, then the last byte of
60483 ** the header of pKey1 is ignored.  It is assumed that pKey1 is
60484 ** an index key, and thus ends with a rowid value.  The last byte
60485 ** of the header will therefore be the serial type of the rowid:
60486 ** one of 1, 2, 3, 4, 5, 6, 8, or 9 - the integer serial types.
60487 ** The serial type of the final rowid will always be a single byte.
60488 ** By ignoring this last byte of the header, we force the comparison
60489 ** to ignore the rowid at the end of key1.
60490 */
60491 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
60492   int nKey1, const void *pKey1, /* Left key */
60493   UnpackedRecord *pPKey2        /* Right key */
60494 ){
60495   int d1;            /* Offset into aKey[] of next data element */
60496   u32 idx1;          /* Offset into aKey[] of next header element */
60497   u32 szHdr1;        /* Number of bytes in header */
60498   int i = 0;
60499   int nField;
60500   int rc = 0;
60501   const unsigned char *aKey1 = (const unsigned char *)pKey1;
60502   KeyInfo *pKeyInfo;
60503   Mem mem1;
60504
60505   pKeyInfo = pPKey2->pKeyInfo;
60506   mem1.enc = pKeyInfo->enc;
60507   mem1.db = pKeyInfo->db;
60508   /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
60509   VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
60510
60511   /* Compilers may complain that mem1.u.i is potentially uninitialized.
60512   ** We could initialize it, as shown here, to silence those complaints.
60513   ** But in fact, mem1.u.i will never actually be used uninitialized, and doing 
60514   ** the unnecessary initialization has a measurable negative performance
60515   ** impact, since this routine is a very high runner.  And so, we choose
60516   ** to ignore the compiler warnings and leave this variable uninitialized.
60517   */
60518   /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
60519   
60520   idx1 = getVarint32(aKey1, szHdr1);
60521   d1 = szHdr1;
60522   if( pPKey2->flags & UNPACKED_IGNORE_ROWID ){
60523     szHdr1--;
60524   }
60525   nField = pKeyInfo->nField;
60526   while( idx1<szHdr1 && i<pPKey2->nField ){
60527     u32 serial_type1;
60528
60529     /* Read the serial types for the next element in each key. */
60530     idx1 += getVarint32( aKey1+idx1, serial_type1 );
60531     if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
60532
60533     /* Extract the values to be compared.
60534     */
60535     d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
60536
60537     /* Do the comparison
60538     */
60539     rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
60540                            i<nField ? pKeyInfo->aColl[i] : 0);
60541     if( rc!=0 ){
60542       assert( mem1.zMalloc==0 );  /* See comment below */
60543
60544       /* Invert the result if we are using DESC sort order. */
60545       if( pKeyInfo->aSortOrder && i<nField && pKeyInfo->aSortOrder[i] ){
60546         rc = -rc;
60547       }
60548     
60549       /* If the PREFIX_SEARCH flag is set and all fields except the final
60550       ** rowid field were equal, then clear the PREFIX_SEARCH flag and set 
60551       ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
60552       ** This is used by the OP_IsUnique opcode.
60553       */
60554       if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
60555         assert( idx1==szHdr1 && rc );
60556         assert( mem1.flags & MEM_Int );
60557         pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
60558         pPKey2->rowid = mem1.u.i;
60559       }
60560     
60561       return rc;
60562     }
60563     i++;
60564   }
60565
60566   /* No memory allocation is ever used on mem1.  Prove this using
60567   ** the following assert().  If the assert() fails, it indicates a
60568   ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
60569   */
60570   assert( mem1.zMalloc==0 );
60571
60572   /* rc==0 here means that one of the keys ran out of fields and
60573   ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
60574   ** flag is set, then break the tie by treating key2 as larger.
60575   ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
60576   ** are considered to be equal.  Otherwise, the longer key is the 
60577   ** larger.  As it happens, the pPKey2 will always be the longer
60578   ** if there is a difference.
60579   */
60580   assert( rc==0 );
60581   if( pPKey2->flags & UNPACKED_INCRKEY ){
60582     rc = -1;
60583   }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
60584     /* Leave rc==0 */
60585   }else if( idx1<szHdr1 ){
60586     rc = 1;
60587   }
60588   return rc;
60589 }
60590  
60591
60592 /*
60593 ** pCur points at an index entry created using the OP_MakeRecord opcode.
60594 ** Read the rowid (the last field in the record) and store it in *rowid.
60595 ** Return SQLITE_OK if everything works, or an error code otherwise.
60596 **
60597 ** pCur might be pointing to text obtained from a corrupt database file.
60598 ** So the content cannot be trusted.  Do appropriate checks on the content.
60599 */
60600 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
60601   i64 nCellKey = 0;
60602   int rc;
60603   u32 szHdr;        /* Size of the header */
60604   u32 typeRowid;    /* Serial type of the rowid */
60605   u32 lenRowid;     /* Size of the rowid */
60606   Mem m, v;
60607
60608   UNUSED_PARAMETER(db);
60609
60610   /* Get the size of the index entry.  Only indices entries of less
60611   ** than 2GiB are support - anything large must be database corruption.
60612   ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
60613   ** this code can safely assume that nCellKey is 32-bits  
60614   */
60615   assert( sqlite3BtreeCursorIsValid(pCur) );
60616   rc = sqlite3BtreeKeySize(pCur, &nCellKey);
60617   assert( rc==SQLITE_OK );     /* pCur is always valid so KeySize cannot fail */
60618   assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
60619
60620   /* Read in the complete content of the index entry */
60621   memset(&m, 0, sizeof(m));
60622   rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
60623   if( rc ){
60624     return rc;
60625   }
60626
60627   /* The index entry must begin with a header size */
60628   (void)getVarint32((u8*)m.z, szHdr);
60629   testcase( szHdr==3 );
60630   testcase( szHdr==m.n );
60631   if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
60632     goto idx_rowid_corruption;
60633   }
60634
60635   /* The last field of the index should be an integer - the ROWID.
60636   ** Verify that the last entry really is an integer. */
60637   (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
60638   testcase( typeRowid==1 );
60639   testcase( typeRowid==2 );
60640   testcase( typeRowid==3 );
60641   testcase( typeRowid==4 );
60642   testcase( typeRowid==5 );
60643   testcase( typeRowid==6 );
60644   testcase( typeRowid==8 );
60645   testcase( typeRowid==9 );
60646   if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
60647     goto idx_rowid_corruption;
60648   }
60649   lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
60650   testcase( (u32)m.n==szHdr+lenRowid );
60651   if( unlikely((u32)m.n<szHdr+lenRowid) ){
60652     goto idx_rowid_corruption;
60653   }
60654
60655   /* Fetch the integer off the end of the index record */
60656   sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
60657   *rowid = v.u.i;
60658   sqlite3VdbeMemRelease(&m);
60659   return SQLITE_OK;
60660
60661   /* Jump here if database corruption is detected after m has been
60662   ** allocated.  Free the m object and return SQLITE_CORRUPT. */
60663 idx_rowid_corruption:
60664   testcase( m.zMalloc!=0 );
60665   sqlite3VdbeMemRelease(&m);
60666   return SQLITE_CORRUPT_BKPT;
60667 }
60668
60669 /*
60670 ** Compare the key of the index entry that cursor pC is pointing to against
60671 ** the key string in pUnpacked.  Write into *pRes a number
60672 ** that is negative, zero, or positive if pC is less than, equal to,
60673 ** or greater than pUnpacked.  Return SQLITE_OK on success.
60674 **
60675 ** pUnpacked is either created without a rowid or is truncated so that it
60676 ** omits the rowid at the end.  The rowid at the end of the index entry
60677 ** is ignored as well.  Hence, this routine only compares the prefixes 
60678 ** of the keys prior to the final rowid, not the entire key.
60679 */
60680 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
60681   VdbeCursor *pC,             /* The cursor to compare against */
60682   UnpackedRecord *pUnpacked,  /* Unpacked version of key to compare against */
60683   int *res                    /* Write the comparison result here */
60684 ){
60685   i64 nCellKey = 0;
60686   int rc;
60687   BtCursor *pCur = pC->pCursor;
60688   Mem m;
60689
60690   assert( sqlite3BtreeCursorIsValid(pCur) );
60691   rc = sqlite3BtreeKeySize(pCur, &nCellKey);
60692   assert( rc==SQLITE_OK );    /* pCur is always valid so KeySize cannot fail */
60693   /* nCellKey will always be between 0 and 0xffffffff because of the say
60694   ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
60695   if( nCellKey<=0 || nCellKey>0x7fffffff ){
60696     *res = 0;
60697     return SQLITE_CORRUPT_BKPT;
60698   }
60699   memset(&m, 0, sizeof(m));
60700   rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
60701   if( rc ){
60702     return rc;
60703   }
60704   assert( pUnpacked->flags & UNPACKED_IGNORE_ROWID );
60705   *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
60706   sqlite3VdbeMemRelease(&m);
60707   return SQLITE_OK;
60708 }
60709
60710 /*
60711 ** This routine sets the value to be returned by subsequent calls to
60712 ** sqlite3_changes() on the database handle 'db'. 
60713 */
60714 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
60715   assert( sqlite3_mutex_held(db->mutex) );
60716   db->nChange = nChange;
60717   db->nTotalChange += nChange;
60718 }
60719
60720 /*
60721 ** Set a flag in the vdbe to update the change counter when it is finalised
60722 ** or reset.
60723 */
60724 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
60725   v->changeCntOn = 1;
60726 }
60727
60728 /*
60729 ** Mark every prepared statement associated with a database connection
60730 ** as expired.
60731 **
60732 ** An expired statement means that recompilation of the statement is
60733 ** recommend.  Statements expire when things happen that make their
60734 ** programs obsolete.  Removing user-defined functions or collating
60735 ** sequences, or changing an authorization function are the types of
60736 ** things that make prepared statements obsolete.
60737 */
60738 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
60739   Vdbe *p;
60740   for(p = db->pVdbe; p; p=p->pNext){
60741     p->expired = 1;
60742   }
60743 }
60744
60745 /*
60746 ** Return the database associated with the Vdbe.
60747 */
60748 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
60749   return v->db;
60750 }
60751
60752 /*
60753 ** Return a pointer to an sqlite3_value structure containing the value bound
60754 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return 
60755 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
60756 ** constants) to the value before returning it.
60757 **
60758 ** The returned value must be freed by the caller using sqlite3ValueFree().
60759 */
60760 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe *v, int iVar, u8 aff){
60761   assert( iVar>0 );
60762   if( v ){
60763     Mem *pMem = &v->aVar[iVar-1];
60764     if( 0==(pMem->flags & MEM_Null) ){
60765       sqlite3_value *pRet = sqlite3ValueNew(v->db);
60766       if( pRet ){
60767         sqlite3VdbeMemCopy((Mem *)pRet, pMem);
60768         sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
60769         sqlite3VdbeMemStoreType((Mem *)pRet);
60770       }
60771       return pRet;
60772     }
60773   }
60774   return 0;
60775 }
60776
60777 /*
60778 ** Configure SQL variable iVar so that binding a new value to it signals
60779 ** to sqlite3_reoptimize() that re-preparing the statement may result
60780 ** in a better query plan.
60781 */
60782 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
60783   assert( iVar>0 );
60784   if( iVar>32 ){
60785     v->expmask = 0xffffffff;
60786   }else{
60787     v->expmask |= ((u32)1 << (iVar-1));
60788   }
60789 }
60790
60791 /************** End of vdbeaux.c *********************************************/
60792 /************** Begin file vdbeapi.c *****************************************/
60793 /*
60794 ** 2004 May 26
60795 **
60796 ** The author disclaims copyright to this source code.  In place of
60797 ** a legal notice, here is a blessing:
60798 **
60799 **    May you do good and not evil.
60800 **    May you find forgiveness for yourself and forgive others.
60801 **    May you share freely, never taking more than you give.
60802 **
60803 *************************************************************************
60804 **
60805 ** This file contains code use to implement APIs that are part of the
60806 ** VDBE.
60807 */
60808
60809 #ifndef SQLITE_OMIT_DEPRECATED
60810 /*
60811 ** Return TRUE (non-zero) of the statement supplied as an argument needs
60812 ** to be recompiled.  A statement needs to be recompiled whenever the
60813 ** execution environment changes in a way that would alter the program
60814 ** that sqlite3_prepare() generates.  For example, if new functions or
60815 ** collating sequences are registered or if an authorizer function is
60816 ** added or changed.
60817 */
60818 SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
60819   Vdbe *p = (Vdbe*)pStmt;
60820   return p==0 || p->expired;
60821 }
60822 #endif
60823
60824 /*
60825 ** Check on a Vdbe to make sure it has not been finalized.  Log
60826 ** an error and return true if it has been finalized (or is otherwise
60827 ** invalid).  Return false if it is ok.
60828 */
60829 static int vdbeSafety(Vdbe *p){
60830   if( p->db==0 ){
60831     sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
60832     return 1;
60833   }else{
60834     return 0;
60835   }
60836 }
60837 static int vdbeSafetyNotNull(Vdbe *p){
60838   if( p==0 ){
60839     sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
60840     return 1;
60841   }else{
60842     return vdbeSafety(p);
60843   }
60844 }
60845
60846 /*
60847 ** The following routine destroys a virtual machine that is created by
60848 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
60849 ** success/failure code that describes the result of executing the virtual
60850 ** machine.
60851 **
60852 ** This routine sets the error code and string returned by
60853 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
60854 */
60855 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
60856   int rc;
60857   if( pStmt==0 ){
60858     /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
60859     ** pointer is a harmless no-op. */
60860     rc = SQLITE_OK;
60861   }else{
60862     Vdbe *v = (Vdbe*)pStmt;
60863     sqlite3 *db = v->db;
60864 #if SQLITE_THREADSAFE
60865     sqlite3_mutex *mutex;
60866 #endif
60867     if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
60868 #if SQLITE_THREADSAFE
60869     mutex = v->db->mutex;
60870 #endif
60871     sqlite3_mutex_enter(mutex);
60872     rc = sqlite3VdbeFinalize(v);
60873     rc = sqlite3ApiExit(db, rc);
60874     sqlite3_mutex_leave(mutex);
60875   }
60876   return rc;
60877 }
60878
60879 /*
60880 ** Terminate the current execution of an SQL statement and reset it
60881 ** back to its starting state so that it can be reused. A success code from
60882 ** the prior execution is returned.
60883 **
60884 ** This routine sets the error code and string returned by
60885 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
60886 */
60887 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
60888   int rc;
60889   if( pStmt==0 ){
60890     rc = SQLITE_OK;
60891   }else{
60892     Vdbe *v = (Vdbe*)pStmt;
60893     sqlite3_mutex_enter(v->db->mutex);
60894     rc = sqlite3VdbeReset(v);
60895     sqlite3VdbeRewind(v);
60896     assert( (rc & (v->db->errMask))==rc );
60897     rc = sqlite3ApiExit(v->db, rc);
60898     sqlite3_mutex_leave(v->db->mutex);
60899   }
60900   return rc;
60901 }
60902
60903 /*
60904 ** Set all the parameters in the compiled SQL statement to NULL.
60905 */
60906 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
60907   int i;
60908   int rc = SQLITE_OK;
60909   Vdbe *p = (Vdbe*)pStmt;
60910 #if SQLITE_THREADSAFE
60911   sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
60912 #endif
60913   sqlite3_mutex_enter(mutex);
60914   for(i=0; i<p->nVar; i++){
60915     sqlite3VdbeMemRelease(&p->aVar[i]);
60916     p->aVar[i].flags = MEM_Null;
60917   }
60918   if( p->isPrepareV2 && p->expmask ){
60919     p->expired = 1;
60920   }
60921   sqlite3_mutex_leave(mutex);
60922   return rc;
60923 }
60924
60925
60926 /**************************** sqlite3_value_  *******************************
60927 ** The following routines extract information from a Mem or sqlite3_value
60928 ** structure.
60929 */
60930 SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
60931   Mem *p = (Mem*)pVal;
60932   if( p->flags & (MEM_Blob|MEM_Str) ){
60933     sqlite3VdbeMemExpandBlob(p);
60934     p->flags &= ~MEM_Str;
60935     p->flags |= MEM_Blob;
60936     return p->n ? p->z : 0;
60937   }else{
60938     return sqlite3_value_text(pVal);
60939   }
60940 }
60941 SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
60942   return sqlite3ValueBytes(pVal, SQLITE_UTF8);
60943 }
60944 SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
60945   return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
60946 }
60947 SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
60948   return sqlite3VdbeRealValue((Mem*)pVal);
60949 }
60950 SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
60951   return (int)sqlite3VdbeIntValue((Mem*)pVal);
60952 }
60953 SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
60954   return sqlite3VdbeIntValue((Mem*)pVal);
60955 }
60956 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
60957   return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
60958 }
60959 #ifndef SQLITE_OMIT_UTF16
60960 SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
60961   return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
60962 }
60963 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
60964   return sqlite3ValueText(pVal, SQLITE_UTF16BE);
60965 }
60966 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
60967   return sqlite3ValueText(pVal, SQLITE_UTF16LE);
60968 }
60969 #endif /* SQLITE_OMIT_UTF16 */
60970 SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
60971   return pVal->type;
60972 }
60973
60974 /**************************** sqlite3_result_  *******************************
60975 ** The following routines are used by user-defined functions to specify
60976 ** the function result.
60977 **
60978 ** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the
60979 ** result as a string or blob but if the string or blob is too large, it
60980 ** then sets the error code to SQLITE_TOOBIG
60981 */
60982 static void setResultStrOrError(
60983   sqlite3_context *pCtx,  /* Function context */
60984   const char *z,          /* String pointer */
60985   int n,                  /* Bytes in string, or negative */
60986   u8 enc,                 /* Encoding of z.  0 for BLOBs */
60987   void (*xDel)(void*)     /* Destructor function */
60988 ){
60989   if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
60990     sqlite3_result_error_toobig(pCtx);
60991   }
60992 }
60993 SQLITE_API void sqlite3_result_blob(
60994   sqlite3_context *pCtx, 
60995   const void *z, 
60996   int n, 
60997   void (*xDel)(void *)
60998 ){
60999   assert( n>=0 );
61000   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61001   setResultStrOrError(pCtx, z, n, 0, xDel);
61002 }
61003 SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
61004   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61005   sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
61006 }
61007 SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
61008   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61009   pCtx->isError = SQLITE_ERROR;
61010   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
61011 }
61012 #ifndef SQLITE_OMIT_UTF16
61013 SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
61014   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61015   pCtx->isError = SQLITE_ERROR;
61016   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
61017 }
61018 #endif
61019 SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
61020   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61021   sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
61022 }
61023 SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
61024   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61025   sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
61026 }
61027 SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
61028   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61029   sqlite3VdbeMemSetNull(&pCtx->s);
61030 }
61031 SQLITE_API void sqlite3_result_text(
61032   sqlite3_context *pCtx, 
61033   const char *z, 
61034   int n,
61035   void (*xDel)(void *)
61036 ){
61037   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61038   setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
61039 }
61040 #ifndef SQLITE_OMIT_UTF16
61041 SQLITE_API void sqlite3_result_text16(
61042   sqlite3_context *pCtx, 
61043   const void *z, 
61044   int n, 
61045   void (*xDel)(void *)
61046 ){
61047   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61048   setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
61049 }
61050 SQLITE_API void sqlite3_result_text16be(
61051   sqlite3_context *pCtx, 
61052   const void *z, 
61053   int n, 
61054   void (*xDel)(void *)
61055 ){
61056   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61057   setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
61058 }
61059 SQLITE_API void sqlite3_result_text16le(
61060   sqlite3_context *pCtx, 
61061   const void *z, 
61062   int n, 
61063   void (*xDel)(void *)
61064 ){
61065   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61066   setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
61067 }
61068 #endif /* SQLITE_OMIT_UTF16 */
61069 SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
61070   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61071   sqlite3VdbeMemCopy(&pCtx->s, pValue);
61072 }
61073 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
61074   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61075   sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
61076 }
61077 SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
61078   pCtx->isError = errCode;
61079   if( pCtx->s.flags & MEM_Null ){
61080     sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1, 
61081                          SQLITE_UTF8, SQLITE_STATIC);
61082   }
61083 }
61084
61085 /* Force an SQLITE_TOOBIG error. */
61086 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
61087   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61088   pCtx->isError = SQLITE_TOOBIG;
61089   sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1, 
61090                        SQLITE_UTF8, SQLITE_STATIC);
61091 }
61092
61093 /* An SQLITE_NOMEM error. */
61094 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
61095   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61096   sqlite3VdbeMemSetNull(&pCtx->s);
61097   pCtx->isError = SQLITE_NOMEM;
61098   pCtx->s.db->mallocFailed = 1;
61099 }
61100
61101 /*
61102 ** This function is called after a transaction has been committed. It 
61103 ** invokes callbacks registered with sqlite3_wal_hook() as required.
61104 */
61105 static int doWalCallbacks(sqlite3 *db){
61106   int rc = SQLITE_OK;
61107 #ifndef SQLITE_OMIT_WAL
61108   int i;
61109   for(i=0; i<db->nDb; i++){
61110     Btree *pBt = db->aDb[i].pBt;
61111     if( pBt ){
61112       int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
61113       if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
61114         rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
61115       }
61116     }
61117   }
61118 #endif
61119   return rc;
61120 }
61121
61122 /*
61123 ** Execute the statement pStmt, either until a row of data is ready, the
61124 ** statement is completely executed or an error occurs.
61125 **
61126 ** This routine implements the bulk of the logic behind the sqlite_step()
61127 ** API.  The only thing omitted is the automatic recompile if a 
61128 ** schema change has occurred.  That detail is handled by the
61129 ** outer sqlite3_step() wrapper procedure.
61130 */
61131 static int sqlite3Step(Vdbe *p){
61132   sqlite3 *db;
61133   int rc;
61134
61135   assert(p);
61136   if( p->magic!=VDBE_MAGIC_RUN ){
61137     /* We used to require that sqlite3_reset() be called before retrying
61138     ** sqlite3_step() after any error or after SQLITE_DONE.  But beginning
61139     ** with version 3.7.0, we changed this so that sqlite3_reset() would
61140     ** be called automatically instead of throwing the SQLITE_MISUSE error.
61141     ** This "automatic-reset" change is not technically an incompatibility, 
61142     ** since any application that receives an SQLITE_MISUSE is broken by
61143     ** definition.
61144     **
61145     ** Nevertheless, some published applications that were originally written
61146     ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE 
61147     ** returns, and the so were broken by the automatic-reset change.  As a
61148     ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
61149     ** legacy behavior of returning SQLITE_MISUSE for cases where the 
61150     ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
61151     ** or SQLITE_BUSY error.
61152     */
61153 #ifdef SQLITE_OMIT_AUTORESET
61154     if( p->rc==SQLITE_BUSY || p->rc==SQLITE_LOCKED ){
61155       sqlite3_reset((sqlite3_stmt*)p);
61156     }else{
61157       return SQLITE_MISUSE_BKPT;
61158     }
61159 #else
61160     sqlite3_reset((sqlite3_stmt*)p);
61161 #endif
61162   }
61163
61164   /* Check that malloc() has not failed. If it has, return early. */
61165   db = p->db;
61166   if( db->mallocFailed ){
61167     p->rc = SQLITE_NOMEM;
61168     return SQLITE_NOMEM;
61169   }
61170
61171   if( p->pc<=0 && p->expired ){
61172     p->rc = SQLITE_SCHEMA;
61173     rc = SQLITE_ERROR;
61174     goto end_of_step;
61175   }
61176   if( p->pc<0 ){
61177     /* If there are no other statements currently running, then
61178     ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
61179     ** from interrupting a statement that has not yet started.
61180     */
61181     if( db->activeVdbeCnt==0 ){
61182       db->u1.isInterrupted = 0;
61183     }
61184
61185     assert( db->writeVdbeCnt>0 || db->autoCommit==0 || db->nDeferredCons==0 );
61186
61187 #ifndef SQLITE_OMIT_TRACE
61188     if( db->xProfile && !db->init.busy ){
61189       sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
61190     }
61191 #endif
61192
61193     db->activeVdbeCnt++;
61194     if( p->readOnly==0 ) db->writeVdbeCnt++;
61195     p->pc = 0;
61196   }
61197 #ifndef SQLITE_OMIT_EXPLAIN
61198   if( p->explain ){
61199     rc = sqlite3VdbeList(p);
61200   }else
61201 #endif /* SQLITE_OMIT_EXPLAIN */
61202   {
61203     db->vdbeExecCnt++;
61204     rc = sqlite3VdbeExec(p);
61205     db->vdbeExecCnt--;
61206   }
61207
61208 #ifndef SQLITE_OMIT_TRACE
61209   /* Invoke the profile callback if there is one
61210   */
61211   if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
61212     sqlite3_int64 iNow;
61213     sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
61214     db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
61215   }
61216 #endif
61217
61218   if( rc==SQLITE_DONE ){
61219     assert( p->rc==SQLITE_OK );
61220     p->rc = doWalCallbacks(db);
61221     if( p->rc!=SQLITE_OK ){
61222       rc = SQLITE_ERROR;
61223     }
61224   }
61225
61226   db->errCode = rc;
61227   if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
61228     p->rc = SQLITE_NOMEM;
61229   }
61230 end_of_step:
61231   /* At this point local variable rc holds the value that should be 
61232   ** returned if this statement was compiled using the legacy 
61233   ** sqlite3_prepare() interface. According to the docs, this can only
61234   ** be one of the values in the first assert() below. Variable p->rc 
61235   ** contains the value that would be returned if sqlite3_finalize() 
61236   ** were called on statement p.
61237   */
61238   assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR 
61239        || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
61240   );
61241   assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
61242   if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
61243     /* If this statement was prepared using sqlite3_prepare_v2(), and an
61244     ** error has occured, then return the error code in p->rc to the
61245     ** caller. Set the error code in the database handle to the same value.
61246     */ 
61247     rc = db->errCode = p->rc;
61248   }
61249   return (rc&db->errMask);
61250 }
61251
61252 /*
61253 ** The maximum number of times that a statement will try to reparse
61254 ** itself before giving up and returning SQLITE_SCHEMA.
61255 */
61256 #ifndef SQLITE_MAX_SCHEMA_RETRY
61257 # define SQLITE_MAX_SCHEMA_RETRY 5
61258 #endif
61259
61260 /*
61261 ** This is the top-level implementation of sqlite3_step().  Call
61262 ** sqlite3Step() to do most of the work.  If a schema error occurs,
61263 ** call sqlite3Reprepare() and try again.
61264 */
61265 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
61266   int rc = SQLITE_OK;      /* Result from sqlite3Step() */
61267   int rc2 = SQLITE_OK;     /* Result from sqlite3Reprepare() */
61268   Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
61269   int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
61270   sqlite3 *db;             /* The database connection */
61271
61272   if( vdbeSafetyNotNull(v) ){
61273     return SQLITE_MISUSE_BKPT;
61274   }
61275   db = v->db;
61276   sqlite3_mutex_enter(db->mutex);
61277   while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
61278          && cnt++ < SQLITE_MAX_SCHEMA_RETRY
61279          && (rc2 = rc = sqlite3Reprepare(v))==SQLITE_OK ){
61280     sqlite3_reset(pStmt);
61281     v->expired = 0;
61282   }
61283   if( rc2!=SQLITE_OK && ALWAYS(v->isPrepareV2) && ALWAYS(db->pErr) ){
61284     /* This case occurs after failing to recompile an sql statement. 
61285     ** The error message from the SQL compiler has already been loaded 
61286     ** into the database handle. This block copies the error message 
61287     ** from the database handle into the statement and sets the statement
61288     ** program counter to 0 to ensure that when the statement is 
61289     ** finalized or reset the parser error message is available via
61290     ** sqlite3_errmsg() and sqlite3_errcode().
61291     */
61292     const char *zErr = (const char *)sqlite3_value_text(db->pErr); 
61293     sqlite3DbFree(db, v->zErrMsg);
61294     if( !db->mallocFailed ){
61295       v->zErrMsg = sqlite3DbStrDup(db, zErr);
61296       v->rc = rc2;
61297     } else {
61298       v->zErrMsg = 0;
61299       v->rc = rc = SQLITE_NOMEM;
61300     }
61301   }
61302   rc = sqlite3ApiExit(db, rc);
61303   sqlite3_mutex_leave(db->mutex);
61304   return rc;
61305 }
61306
61307 /*
61308 ** Extract the user data from a sqlite3_context structure and return a
61309 ** pointer to it.
61310 */
61311 SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
61312   assert( p && p->pFunc );
61313   return p->pFunc->pUserData;
61314 }
61315
61316 /*
61317 ** Extract the user data from a sqlite3_context structure and return a
61318 ** pointer to it.
61319 **
61320 ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
61321 ** returns a copy of the pointer to the database connection (the 1st
61322 ** parameter) of the sqlite3_create_function() and
61323 ** sqlite3_create_function16() routines that originally registered the
61324 ** application defined function.
61325 */
61326 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
61327   assert( p && p->pFunc );
61328   return p->s.db;
61329 }
61330
61331 /*
61332 ** The following is the implementation of an SQL function that always
61333 ** fails with an error message stating that the function is used in the
61334 ** wrong context.  The sqlite3_overload_function() API might construct
61335 ** SQL function that use this routine so that the functions will exist
61336 ** for name resolution but are actually overloaded by the xFindFunction
61337 ** method of virtual tables.
61338 */
61339 SQLITE_PRIVATE void sqlite3InvalidFunction(
61340   sqlite3_context *context,  /* The function calling context */
61341   int NotUsed,               /* Number of arguments to the function */
61342   sqlite3_value **NotUsed2   /* Value of each argument */
61343 ){
61344   const char *zName = context->pFunc->zName;
61345   char *zErr;
61346   UNUSED_PARAMETER2(NotUsed, NotUsed2);
61347   zErr = sqlite3_mprintf(
61348       "unable to use function %s in the requested context", zName);
61349   sqlite3_result_error(context, zErr, -1);
61350   sqlite3_free(zErr);
61351 }
61352
61353 /*
61354 ** Allocate or return the aggregate context for a user function.  A new
61355 ** context is allocated on the first call.  Subsequent calls return the
61356 ** same context that was returned on prior calls.
61357 */
61358 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
61359   Mem *pMem;
61360   assert( p && p->pFunc && p->pFunc->xStep );
61361   assert( sqlite3_mutex_held(p->s.db->mutex) );
61362   pMem = p->pMem;
61363   testcase( nByte<0 );
61364   if( (pMem->flags & MEM_Agg)==0 ){
61365     if( nByte<=0 ){
61366       sqlite3VdbeMemReleaseExternal(pMem);
61367       pMem->flags = MEM_Null;
61368       pMem->z = 0;
61369     }else{
61370       sqlite3VdbeMemGrow(pMem, nByte, 0);
61371       pMem->flags = MEM_Agg;
61372       pMem->u.pDef = p->pFunc;
61373       if( pMem->z ){
61374         memset(pMem->z, 0, nByte);
61375       }
61376     }
61377   }
61378   return (void*)pMem->z;
61379 }
61380
61381 /*
61382 ** Return the auxilary data pointer, if any, for the iArg'th argument to
61383 ** the user-function defined by pCtx.
61384 */
61385 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
61386   VdbeFunc *pVdbeFunc;
61387
61388   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61389   pVdbeFunc = pCtx->pVdbeFunc;
61390   if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
61391     return 0;
61392   }
61393   return pVdbeFunc->apAux[iArg].pAux;
61394 }
61395
61396 /*
61397 ** Set the auxilary data pointer and delete function, for the iArg'th
61398 ** argument to the user-function defined by pCtx. Any previous value is
61399 ** deleted by calling the delete function specified when it was set.
61400 */
61401 SQLITE_API void sqlite3_set_auxdata(
61402   sqlite3_context *pCtx, 
61403   int iArg, 
61404   void *pAux, 
61405   void (*xDelete)(void*)
61406 ){
61407   struct AuxData *pAuxData;
61408   VdbeFunc *pVdbeFunc;
61409   if( iArg<0 ) goto failed;
61410
61411   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61412   pVdbeFunc = pCtx->pVdbeFunc;
61413   if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
61414     int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
61415     int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
61416     pVdbeFunc = sqlite3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
61417     if( !pVdbeFunc ){
61418       goto failed;
61419     }
61420     pCtx->pVdbeFunc = pVdbeFunc;
61421     memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
61422     pVdbeFunc->nAux = iArg+1;
61423     pVdbeFunc->pFunc = pCtx->pFunc;
61424   }
61425
61426   pAuxData = &pVdbeFunc->apAux[iArg];
61427   if( pAuxData->pAux && pAuxData->xDelete ){
61428     pAuxData->xDelete(pAuxData->pAux);
61429   }
61430   pAuxData->pAux = pAux;
61431   pAuxData->xDelete = xDelete;
61432   return;
61433
61434 failed:
61435   if( xDelete ){
61436     xDelete(pAux);
61437   }
61438 }
61439
61440 #ifndef SQLITE_OMIT_DEPRECATED
61441 /*
61442 ** Return the number of times the Step function of a aggregate has been 
61443 ** called.
61444 **
61445 ** This function is deprecated.  Do not use it for new code.  It is
61446 ** provide only to avoid breaking legacy code.  New aggregate function
61447 ** implementations should keep their own counts within their aggregate
61448 ** context.
61449 */
61450 SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
61451   assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
61452   return p->pMem->n;
61453 }
61454 #endif
61455
61456 /*
61457 ** Return the number of columns in the result set for the statement pStmt.
61458 */
61459 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
61460   Vdbe *pVm = (Vdbe *)pStmt;
61461   return pVm ? pVm->nResColumn : 0;
61462 }
61463
61464 /*
61465 ** Return the number of values available from the current row of the
61466 ** currently executing statement pStmt.
61467 */
61468 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
61469   Vdbe *pVm = (Vdbe *)pStmt;
61470   if( pVm==0 || pVm->pResultSet==0 ) return 0;
61471   return pVm->nResColumn;
61472 }
61473
61474
61475 /*
61476 ** Check to see if column iCol of the given statement is valid.  If
61477 ** it is, return a pointer to the Mem for the value of that column.
61478 ** If iCol is not valid, return a pointer to a Mem which has a value
61479 ** of NULL.
61480 */
61481 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
61482   Vdbe *pVm;
61483   Mem *pOut;
61484
61485   pVm = (Vdbe *)pStmt;
61486   if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
61487     sqlite3_mutex_enter(pVm->db->mutex);
61488     pOut = &pVm->pResultSet[i];
61489   }else{
61490     /* If the value passed as the second argument is out of range, return
61491     ** a pointer to the following static Mem object which contains the
61492     ** value SQL NULL. Even though the Mem structure contains an element
61493     ** of type i64, on certain architecture (x86) with certain compiler
61494     ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
61495     ** instead of an 8-byte one. This all works fine, except that when
61496     ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
61497     ** that a Mem structure is located on an 8-byte boundary. To prevent
61498     ** this assert() from failing, when building with SQLITE_DEBUG defined
61499     ** using gcc, force nullMem to be 8-byte aligned using the magical
61500     ** __attribute__((aligned(8))) macro.  */
61501     static const Mem nullMem 
61502 #if defined(SQLITE_DEBUG) && defined(__GNUC__)
61503       __attribute__((aligned(8))) 
61504 #endif
61505       = {0, "", (double)0, {0}, 0, MEM_Null, SQLITE_NULL, 0,
61506 #ifdef SQLITE_DEBUG
61507          0, 0,  /* pScopyFrom, pFiller */
61508 #endif
61509          0, 0 };
61510
61511     if( pVm && ALWAYS(pVm->db) ){
61512       sqlite3_mutex_enter(pVm->db->mutex);
61513       sqlite3Error(pVm->db, SQLITE_RANGE, 0);
61514     }
61515     pOut = (Mem*)&nullMem;
61516   }
61517   return pOut;
61518 }
61519
61520 /*
61521 ** This function is called after invoking an sqlite3_value_XXX function on a 
61522 ** column value (i.e. a value returned by evaluating an SQL expression in the
61523 ** select list of a SELECT statement) that may cause a malloc() failure. If 
61524 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
61525 ** code of statement pStmt set to SQLITE_NOMEM.
61526 **
61527 ** Specifically, this is called from within:
61528 **
61529 **     sqlite3_column_int()
61530 **     sqlite3_column_int64()
61531 **     sqlite3_column_text()
61532 **     sqlite3_column_text16()
61533 **     sqlite3_column_real()
61534 **     sqlite3_column_bytes()
61535 **     sqlite3_column_bytes16()
61536 **     sqiite3_column_blob()
61537 */
61538 static void columnMallocFailure(sqlite3_stmt *pStmt)
61539 {
61540   /* If malloc() failed during an encoding conversion within an
61541   ** sqlite3_column_XXX API, then set the return code of the statement to
61542   ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
61543   ** and _finalize() will return NOMEM.
61544   */
61545   Vdbe *p = (Vdbe *)pStmt;
61546   if( p ){
61547     p->rc = sqlite3ApiExit(p->db, p->rc);
61548     sqlite3_mutex_leave(p->db->mutex);
61549   }
61550 }
61551
61552 /**************************** sqlite3_column_  *******************************
61553 ** The following routines are used to access elements of the current row
61554 ** in the result set.
61555 */
61556 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
61557   const void *val;
61558   val = sqlite3_value_blob( columnMem(pStmt,i) );
61559   /* Even though there is no encoding conversion, value_blob() might
61560   ** need to call malloc() to expand the result of a zeroblob() 
61561   ** expression. 
61562   */
61563   columnMallocFailure(pStmt);
61564   return val;
61565 }
61566 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
61567   int val = sqlite3_value_bytes( columnMem(pStmt,i) );
61568   columnMallocFailure(pStmt);
61569   return val;
61570 }
61571 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
61572   int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
61573   columnMallocFailure(pStmt);
61574   return val;
61575 }
61576 SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
61577   double val = sqlite3_value_double( columnMem(pStmt,i) );
61578   columnMallocFailure(pStmt);
61579   return val;
61580 }
61581 SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
61582   int val = sqlite3_value_int( columnMem(pStmt,i) );
61583   columnMallocFailure(pStmt);
61584   return val;
61585 }
61586 SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
61587   sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
61588   columnMallocFailure(pStmt);
61589   return val;
61590 }
61591 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
61592   const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
61593   columnMallocFailure(pStmt);
61594   return val;
61595 }
61596 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
61597   Mem *pOut = columnMem(pStmt, i);
61598   if( pOut->flags&MEM_Static ){
61599     pOut->flags &= ~MEM_Static;
61600     pOut->flags |= MEM_Ephem;
61601   }
61602   columnMallocFailure(pStmt);
61603   return (sqlite3_value *)pOut;
61604 }
61605 #ifndef SQLITE_OMIT_UTF16
61606 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
61607   const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
61608   columnMallocFailure(pStmt);
61609   return val;
61610 }
61611 #endif /* SQLITE_OMIT_UTF16 */
61612 SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
61613   int iType = sqlite3_value_type( columnMem(pStmt,i) );
61614   columnMallocFailure(pStmt);
61615   return iType;
61616 }
61617
61618 /* The following function is experimental and subject to change or
61619 ** removal */
61620 /*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
61621 **  return sqlite3_value_numeric_type( columnMem(pStmt,i) );
61622 **}
61623 */
61624
61625 /*
61626 ** Convert the N-th element of pStmt->pColName[] into a string using
61627 ** xFunc() then return that string.  If N is out of range, return 0.
61628 **
61629 ** There are up to 5 names for each column.  useType determines which
61630 ** name is returned.  Here are the names:
61631 **
61632 **    0      The column name as it should be displayed for output
61633 **    1      The datatype name for the column
61634 **    2      The name of the database that the column derives from
61635 **    3      The name of the table that the column derives from
61636 **    4      The name of the table column that the result column derives from
61637 **
61638 ** If the result is not a simple column reference (if it is an expression
61639 ** or a constant) then useTypes 2, 3, and 4 return NULL.
61640 */
61641 static const void *columnName(
61642   sqlite3_stmt *pStmt,
61643   int N,
61644   const void *(*xFunc)(Mem*),
61645   int useType
61646 ){
61647   const void *ret = 0;
61648   Vdbe *p = (Vdbe *)pStmt;
61649   int n;
61650   sqlite3 *db = p->db;
61651   
61652   assert( db!=0 );
61653   n = sqlite3_column_count(pStmt);
61654   if( N<n && N>=0 ){
61655     N += useType*n;
61656     sqlite3_mutex_enter(db->mutex);
61657     assert( db->mallocFailed==0 );
61658     ret = xFunc(&p->aColName[N]);
61659      /* A malloc may have failed inside of the xFunc() call. If this
61660     ** is the case, clear the mallocFailed flag and return NULL.
61661     */
61662     if( db->mallocFailed ){
61663       db->mallocFailed = 0;
61664       ret = 0;
61665     }
61666     sqlite3_mutex_leave(db->mutex);
61667   }
61668   return ret;
61669 }
61670
61671 /*
61672 ** Return the name of the Nth column of the result set returned by SQL
61673 ** statement pStmt.
61674 */
61675 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
61676   return columnName(
61677       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
61678 }
61679 #ifndef SQLITE_OMIT_UTF16
61680 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
61681   return columnName(
61682       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
61683 }
61684 #endif
61685
61686 /*
61687 ** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
61688 ** not define OMIT_DECLTYPE.
61689 */
61690 #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
61691 # error "Must not define both SQLITE_OMIT_DECLTYPE \
61692          and SQLITE_ENABLE_COLUMN_METADATA"
61693 #endif
61694
61695 #ifndef SQLITE_OMIT_DECLTYPE
61696 /*
61697 ** Return the column declaration type (if applicable) of the 'i'th column
61698 ** of the result set of SQL statement pStmt.
61699 */
61700 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
61701   return columnName(
61702       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
61703 }
61704 #ifndef SQLITE_OMIT_UTF16
61705 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
61706   return columnName(
61707       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
61708 }
61709 #endif /* SQLITE_OMIT_UTF16 */
61710 #endif /* SQLITE_OMIT_DECLTYPE */
61711
61712 #ifdef SQLITE_ENABLE_COLUMN_METADATA
61713 /*
61714 ** Return the name of the database from which a result column derives.
61715 ** NULL is returned if the result column is an expression or constant or
61716 ** anything else which is not an unabiguous reference to a database column.
61717 */
61718 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
61719   return columnName(
61720       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
61721 }
61722 #ifndef SQLITE_OMIT_UTF16
61723 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
61724   return columnName(
61725       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
61726 }
61727 #endif /* SQLITE_OMIT_UTF16 */
61728
61729 /*
61730 ** Return the name of the table from which a result column derives.
61731 ** NULL is returned if the result column is an expression or constant or
61732 ** anything else which is not an unabiguous reference to a database column.
61733 */
61734 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
61735   return columnName(
61736       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
61737 }
61738 #ifndef SQLITE_OMIT_UTF16
61739 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
61740   return columnName(
61741       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
61742 }
61743 #endif /* SQLITE_OMIT_UTF16 */
61744
61745 /*
61746 ** Return the name of the table column from which a result column derives.
61747 ** NULL is returned if the result column is an expression or constant or
61748 ** anything else which is not an unabiguous reference to a database column.
61749 */
61750 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
61751   return columnName(
61752       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
61753 }
61754 #ifndef SQLITE_OMIT_UTF16
61755 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
61756   return columnName(
61757       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
61758 }
61759 #endif /* SQLITE_OMIT_UTF16 */
61760 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
61761
61762
61763 /******************************* sqlite3_bind_  ***************************
61764 ** 
61765 ** Routines used to attach values to wildcards in a compiled SQL statement.
61766 */
61767 /*
61768 ** Unbind the value bound to variable i in virtual machine p. This is the 
61769 ** the same as binding a NULL value to the column. If the "i" parameter is
61770 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
61771 **
61772 ** A successful evaluation of this routine acquires the mutex on p.
61773 ** the mutex is released if any kind of error occurs.
61774 **
61775 ** The error code stored in database p->db is overwritten with the return
61776 ** value in any case.
61777 */
61778 static int vdbeUnbind(Vdbe *p, int i){
61779   Mem *pVar;
61780   if( vdbeSafetyNotNull(p) ){
61781     return SQLITE_MISUSE_BKPT;
61782   }
61783   sqlite3_mutex_enter(p->db->mutex);
61784   if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
61785     sqlite3Error(p->db, SQLITE_MISUSE, 0);
61786     sqlite3_mutex_leave(p->db->mutex);
61787     sqlite3_log(SQLITE_MISUSE, 
61788         "bind on a busy prepared statement: [%s]", p->zSql);
61789     return SQLITE_MISUSE_BKPT;
61790   }
61791   if( i<1 || i>p->nVar ){
61792     sqlite3Error(p->db, SQLITE_RANGE, 0);
61793     sqlite3_mutex_leave(p->db->mutex);
61794     return SQLITE_RANGE;
61795   }
61796   i--;
61797   pVar = &p->aVar[i];
61798   sqlite3VdbeMemRelease(pVar);
61799   pVar->flags = MEM_Null;
61800   sqlite3Error(p->db, SQLITE_OK, 0);
61801
61802   /* If the bit corresponding to this variable in Vdbe.expmask is set, then 
61803   ** binding a new value to this variable invalidates the current query plan.
61804   **
61805   ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
61806   ** parameter in the WHERE clause might influence the choice of query plan
61807   ** for a statement, then the statement will be automatically recompiled,
61808   ** as if there had been a schema change, on the first sqlite3_step() call
61809   ** following any change to the bindings of that parameter.
61810   */
61811   if( p->isPrepareV2 &&
61812      ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
61813   ){
61814     p->expired = 1;
61815   }
61816   return SQLITE_OK;
61817 }
61818
61819 /*
61820 ** Bind a text or BLOB value.
61821 */
61822 static int bindText(
61823   sqlite3_stmt *pStmt,   /* The statement to bind against */
61824   int i,                 /* Index of the parameter to bind */
61825   const void *zData,     /* Pointer to the data to be bound */
61826   int nData,             /* Number of bytes of data to be bound */
61827   void (*xDel)(void*),   /* Destructor for the data */
61828   u8 encoding            /* Encoding for the data */
61829 ){
61830   Vdbe *p = (Vdbe *)pStmt;
61831   Mem *pVar;
61832   int rc;
61833
61834   rc = vdbeUnbind(p, i);
61835   if( rc==SQLITE_OK ){
61836     if( zData!=0 ){
61837       pVar = &p->aVar[i-1];
61838       rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
61839       if( rc==SQLITE_OK && encoding!=0 ){
61840         rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
61841       }
61842       sqlite3Error(p->db, rc, 0);
61843       rc = sqlite3ApiExit(p->db, rc);
61844     }
61845     sqlite3_mutex_leave(p->db->mutex);
61846   }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
61847     xDel((void*)zData);
61848   }
61849   return rc;
61850 }
61851
61852
61853 /*
61854 ** Bind a blob value to an SQL statement variable.
61855 */
61856 SQLITE_API int sqlite3_bind_blob(
61857   sqlite3_stmt *pStmt, 
61858   int i, 
61859   const void *zData, 
61860   int nData, 
61861   void (*xDel)(void*)
61862 ){
61863   return bindText(pStmt, i, zData, nData, xDel, 0);
61864 }
61865 SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
61866   int rc;
61867   Vdbe *p = (Vdbe *)pStmt;
61868   rc = vdbeUnbind(p, i);
61869   if( rc==SQLITE_OK ){
61870     sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
61871     sqlite3_mutex_leave(p->db->mutex);
61872   }
61873   return rc;
61874 }
61875 SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
61876   return sqlite3_bind_int64(p, i, (i64)iValue);
61877 }
61878 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
61879   int rc;
61880   Vdbe *p = (Vdbe *)pStmt;
61881   rc = vdbeUnbind(p, i);
61882   if( rc==SQLITE_OK ){
61883     sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
61884     sqlite3_mutex_leave(p->db->mutex);
61885   }
61886   return rc;
61887 }
61888 SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
61889   int rc;
61890   Vdbe *p = (Vdbe*)pStmt;
61891   rc = vdbeUnbind(p, i);
61892   if( rc==SQLITE_OK ){
61893     sqlite3_mutex_leave(p->db->mutex);
61894   }
61895   return rc;
61896 }
61897 SQLITE_API int sqlite3_bind_text( 
61898   sqlite3_stmt *pStmt, 
61899   int i, 
61900   const char *zData, 
61901   int nData, 
61902   void (*xDel)(void*)
61903 ){
61904   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
61905 }
61906 #ifndef SQLITE_OMIT_UTF16
61907 SQLITE_API int sqlite3_bind_text16(
61908   sqlite3_stmt *pStmt, 
61909   int i, 
61910   const void *zData, 
61911   int nData, 
61912   void (*xDel)(void*)
61913 ){
61914   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
61915 }
61916 #endif /* SQLITE_OMIT_UTF16 */
61917 SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
61918   int rc;
61919   switch( pValue->type ){
61920     case SQLITE_INTEGER: {
61921       rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
61922       break;
61923     }
61924     case SQLITE_FLOAT: {
61925       rc = sqlite3_bind_double(pStmt, i, pValue->r);
61926       break;
61927     }
61928     case SQLITE_BLOB: {
61929       if( pValue->flags & MEM_Zero ){
61930         rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
61931       }else{
61932         rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
61933       }
61934       break;
61935     }
61936     case SQLITE_TEXT: {
61937       rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
61938                               pValue->enc);
61939       break;
61940     }
61941     default: {
61942       rc = sqlite3_bind_null(pStmt, i);
61943       break;
61944     }
61945   }
61946   return rc;
61947 }
61948 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
61949   int rc;
61950   Vdbe *p = (Vdbe *)pStmt;
61951   rc = vdbeUnbind(p, i);
61952   if( rc==SQLITE_OK ){
61953     sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
61954     sqlite3_mutex_leave(p->db->mutex);
61955   }
61956   return rc;
61957 }
61958
61959 /*
61960 ** Return the number of wildcards that can be potentially bound to.
61961 ** This routine is added to support DBD::SQLite.  
61962 */
61963 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
61964   Vdbe *p = (Vdbe*)pStmt;
61965   return p ? p->nVar : 0;
61966 }
61967
61968 /*
61969 ** Return the name of a wildcard parameter.  Return NULL if the index
61970 ** is out of range or if the wildcard is unnamed.
61971 **
61972 ** The result is always UTF-8.
61973 */
61974 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
61975   Vdbe *p = (Vdbe*)pStmt;
61976   if( p==0 || i<1 || i>p->nzVar ){
61977     return 0;
61978   }
61979   return p->azVar[i-1];
61980 }
61981
61982 /*
61983 ** Given a wildcard parameter name, return the index of the variable
61984 ** with that name.  If there is no variable with the given name,
61985 ** return 0.
61986 */
61987 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
61988   int i;
61989   if( p==0 ){
61990     return 0;
61991   }
61992   if( zName ){
61993     for(i=0; i<p->nzVar; i++){
61994       const char *z = p->azVar[i];
61995       if( z && memcmp(z,zName,nName)==0 && z[nName]==0 ){
61996         return i+1;
61997       }
61998     }
61999   }
62000   return 0;
62001 }
62002 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
62003   return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
62004 }
62005
62006 /*
62007 ** Transfer all bindings from the first statement over to the second.
62008 */
62009 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
62010   Vdbe *pFrom = (Vdbe*)pFromStmt;
62011   Vdbe *pTo = (Vdbe*)pToStmt;
62012   int i;
62013   assert( pTo->db==pFrom->db );
62014   assert( pTo->nVar==pFrom->nVar );
62015   sqlite3_mutex_enter(pTo->db->mutex);
62016   for(i=0; i<pFrom->nVar; i++){
62017     sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
62018   }
62019   sqlite3_mutex_leave(pTo->db->mutex);
62020   return SQLITE_OK;
62021 }
62022
62023 #ifndef SQLITE_OMIT_DEPRECATED
62024 /*
62025 ** Deprecated external interface.  Internal/core SQLite code
62026 ** should call sqlite3TransferBindings.
62027 **
62028 ** Is is misuse to call this routine with statements from different
62029 ** database connections.  But as this is a deprecated interface, we
62030 ** will not bother to check for that condition.
62031 **
62032 ** If the two statements contain a different number of bindings, then
62033 ** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
62034 ** SQLITE_OK is returned.
62035 */
62036 SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
62037   Vdbe *pFrom = (Vdbe*)pFromStmt;
62038   Vdbe *pTo = (Vdbe*)pToStmt;
62039   if( pFrom->nVar!=pTo->nVar ){
62040     return SQLITE_ERROR;
62041   }
62042   if( pTo->isPrepareV2 && pTo->expmask ){
62043     pTo->expired = 1;
62044   }
62045   if( pFrom->isPrepareV2 && pFrom->expmask ){
62046     pFrom->expired = 1;
62047   }
62048   return sqlite3TransferBindings(pFromStmt, pToStmt);
62049 }
62050 #endif
62051
62052 /*
62053 ** Return the sqlite3* database handle to which the prepared statement given
62054 ** in the argument belongs.  This is the same database handle that was
62055 ** the first argument to the sqlite3_prepare() that was used to create
62056 ** the statement in the first place.
62057 */
62058 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
62059   return pStmt ? ((Vdbe*)pStmt)->db : 0;
62060 }
62061
62062 /*
62063 ** Return true if the prepared statement is guaranteed to not modify the
62064 ** database.
62065 */
62066 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
62067   return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
62068 }
62069
62070 /*
62071 ** Return a pointer to the next prepared statement after pStmt associated
62072 ** with database connection pDb.  If pStmt is NULL, return the first
62073 ** prepared statement for the database connection.  Return NULL if there
62074 ** are no more.
62075 */
62076 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
62077   sqlite3_stmt *pNext;
62078   sqlite3_mutex_enter(pDb->mutex);
62079   if( pStmt==0 ){
62080     pNext = (sqlite3_stmt*)pDb->pVdbe;
62081   }else{
62082     pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
62083   }
62084   sqlite3_mutex_leave(pDb->mutex);
62085   return pNext;
62086 }
62087
62088 /*
62089 ** Return the value of a status counter for a prepared statement
62090 */
62091 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
62092   Vdbe *pVdbe = (Vdbe*)pStmt;
62093   int v = pVdbe->aCounter[op-1];
62094   if( resetFlag ) pVdbe->aCounter[op-1] = 0;
62095   return v;
62096 }
62097
62098 /************** End of vdbeapi.c *********************************************/
62099 /************** Begin file vdbetrace.c ***************************************/
62100 /*
62101 ** 2009 November 25
62102 **
62103 ** The author disclaims copyright to this source code.  In place of
62104 ** a legal notice, here is a blessing:
62105 **
62106 **    May you do good and not evil.
62107 **    May you find forgiveness for yourself and forgive others.
62108 **    May you share freely, never taking more than you give.
62109 **
62110 *************************************************************************
62111 **
62112 ** This file contains code used to insert the values of host parameters
62113 ** (aka "wildcards") into the SQL text output by sqlite3_trace().
62114 */
62115
62116 #ifndef SQLITE_OMIT_TRACE
62117
62118 /*
62119 ** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
62120 ** bytes in this text up to but excluding the first character in
62121 ** a host parameter.  If the text contains no host parameters, return
62122 ** the total number of bytes in the text.
62123 */
62124 static int findNextHostParameter(const char *zSql, int *pnToken){
62125   int tokenType;
62126   int nTotal = 0;
62127   int n;
62128
62129   *pnToken = 0;
62130   while( zSql[0] ){
62131     n = sqlite3GetToken((u8*)zSql, &tokenType);
62132     assert( n>0 && tokenType!=TK_ILLEGAL );
62133     if( tokenType==TK_VARIABLE ){
62134       *pnToken = n;
62135       break;
62136     }
62137     nTotal += n;
62138     zSql += n;
62139   }
62140   return nTotal;
62141 }
62142
62143 /*
62144 ** This function returns a pointer to a nul-terminated string in memory
62145 ** obtained from sqlite3DbMalloc(). If sqlite3.vdbeExecCnt is 1, then the
62146 ** string contains a copy of zRawSql but with host parameters expanded to 
62147 ** their current bindings. Or, if sqlite3.vdbeExecCnt is greater than 1, 
62148 ** then the returned string holds a copy of zRawSql with "-- " prepended
62149 ** to each line of text.
62150 **
62151 ** The calling function is responsible for making sure the memory returned
62152 ** is eventually freed.
62153 **
62154 ** ALGORITHM:  Scan the input string looking for host parameters in any of
62155 ** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
62156 ** string literals, quoted identifier names, and comments.  For text forms,
62157 ** the host parameter index is found by scanning the perpared
62158 ** statement for the corresponding OP_Variable opcode.  Once the host
62159 ** parameter index is known, locate the value in p->aVar[].  Then render
62160 ** the value as a literal in place of the host parameter name.
62161 */
62162 SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
62163   Vdbe *p,                 /* The prepared statement being evaluated */
62164   const char *zRawSql      /* Raw text of the SQL statement */
62165 ){
62166   sqlite3 *db;             /* The database connection */
62167   int idx = 0;             /* Index of a host parameter */
62168   int nextIndex = 1;       /* Index of next ? host parameter */
62169   int n;                   /* Length of a token prefix */
62170   int nToken;              /* Length of the parameter token */
62171   int i;                   /* Loop counter */
62172   Mem *pVar;               /* Value of a host parameter */
62173   StrAccum out;            /* Accumulate the output here */
62174   char zBase[100];         /* Initial working space */
62175
62176   db = p->db;
62177   sqlite3StrAccumInit(&out, zBase, sizeof(zBase), 
62178                       db->aLimit[SQLITE_LIMIT_LENGTH]);
62179   out.db = db;
62180   if( db->vdbeExecCnt>1 ){
62181     while( *zRawSql ){
62182       const char *zStart = zRawSql;
62183       while( *(zRawSql++)!='\n' && *zRawSql );
62184       sqlite3StrAccumAppend(&out, "-- ", 3);
62185       sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
62186     }
62187   }else{
62188     while( zRawSql[0] ){
62189       n = findNextHostParameter(zRawSql, &nToken);
62190       assert( n>0 );
62191       sqlite3StrAccumAppend(&out, zRawSql, n);
62192       zRawSql += n;
62193       assert( zRawSql[0] || nToken==0 );
62194       if( nToken==0 ) break;
62195       if( zRawSql[0]=='?' ){
62196         if( nToken>1 ){
62197           assert( sqlite3Isdigit(zRawSql[1]) );
62198           sqlite3GetInt32(&zRawSql[1], &idx);
62199         }else{
62200           idx = nextIndex;
62201         }
62202       }else{
62203         assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
62204         testcase( zRawSql[0]==':' );
62205         testcase( zRawSql[0]=='$' );
62206         testcase( zRawSql[0]=='@' );
62207         idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
62208         assert( idx>0 );
62209       }
62210       zRawSql += nToken;
62211       nextIndex = idx + 1;
62212       assert( idx>0 && idx<=p->nVar );
62213       pVar = &p->aVar[idx-1];
62214       if( pVar->flags & MEM_Null ){
62215         sqlite3StrAccumAppend(&out, "NULL", 4);
62216       }else if( pVar->flags & MEM_Int ){
62217         sqlite3XPrintf(&out, "%lld", pVar->u.i);
62218       }else if( pVar->flags & MEM_Real ){
62219         sqlite3XPrintf(&out, "%!.15g", pVar->r);
62220       }else if( pVar->flags & MEM_Str ){
62221 #ifndef SQLITE_OMIT_UTF16
62222         u8 enc = ENC(db);
62223         if( enc!=SQLITE_UTF8 ){
62224           Mem utf8;
62225           memset(&utf8, 0, sizeof(utf8));
62226           utf8.db = db;
62227           sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
62228           sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
62229           sqlite3XPrintf(&out, "'%.*q'", utf8.n, utf8.z);
62230           sqlite3VdbeMemRelease(&utf8);
62231         }else
62232 #endif
62233         {
62234           sqlite3XPrintf(&out, "'%.*q'", pVar->n, pVar->z);
62235         }
62236       }else if( pVar->flags & MEM_Zero ){
62237         sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
62238       }else{
62239         assert( pVar->flags & MEM_Blob );
62240         sqlite3StrAccumAppend(&out, "x'", 2);
62241         for(i=0; i<pVar->n; i++){
62242           sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
62243         }
62244         sqlite3StrAccumAppend(&out, "'", 1);
62245       }
62246     }
62247   }
62248   return sqlite3StrAccumFinish(&out);
62249 }
62250
62251 #endif /* #ifndef SQLITE_OMIT_TRACE */
62252
62253 /************** End of vdbetrace.c *******************************************/
62254 /************** Begin file vdbe.c ********************************************/
62255 /*
62256 ** 2001 September 15
62257 **
62258 ** The author disclaims copyright to this source code.  In place of
62259 ** a legal notice, here is a blessing:
62260 **
62261 **    May you do good and not evil.
62262 **    May you find forgiveness for yourself and forgive others.
62263 **    May you share freely, never taking more than you give.
62264 **
62265 *************************************************************************
62266 ** The code in this file implements execution method of the 
62267 ** Virtual Database Engine (VDBE).  A separate file ("vdbeaux.c")
62268 ** handles housekeeping details such as creating and deleting
62269 ** VDBE instances.  This file is solely interested in executing
62270 ** the VDBE program.
62271 **
62272 ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
62273 ** to a VDBE.
62274 **
62275 ** The SQL parser generates a program which is then executed by
62276 ** the VDBE to do the work of the SQL statement.  VDBE programs are 
62277 ** similar in form to assembly language.  The program consists of
62278 ** a linear sequence of operations.  Each operation has an opcode 
62279 ** and 5 operands.  Operands P1, P2, and P3 are integers.  Operand P4 
62280 ** is a null-terminated string.  Operand P5 is an unsigned character.
62281 ** Few opcodes use all 5 operands.
62282 **
62283 ** Computation results are stored on a set of registers numbered beginning
62284 ** with 1 and going up to Vdbe.nMem.  Each register can store
62285 ** either an integer, a null-terminated string, a floating point
62286 ** number, or the SQL "NULL" value.  An implicit conversion from one
62287 ** type to the other occurs as necessary.
62288 ** 
62289 ** Most of the code in this file is taken up by the sqlite3VdbeExec()
62290 ** function which does the work of interpreting a VDBE program.
62291 ** But other routines are also provided to help in building up
62292 ** a program instruction by instruction.
62293 **
62294 ** Various scripts scan this source file in order to generate HTML
62295 ** documentation, headers files, or other derived files.  The formatting
62296 ** of the code in this file is, therefore, important.  See other comments
62297 ** in this file for details.  If in doubt, do not deviate from existing
62298 ** commenting and indentation practices when changing or adding code.
62299 */
62300
62301 /*
62302 ** Invoke this macro on memory cells just prior to changing the
62303 ** value of the cell.  This macro verifies that shallow copies are
62304 ** not misused.
62305 */
62306 #ifdef SQLITE_DEBUG
62307 # define memAboutToChange(P,M) sqlite3VdbeMemPrepareToChange(P,M)
62308 #else
62309 # define memAboutToChange(P,M)
62310 #endif
62311
62312 /*
62313 ** The following global variable is incremented every time a cursor
62314 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
62315 ** procedures use this information to make sure that indices are
62316 ** working correctly.  This variable has no function other than to
62317 ** help verify the correct operation of the library.
62318 */
62319 #ifdef SQLITE_TEST
62320 SQLITE_API int sqlite3_search_count = 0;
62321 #endif
62322
62323 /*
62324 ** When this global variable is positive, it gets decremented once before
62325 ** each instruction in the VDBE.  When reaches zero, the u1.isInterrupted
62326 ** field of the sqlite3 structure is set in order to simulate and interrupt.
62327 **
62328 ** This facility is used for testing purposes only.  It does not function
62329 ** in an ordinary build.
62330 */
62331 #ifdef SQLITE_TEST
62332 SQLITE_API int sqlite3_interrupt_count = 0;
62333 #endif
62334
62335 /*
62336 ** The next global variable is incremented each type the OP_Sort opcode
62337 ** is executed.  The test procedures use this information to make sure that
62338 ** sorting is occurring or not occurring at appropriate times.   This variable
62339 ** has no function other than to help verify the correct operation of the
62340 ** library.
62341 */
62342 #ifdef SQLITE_TEST
62343 SQLITE_API int sqlite3_sort_count = 0;
62344 #endif
62345
62346 /*
62347 ** The next global variable records the size of the largest MEM_Blob
62348 ** or MEM_Str that has been used by a VDBE opcode.  The test procedures
62349 ** use this information to make sure that the zero-blob functionality
62350 ** is working correctly.   This variable has no function other than to
62351 ** help verify the correct operation of the library.
62352 */
62353 #ifdef SQLITE_TEST
62354 SQLITE_API int sqlite3_max_blobsize = 0;
62355 static void updateMaxBlobsize(Mem *p){
62356   if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
62357     sqlite3_max_blobsize = p->n;
62358   }
62359 }
62360 #endif
62361
62362 /*
62363 ** The next global variable is incremented each type the OP_Found opcode
62364 ** is executed. This is used to test whether or not the foreign key
62365 ** operation implemented using OP_FkIsZero is working. This variable
62366 ** has no function other than to help verify the correct operation of the
62367 ** library.
62368 */
62369 #ifdef SQLITE_TEST
62370 SQLITE_API int sqlite3_found_count = 0;
62371 #endif
62372
62373 /*
62374 ** Test a register to see if it exceeds the current maximum blob size.
62375 ** If it does, record the new maximum blob size.
62376 */
62377 #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
62378 # define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
62379 #else
62380 # define UPDATE_MAX_BLOBSIZE(P)
62381 #endif
62382
62383 /*
62384 ** Convert the given register into a string if it isn't one
62385 ** already. Return non-zero if a malloc() fails.
62386 */
62387 #define Stringify(P, enc) \
62388    if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
62389      { goto no_mem; }
62390
62391 /*
62392 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
62393 ** a pointer to a dynamically allocated string where some other entity
62394 ** is responsible for deallocating that string.  Because the register
62395 ** does not control the string, it might be deleted without the register
62396 ** knowing it.
62397 **
62398 ** This routine converts an ephemeral string into a dynamically allocated
62399 ** string that the register itself controls.  In other words, it
62400 ** converts an MEM_Ephem string into an MEM_Dyn string.
62401 */
62402 #define Deephemeralize(P) \
62403    if( ((P)->flags&MEM_Ephem)!=0 \
62404        && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
62405
62406 /*
62407 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
62408 ** P if required.
62409 */
62410 #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
62411
62412 /*
62413 ** Argument pMem points at a register that will be passed to a
62414 ** user-defined function or returned to the user as the result of a query.
62415 ** This routine sets the pMem->type variable used by the sqlite3_value_*() 
62416 ** routines.
62417 */
62418 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem){
62419   int flags = pMem->flags;
62420   if( flags & MEM_Null ){
62421     pMem->type = SQLITE_NULL;
62422   }
62423   else if( flags & MEM_Int ){
62424     pMem->type = SQLITE_INTEGER;
62425   }
62426   else if( flags & MEM_Real ){
62427     pMem->type = SQLITE_FLOAT;
62428   }
62429   else if( flags & MEM_Str ){
62430     pMem->type = SQLITE_TEXT;
62431   }else{
62432     pMem->type = SQLITE_BLOB;
62433   }
62434 }
62435
62436 /*
62437 ** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
62438 ** if we run out of memory.
62439 */
62440 static VdbeCursor *allocateCursor(
62441   Vdbe *p,              /* The virtual machine */
62442   int iCur,             /* Index of the new VdbeCursor */
62443   int nField,           /* Number of fields in the table or index */
62444   int iDb,              /* When database the cursor belongs to, or -1 */
62445   int isBtreeCursor     /* True for B-Tree.  False for pseudo-table or vtab */
62446 ){
62447   /* Find the memory cell that will be used to store the blob of memory
62448   ** required for this VdbeCursor structure. It is convenient to use a 
62449   ** vdbe memory cell to manage the memory allocation required for a
62450   ** VdbeCursor structure for the following reasons:
62451   **
62452   **   * Sometimes cursor numbers are used for a couple of different
62453   **     purposes in a vdbe program. The different uses might require
62454   **     different sized allocations. Memory cells provide growable
62455   **     allocations.
62456   **
62457   **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
62458   **     be freed lazily via the sqlite3_release_memory() API. This
62459   **     minimizes the number of malloc calls made by the system.
62460   **
62461   ** Memory cells for cursors are allocated at the top of the address
62462   ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
62463   ** cursor 1 is managed by memory cell (p->nMem-1), etc.
62464   */
62465   Mem *pMem = &p->aMem[p->nMem-iCur];
62466
62467   int nByte;
62468   VdbeCursor *pCx = 0;
62469   nByte = 
62470       ROUND8(sizeof(VdbeCursor)) + 
62471       (isBtreeCursor?sqlite3BtreeCursorSize():0) + 
62472       2*nField*sizeof(u32);
62473
62474   assert( iCur<p->nCursor );
62475   if( p->apCsr[iCur] ){
62476     sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
62477     p->apCsr[iCur] = 0;
62478   }
62479   if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
62480     p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
62481     memset(pCx, 0, sizeof(VdbeCursor));
62482     pCx->iDb = iDb;
62483     pCx->nField = nField;
62484     if( nField ){
62485       pCx->aType = (u32 *)&pMem->z[ROUND8(sizeof(VdbeCursor))];
62486     }
62487     if( isBtreeCursor ){
62488       pCx->pCursor = (BtCursor*)
62489           &pMem->z[ROUND8(sizeof(VdbeCursor))+2*nField*sizeof(u32)];
62490       sqlite3BtreeCursorZero(pCx->pCursor);
62491     }
62492   }
62493   return pCx;
62494 }
62495
62496 /*
62497 ** Try to convert a value into a numeric representation if we can
62498 ** do so without loss of information.  In other words, if the string
62499 ** looks like a number, convert it into a number.  If it does not
62500 ** look like a number, leave it alone.
62501 */
62502 static void applyNumericAffinity(Mem *pRec){
62503   if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
62504     double rValue;
62505     i64 iValue;
62506     u8 enc = pRec->enc;
62507     if( (pRec->flags&MEM_Str)==0 ) return;
62508     if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
62509     if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
62510       pRec->u.i = iValue;
62511       pRec->flags |= MEM_Int;
62512     }else{
62513       pRec->r = rValue;
62514       pRec->flags |= MEM_Real;
62515     }
62516   }
62517 }
62518
62519 /*
62520 ** Processing is determine by the affinity parameter:
62521 **
62522 ** SQLITE_AFF_INTEGER:
62523 ** SQLITE_AFF_REAL:
62524 ** SQLITE_AFF_NUMERIC:
62525 **    Try to convert pRec to an integer representation or a 
62526 **    floating-point representation if an integer representation
62527 **    is not possible.  Note that the integer representation is
62528 **    always preferred, even if the affinity is REAL, because
62529 **    an integer representation is more space efficient on disk.
62530 **
62531 ** SQLITE_AFF_TEXT:
62532 **    Convert pRec to a text representation.
62533 **
62534 ** SQLITE_AFF_NONE:
62535 **    No-op.  pRec is unchanged.
62536 */
62537 static void applyAffinity(
62538   Mem *pRec,          /* The value to apply affinity to */
62539   char affinity,      /* The affinity to be applied */
62540   u8 enc              /* Use this text encoding */
62541 ){
62542   if( affinity==SQLITE_AFF_TEXT ){
62543     /* Only attempt the conversion to TEXT if there is an integer or real
62544     ** representation (blob and NULL do not get converted) but no string
62545     ** representation.
62546     */
62547     if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
62548       sqlite3VdbeMemStringify(pRec, enc);
62549     }
62550     pRec->flags &= ~(MEM_Real|MEM_Int);
62551   }else if( affinity!=SQLITE_AFF_NONE ){
62552     assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
62553              || affinity==SQLITE_AFF_NUMERIC );
62554     applyNumericAffinity(pRec);
62555     if( pRec->flags & MEM_Real ){
62556       sqlite3VdbeIntegerAffinity(pRec);
62557     }
62558   }
62559 }
62560
62561 /*
62562 ** Try to convert the type of a function argument or a result column
62563 ** into a numeric representation.  Use either INTEGER or REAL whichever
62564 ** is appropriate.  But only do the conversion if it is possible without
62565 ** loss of information and return the revised type of the argument.
62566 */
62567 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
62568   Mem *pMem = (Mem*)pVal;
62569   if( pMem->type==SQLITE_TEXT ){
62570     applyNumericAffinity(pMem);
62571     sqlite3VdbeMemStoreType(pMem);
62572   }
62573   return pMem->type;
62574 }
62575
62576 /*
62577 ** Exported version of applyAffinity(). This one works on sqlite3_value*, 
62578 ** not the internal Mem* type.
62579 */
62580 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
62581   sqlite3_value *pVal, 
62582   u8 affinity, 
62583   u8 enc
62584 ){
62585   applyAffinity((Mem *)pVal, affinity, enc);
62586 }
62587
62588 #ifdef SQLITE_DEBUG
62589 /*
62590 ** Write a nice string representation of the contents of cell pMem
62591 ** into buffer zBuf, length nBuf.
62592 */
62593 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
62594   char *zCsr = zBuf;
62595   int f = pMem->flags;
62596
62597   static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
62598
62599   if( f&MEM_Blob ){
62600     int i;
62601     char c;
62602     if( f & MEM_Dyn ){
62603       c = 'z';
62604       assert( (f & (MEM_Static|MEM_Ephem))==0 );
62605     }else if( f & MEM_Static ){
62606       c = 't';
62607       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
62608     }else if( f & MEM_Ephem ){
62609       c = 'e';
62610       assert( (f & (MEM_Static|MEM_Dyn))==0 );
62611     }else{
62612       c = 's';
62613     }
62614
62615     sqlite3_snprintf(100, zCsr, "%c", c);
62616     zCsr += sqlite3Strlen30(zCsr);
62617     sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
62618     zCsr += sqlite3Strlen30(zCsr);
62619     for(i=0; i<16 && i<pMem->n; i++){
62620       sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
62621       zCsr += sqlite3Strlen30(zCsr);
62622     }
62623     for(i=0; i<16 && i<pMem->n; i++){
62624       char z = pMem->z[i];
62625       if( z<32 || z>126 ) *zCsr++ = '.';
62626       else *zCsr++ = z;
62627     }
62628
62629     sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
62630     zCsr += sqlite3Strlen30(zCsr);
62631     if( f & MEM_Zero ){
62632       sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
62633       zCsr += sqlite3Strlen30(zCsr);
62634     }
62635     *zCsr = '\0';
62636   }else if( f & MEM_Str ){
62637     int j, k;
62638     zBuf[0] = ' ';
62639     if( f & MEM_Dyn ){
62640       zBuf[1] = 'z';
62641       assert( (f & (MEM_Static|MEM_Ephem))==0 );
62642     }else if( f & MEM_Static ){
62643       zBuf[1] = 't';
62644       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
62645     }else if( f & MEM_Ephem ){
62646       zBuf[1] = 'e';
62647       assert( (f & (MEM_Static|MEM_Dyn))==0 );
62648     }else{
62649       zBuf[1] = 's';
62650     }
62651     k = 2;
62652     sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
62653     k += sqlite3Strlen30(&zBuf[k]);
62654     zBuf[k++] = '[';
62655     for(j=0; j<15 && j<pMem->n; j++){
62656       u8 c = pMem->z[j];
62657       if( c>=0x20 && c<0x7f ){
62658         zBuf[k++] = c;
62659       }else{
62660         zBuf[k++] = '.';
62661       }
62662     }
62663     zBuf[k++] = ']';
62664     sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
62665     k += sqlite3Strlen30(&zBuf[k]);
62666     zBuf[k++] = 0;
62667   }
62668 }
62669 #endif
62670
62671 #ifdef SQLITE_DEBUG
62672 /*
62673 ** Print the value of a register for tracing purposes:
62674 */
62675 static void memTracePrint(FILE *out, Mem *p){
62676   if( p->flags & MEM_Null ){
62677     fprintf(out, " NULL");
62678   }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
62679     fprintf(out, " si:%lld", p->u.i);
62680   }else if( p->flags & MEM_Int ){
62681     fprintf(out, " i:%lld", p->u.i);
62682 #ifndef SQLITE_OMIT_FLOATING_POINT
62683   }else if( p->flags & MEM_Real ){
62684     fprintf(out, " r:%g", p->r);
62685 #endif
62686   }else if( p->flags & MEM_RowSet ){
62687     fprintf(out, " (rowset)");
62688   }else{
62689     char zBuf[200];
62690     sqlite3VdbeMemPrettyPrint(p, zBuf);
62691     fprintf(out, " ");
62692     fprintf(out, "%s", zBuf);
62693   }
62694 }
62695 static void registerTrace(FILE *out, int iReg, Mem *p){
62696   fprintf(out, "REG[%d] = ", iReg);
62697   memTracePrint(out, p);
62698   fprintf(out, "\n");
62699 }
62700 #endif
62701
62702 #ifdef SQLITE_DEBUG
62703 #  define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
62704 #else
62705 #  define REGISTER_TRACE(R,M)
62706 #endif
62707
62708
62709 #ifdef VDBE_PROFILE
62710
62711 /* 
62712 ** hwtime.h contains inline assembler code for implementing 
62713 ** high-performance timing routines.
62714 */
62715 /************** Include hwtime.h in the middle of vdbe.c *********************/
62716 /************** Begin file hwtime.h ******************************************/
62717 /*
62718 ** 2008 May 27
62719 **
62720 ** The author disclaims copyright to this source code.  In place of
62721 ** a legal notice, here is a blessing:
62722 **
62723 **    May you do good and not evil.
62724 **    May you find forgiveness for yourself and forgive others.
62725 **    May you share freely, never taking more than you give.
62726 **
62727 ******************************************************************************
62728 **
62729 ** This file contains inline asm code for retrieving "high-performance"
62730 ** counters for x86 class CPUs.
62731 */
62732 #ifndef _HWTIME_H_
62733 #define _HWTIME_H_
62734
62735 /*
62736 ** The following routine only works on pentium-class (or newer) processors.
62737 ** It uses the RDTSC opcode to read the cycle count value out of the
62738 ** processor and returns that value.  This can be used for high-res
62739 ** profiling.
62740 */
62741 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
62742       (defined(i386) || defined(__i386__) || defined(_M_IX86))
62743
62744   #if defined(__GNUC__)
62745
62746   __inline__ sqlite_uint64 sqlite3Hwtime(void){
62747      unsigned int lo, hi;
62748      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
62749      return (sqlite_uint64)hi << 32 | lo;
62750   }
62751
62752   #elif defined(_MSC_VER)
62753
62754   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
62755      __asm {
62756         rdtsc
62757         ret       ; return value at EDX:EAX
62758      }
62759   }
62760
62761   #endif
62762
62763 #elif (defined(__GNUC__) && defined(__x86_64__))
62764
62765   __inline__ sqlite_uint64 sqlite3Hwtime(void){
62766       unsigned long val;
62767       __asm__ __volatile__ ("rdtsc" : "=A" (val));
62768       return val;
62769   }
62770  
62771 #elif (defined(__GNUC__) && defined(__ppc__))
62772
62773   __inline__ sqlite_uint64 sqlite3Hwtime(void){
62774       unsigned long long retval;
62775       unsigned long junk;
62776       __asm__ __volatile__ ("\n\
62777           1:      mftbu   %1\n\
62778                   mftb    %L0\n\
62779                   mftbu   %0\n\
62780                   cmpw    %0,%1\n\
62781                   bne     1b"
62782                   : "=r" (retval), "=r" (junk));
62783       return retval;
62784   }
62785
62786 #else
62787
62788   #error Need implementation of sqlite3Hwtime() for your platform.
62789
62790   /*
62791   ** To compile without implementing sqlite3Hwtime() for your platform,
62792   ** you can remove the above #error and use the following
62793   ** stub function.  You will lose timing support for many
62794   ** of the debugging and testing utilities, but it should at
62795   ** least compile and run.
62796   */
62797 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
62798
62799 #endif
62800
62801 #endif /* !defined(_HWTIME_H_) */
62802
62803 /************** End of hwtime.h **********************************************/
62804 /************** Continuing where we left off in vdbe.c ***********************/
62805
62806 #endif
62807
62808 /*
62809 ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
62810 ** sqlite3_interrupt() routine has been called.  If it has been, then
62811 ** processing of the VDBE program is interrupted.
62812 **
62813 ** This macro added to every instruction that does a jump in order to
62814 ** implement a loop.  This test used to be on every single instruction,
62815 ** but that meant we more testing that we needed.  By only testing the
62816 ** flag on jump instructions, we get a (small) speed improvement.
62817 */
62818 #define CHECK_FOR_INTERRUPT \
62819    if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
62820
62821
62822 #ifndef NDEBUG
62823 /*
62824 ** This function is only called from within an assert() expression. It
62825 ** checks that the sqlite3.nTransaction variable is correctly set to
62826 ** the number of non-transaction savepoints currently in the 
62827 ** linked list starting at sqlite3.pSavepoint.
62828 ** 
62829 ** Usage:
62830 **
62831 **     assert( checkSavepointCount(db) );
62832 */
62833 static int checkSavepointCount(sqlite3 *db){
62834   int n = 0;
62835   Savepoint *p;
62836   for(p=db->pSavepoint; p; p=p->pNext) n++;
62837   assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
62838   return 1;
62839 }
62840 #endif
62841
62842 /*
62843 ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
62844 ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
62845 ** in memory obtained from sqlite3DbMalloc).
62846 */
62847 static void importVtabErrMsg(Vdbe *p, sqlite3_vtab *pVtab){
62848   sqlite3 *db = p->db;
62849   sqlite3DbFree(db, p->zErrMsg);
62850   p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
62851   sqlite3_free(pVtab->zErrMsg);
62852   pVtab->zErrMsg = 0;
62853 }
62854
62855
62856 /*
62857 ** Execute as much of a VDBE program as we can then return.
62858 **
62859 ** sqlite3VdbeMakeReady() must be called before this routine in order to
62860 ** close the program with a final OP_Halt and to set up the callbacks
62861 ** and the error message pointer.
62862 **
62863 ** Whenever a row or result data is available, this routine will either
62864 ** invoke the result callback (if there is one) or return with
62865 ** SQLITE_ROW.
62866 **
62867 ** If an attempt is made to open a locked database, then this routine
62868 ** will either invoke the busy callback (if there is one) or it will
62869 ** return SQLITE_BUSY.
62870 **
62871 ** If an error occurs, an error message is written to memory obtained
62872 ** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
62873 ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
62874 **
62875 ** If the callback ever returns non-zero, then the program exits
62876 ** immediately.  There will be no error message but the p->rc field is
62877 ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
62878 **
62879 ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
62880 ** routine to return SQLITE_ERROR.
62881 **
62882 ** Other fatal errors return SQLITE_ERROR.
62883 **
62884 ** After this routine has finished, sqlite3VdbeFinalize() should be
62885 ** used to clean up the mess that was left behind.
62886 */
62887 SQLITE_PRIVATE int sqlite3VdbeExec(
62888   Vdbe *p                    /* The VDBE */
62889 ){
62890   int pc=0;                  /* The program counter */
62891   Op *aOp = p->aOp;          /* Copy of p->aOp */
62892   Op *pOp;                   /* Current operation */
62893   int rc = SQLITE_OK;        /* Value to return */
62894   sqlite3 *db = p->db;       /* The database */
62895   u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
62896   u8 encoding = ENC(db);     /* The database encoding */
62897 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
62898   int checkProgress;         /* True if progress callbacks are enabled */
62899   int nProgressOps = 0;      /* Opcodes executed since progress callback. */
62900 #endif
62901   Mem *aMem = p->aMem;       /* Copy of p->aMem */
62902   Mem *pIn1 = 0;             /* 1st input operand */
62903   Mem *pIn2 = 0;             /* 2nd input operand */
62904   Mem *pIn3 = 0;             /* 3rd input operand */
62905   Mem *pOut = 0;             /* Output operand */
62906   int iCompare = 0;          /* Result of last OP_Compare operation */
62907   int *aPermute = 0;         /* Permutation of columns for OP_Compare */
62908   i64 lastRowid = db->lastRowid;  /* Saved value of the last insert ROWID */
62909 #ifdef VDBE_PROFILE
62910   u64 start;                 /* CPU clock count at start of opcode */
62911   int origPc;                /* Program counter at start of opcode */
62912 #endif
62913   /********************************************************************
62914   ** Automatically generated code
62915   **
62916   ** The following union is automatically generated by the
62917   ** vdbe-compress.tcl script.  The purpose of this union is to
62918   ** reduce the amount of stack space required by this function.
62919   ** See comments in the vdbe-compress.tcl script for details.
62920   */
62921   union vdbeExecUnion {
62922     struct OP_Yield_stack_vars {
62923       int pcDest;
62924     } aa;
62925     struct OP_Variable_stack_vars {
62926       Mem *pVar;       /* Value being transferred */
62927     } ab;
62928     struct OP_Move_stack_vars {
62929       char *zMalloc;   /* Holding variable for allocated memory */
62930       int n;           /* Number of registers left to copy */
62931       int p1;          /* Register to copy from */
62932       int p2;          /* Register to copy to */
62933     } ac;
62934     struct OP_ResultRow_stack_vars {
62935       Mem *pMem;
62936       int i;
62937     } ad;
62938     struct OP_Concat_stack_vars {
62939       i64 nByte;
62940     } ae;
62941     struct OP_Remainder_stack_vars {
62942       int flags;      /* Combined MEM_* flags from both inputs */
62943       i64 iA;         /* Integer value of left operand */
62944       i64 iB;         /* Integer value of right operand */
62945       double rA;      /* Real value of left operand */
62946       double rB;      /* Real value of right operand */
62947     } af;
62948     struct OP_Function_stack_vars {
62949       int i;
62950       Mem *pArg;
62951       sqlite3_context ctx;
62952       sqlite3_value **apVal;
62953       int n;
62954     } ag;
62955     struct OP_ShiftRight_stack_vars {
62956       i64 iA;
62957       u64 uA;
62958       i64 iB;
62959       u8 op;
62960     } ah;
62961     struct OP_Ge_stack_vars {
62962       int res;            /* Result of the comparison of pIn1 against pIn3 */
62963       char affinity;      /* Affinity to use for comparison */
62964       u16 flags1;         /* Copy of initial value of pIn1->flags */
62965       u16 flags3;         /* Copy of initial value of pIn3->flags */
62966     } ai;
62967     struct OP_Compare_stack_vars {
62968       int n;
62969       int i;
62970       int p1;
62971       int p2;
62972       const KeyInfo *pKeyInfo;
62973       int idx;
62974       CollSeq *pColl;    /* Collating sequence to use on this term */
62975       int bRev;          /* True for DESCENDING sort order */
62976     } aj;
62977     struct OP_Or_stack_vars {
62978       int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
62979       int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
62980     } ak;
62981     struct OP_IfNot_stack_vars {
62982       int c;
62983     } al;
62984     struct OP_Column_stack_vars {
62985       u32 payloadSize;   /* Number of bytes in the record */
62986       i64 payloadSize64; /* Number of bytes in the record */
62987       int p1;            /* P1 value of the opcode */
62988       int p2;            /* column number to retrieve */
62989       VdbeCursor *pC;    /* The VDBE cursor */
62990       char *zRec;        /* Pointer to complete record-data */
62991       BtCursor *pCrsr;   /* The BTree cursor */
62992       u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
62993       u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
62994       int nField;        /* number of fields in the record */
62995       int len;           /* The length of the serialized data for the column */
62996       int i;             /* Loop counter */
62997       char *zData;       /* Part of the record being decoded */
62998       Mem *pDest;        /* Where to write the extracted value */
62999       Mem sMem;          /* For storing the record being decoded */
63000       u8 *zIdx;          /* Index into header */
63001       u8 *zEndHdr;       /* Pointer to first byte after the header */
63002       u32 offset;        /* Offset into the data */
63003       u32 szField;       /* Number of bytes in the content of a field */
63004       int szHdr;         /* Size of the header size field at start of record */
63005       int avail;         /* Number of bytes of available data */
63006       Mem *pReg;         /* PseudoTable input register */
63007     } am;
63008     struct OP_Affinity_stack_vars {
63009       const char *zAffinity;   /* The affinity to be applied */
63010       char cAff;               /* A single character of affinity */
63011     } an;
63012     struct OP_MakeRecord_stack_vars {
63013       u8 *zNewRecord;        /* A buffer to hold the data for the new record */
63014       Mem *pRec;             /* The new record */
63015       u64 nData;             /* Number of bytes of data space */
63016       int nHdr;              /* Number of bytes of header space */
63017       i64 nByte;             /* Data space required for this record */
63018       int nZero;             /* Number of zero bytes at the end of the record */
63019       int nVarint;           /* Number of bytes in a varint */
63020       u32 serial_type;       /* Type field */
63021       Mem *pData0;           /* First field to be combined into the record */
63022       Mem *pLast;            /* Last field of the record */
63023       int nField;            /* Number of fields in the record */
63024       char *zAffinity;       /* The affinity string for the record */
63025       int file_format;       /* File format to use for encoding */
63026       int i;                 /* Space used in zNewRecord[] */
63027       int len;               /* Length of a field */
63028     } ao;
63029     struct OP_Count_stack_vars {
63030       i64 nEntry;
63031       BtCursor *pCrsr;
63032     } ap;
63033     struct OP_Savepoint_stack_vars {
63034       int p1;                         /* Value of P1 operand */
63035       char *zName;                    /* Name of savepoint */
63036       int nName;
63037       Savepoint *pNew;
63038       Savepoint *pSavepoint;
63039       Savepoint *pTmp;
63040       int iSavepoint;
63041       int ii;
63042     } aq;
63043     struct OP_AutoCommit_stack_vars {
63044       int desiredAutoCommit;
63045       int iRollback;
63046       int turnOnAC;
63047     } ar;
63048     struct OP_Transaction_stack_vars {
63049       Btree *pBt;
63050     } as;
63051     struct OP_ReadCookie_stack_vars {
63052       int iMeta;
63053       int iDb;
63054       int iCookie;
63055     } at;
63056     struct OP_SetCookie_stack_vars {
63057       Db *pDb;
63058     } au;
63059     struct OP_VerifyCookie_stack_vars {
63060       int iMeta;
63061       int iGen;
63062       Btree *pBt;
63063     } av;
63064     struct OP_OpenWrite_stack_vars {
63065       int nField;
63066       KeyInfo *pKeyInfo;
63067       int p2;
63068       int iDb;
63069       int wrFlag;
63070       Btree *pX;
63071       VdbeCursor *pCur;
63072       Db *pDb;
63073     } aw;
63074     struct OP_OpenEphemeral_stack_vars {
63075       VdbeCursor *pCx;
63076     } ax;
63077     struct OP_OpenPseudo_stack_vars {
63078       VdbeCursor *pCx;
63079     } ay;
63080     struct OP_SeekGt_stack_vars {
63081       int res;
63082       int oc;
63083       VdbeCursor *pC;
63084       UnpackedRecord r;
63085       int nField;
63086       i64 iKey;      /* The rowid we are to seek to */
63087     } az;
63088     struct OP_Seek_stack_vars {
63089       VdbeCursor *pC;
63090     } ba;
63091     struct OP_Found_stack_vars {
63092       int alreadyExists;
63093       VdbeCursor *pC;
63094       int res;
63095       UnpackedRecord *pIdxKey;
63096       UnpackedRecord r;
63097       char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
63098     } bb;
63099     struct OP_IsUnique_stack_vars {
63100       u16 ii;
63101       VdbeCursor *pCx;
63102       BtCursor *pCrsr;
63103       u16 nField;
63104       Mem *aMx;
63105       UnpackedRecord r;                  /* B-Tree index search key */
63106       i64 R;                             /* Rowid stored in register P3 */
63107     } bc;
63108     struct OP_NotExists_stack_vars {
63109       VdbeCursor *pC;
63110       BtCursor *pCrsr;
63111       int res;
63112       u64 iKey;
63113     } bd;
63114     struct OP_NewRowid_stack_vars {
63115       i64 v;                 /* The new rowid */
63116       VdbeCursor *pC;        /* Cursor of table to get the new rowid */
63117       int res;               /* Result of an sqlite3BtreeLast() */
63118       int cnt;               /* Counter to limit the number of searches */
63119       Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
63120       VdbeFrame *pFrame;     /* Root frame of VDBE */
63121     } be;
63122     struct OP_InsertInt_stack_vars {
63123       Mem *pData;       /* MEM cell holding data for the record to be inserted */
63124       Mem *pKey;        /* MEM cell holding key  for the record */
63125       i64 iKey;         /* The integer ROWID or key for the record to be inserted */
63126       VdbeCursor *pC;   /* Cursor to table into which insert is written */
63127       int nZero;        /* Number of zero-bytes to append */
63128       int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
63129       const char *zDb;  /* database name - used by the update hook */
63130       const char *zTbl; /* Table name - used by the opdate hook */
63131       int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
63132     } bf;
63133     struct OP_Delete_stack_vars {
63134       i64 iKey;
63135       VdbeCursor *pC;
63136     } bg;
63137     struct OP_RowData_stack_vars {
63138       VdbeCursor *pC;
63139       BtCursor *pCrsr;
63140       u32 n;
63141       i64 n64;
63142     } bh;
63143     struct OP_Rowid_stack_vars {
63144       VdbeCursor *pC;
63145       i64 v;
63146       sqlite3_vtab *pVtab;
63147       const sqlite3_module *pModule;
63148     } bi;
63149     struct OP_NullRow_stack_vars {
63150       VdbeCursor *pC;
63151     } bj;
63152     struct OP_Last_stack_vars {
63153       VdbeCursor *pC;
63154       BtCursor *pCrsr;
63155       int res;
63156     } bk;
63157     struct OP_Rewind_stack_vars {
63158       VdbeCursor *pC;
63159       BtCursor *pCrsr;
63160       int res;
63161     } bl;
63162     struct OP_Next_stack_vars {
63163       VdbeCursor *pC;
63164       BtCursor *pCrsr;
63165       int res;
63166     } bm;
63167     struct OP_IdxInsert_stack_vars {
63168       VdbeCursor *pC;
63169       BtCursor *pCrsr;
63170       int nKey;
63171       const char *zKey;
63172     } bn;
63173     struct OP_IdxDelete_stack_vars {
63174       VdbeCursor *pC;
63175       BtCursor *pCrsr;
63176       int res;
63177       UnpackedRecord r;
63178     } bo;
63179     struct OP_IdxRowid_stack_vars {
63180       BtCursor *pCrsr;
63181       VdbeCursor *pC;
63182       i64 rowid;
63183     } bp;
63184     struct OP_IdxGE_stack_vars {
63185       VdbeCursor *pC;
63186       int res;
63187       UnpackedRecord r;
63188     } bq;
63189     struct OP_Destroy_stack_vars {
63190       int iMoved;
63191       int iCnt;
63192       Vdbe *pVdbe;
63193       int iDb;
63194     } br;
63195     struct OP_Clear_stack_vars {
63196       int nChange;
63197     } bs;
63198     struct OP_CreateTable_stack_vars {
63199       int pgno;
63200       int flags;
63201       Db *pDb;
63202     } bt;
63203     struct OP_ParseSchema_stack_vars {
63204       int iDb;
63205       const char *zMaster;
63206       char *zSql;
63207       InitData initData;
63208     } bu;
63209     struct OP_IntegrityCk_stack_vars {
63210       int nRoot;      /* Number of tables to check.  (Number of root pages.) */
63211       int *aRoot;     /* Array of rootpage numbers for tables to be checked */
63212       int j;          /* Loop counter */
63213       int nErr;       /* Number of errors reported */
63214       char *z;        /* Text of the error report */
63215       Mem *pnErr;     /* Register keeping track of errors remaining */
63216     } bv;
63217     struct OP_RowSetRead_stack_vars {
63218       i64 val;
63219     } bw;
63220     struct OP_RowSetTest_stack_vars {
63221       int iSet;
63222       int exists;
63223     } bx;
63224     struct OP_Program_stack_vars {
63225       int nMem;               /* Number of memory registers for sub-program */
63226       int nByte;              /* Bytes of runtime space required for sub-program */
63227       Mem *pRt;               /* Register to allocate runtime space */
63228       Mem *pMem;              /* Used to iterate through memory cells */
63229       Mem *pEnd;              /* Last memory cell in new array */
63230       VdbeFrame *pFrame;      /* New vdbe frame to execute in */
63231       SubProgram *pProgram;   /* Sub-program to execute */
63232       void *t;                /* Token identifying trigger */
63233     } by;
63234     struct OP_Param_stack_vars {
63235       VdbeFrame *pFrame;
63236       Mem *pIn;
63237     } bz;
63238     struct OP_MemMax_stack_vars {
63239       Mem *pIn1;
63240       VdbeFrame *pFrame;
63241     } ca;
63242     struct OP_AggStep_stack_vars {
63243       int n;
63244       int i;
63245       Mem *pMem;
63246       Mem *pRec;
63247       sqlite3_context ctx;
63248       sqlite3_value **apVal;
63249     } cb;
63250     struct OP_AggFinal_stack_vars {
63251       Mem *pMem;
63252     } cc;
63253     struct OP_Checkpoint_stack_vars {
63254       int i;                          /* Loop counter */
63255       int aRes[3];                    /* Results */
63256       Mem *pMem;                      /* Write results here */
63257     } cd;
63258     struct OP_JournalMode_stack_vars {
63259       Btree *pBt;                     /* Btree to change journal mode of */
63260       Pager *pPager;                  /* Pager associated with pBt */
63261       int eNew;                       /* New journal mode */
63262       int eOld;                       /* The old journal mode */
63263       const char *zFilename;          /* Name of database file for pPager */
63264     } ce;
63265     struct OP_IncrVacuum_stack_vars {
63266       Btree *pBt;
63267     } cf;
63268     struct OP_VBegin_stack_vars {
63269       VTable *pVTab;
63270     } cg;
63271     struct OP_VOpen_stack_vars {
63272       VdbeCursor *pCur;
63273       sqlite3_vtab_cursor *pVtabCursor;
63274       sqlite3_vtab *pVtab;
63275       sqlite3_module *pModule;
63276     } ch;
63277     struct OP_VFilter_stack_vars {
63278       int nArg;
63279       int iQuery;
63280       const sqlite3_module *pModule;
63281       Mem *pQuery;
63282       Mem *pArgc;
63283       sqlite3_vtab_cursor *pVtabCursor;
63284       sqlite3_vtab *pVtab;
63285       VdbeCursor *pCur;
63286       int res;
63287       int i;
63288       Mem **apArg;
63289     } ci;
63290     struct OP_VColumn_stack_vars {
63291       sqlite3_vtab *pVtab;
63292       const sqlite3_module *pModule;
63293       Mem *pDest;
63294       sqlite3_context sContext;
63295     } cj;
63296     struct OP_VNext_stack_vars {
63297       sqlite3_vtab *pVtab;
63298       const sqlite3_module *pModule;
63299       int res;
63300       VdbeCursor *pCur;
63301     } ck;
63302     struct OP_VRename_stack_vars {
63303       sqlite3_vtab *pVtab;
63304       Mem *pName;
63305     } cl;
63306     struct OP_VUpdate_stack_vars {
63307       sqlite3_vtab *pVtab;
63308       sqlite3_module *pModule;
63309       int nArg;
63310       int i;
63311       sqlite_int64 rowid;
63312       Mem **apArg;
63313       Mem *pX;
63314     } cm;
63315     struct OP_Trace_stack_vars {
63316       char *zTrace;
63317       char *z;
63318     } cn;
63319   } u;
63320   /* End automatically generated code
63321   ********************************************************************/
63322
63323   assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
63324   sqlite3VdbeEnter(p);
63325   if( p->rc==SQLITE_NOMEM ){
63326     /* This happens if a malloc() inside a call to sqlite3_column_text() or
63327     ** sqlite3_column_text16() failed.  */
63328     goto no_mem;
63329   }
63330   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
63331   p->rc = SQLITE_OK;
63332   assert( p->explain==0 );
63333   p->pResultSet = 0;
63334   db->busyHandler.nBusy = 0;
63335   CHECK_FOR_INTERRUPT;
63336   sqlite3VdbeIOTraceSql(p);
63337 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
63338   checkProgress = db->xProgress!=0;
63339 #endif
63340 #ifdef SQLITE_DEBUG
63341   sqlite3BeginBenignMalloc();
63342   if( p->pc==0  && (p->db->flags & SQLITE_VdbeListing)!=0 ){
63343     int i;
63344     printf("VDBE Program Listing:\n");
63345     sqlite3VdbePrintSql(p);
63346     for(i=0; i<p->nOp; i++){
63347       sqlite3VdbePrintOp(stdout, i, &aOp[i]);
63348     }
63349   }
63350   sqlite3EndBenignMalloc();
63351 #endif
63352   for(pc=p->pc; rc==SQLITE_OK; pc++){
63353     assert( pc>=0 && pc<p->nOp );
63354     if( db->mallocFailed ) goto no_mem;
63355 #ifdef VDBE_PROFILE
63356     origPc = pc;
63357     start = sqlite3Hwtime();
63358 #endif
63359     pOp = &aOp[pc];
63360
63361     /* Only allow tracing if SQLITE_DEBUG is defined.
63362     */
63363 #ifdef SQLITE_DEBUG
63364     if( p->trace ){
63365       if( pc==0 ){
63366         printf("VDBE Execution Trace:\n");
63367         sqlite3VdbePrintSql(p);
63368       }
63369       sqlite3VdbePrintOp(p->trace, pc, pOp);
63370     }
63371 #endif
63372       
63373
63374     /* Check to see if we need to simulate an interrupt.  This only happens
63375     ** if we have a special test build.
63376     */
63377 #ifdef SQLITE_TEST
63378     if( sqlite3_interrupt_count>0 ){
63379       sqlite3_interrupt_count--;
63380       if( sqlite3_interrupt_count==0 ){
63381         sqlite3_interrupt(db);
63382       }
63383     }
63384 #endif
63385
63386 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
63387     /* Call the progress callback if it is configured and the required number
63388     ** of VDBE ops have been executed (either since this invocation of
63389     ** sqlite3VdbeExec() or since last time the progress callback was called).
63390     ** If the progress callback returns non-zero, exit the virtual machine with
63391     ** a return code SQLITE_ABORT.
63392     */
63393     if( checkProgress ){
63394       if( db->nProgressOps==nProgressOps ){
63395         int prc;
63396         prc = db->xProgress(db->pProgressArg);
63397         if( prc!=0 ){
63398           rc = SQLITE_INTERRUPT;
63399           goto vdbe_error_halt;
63400         }
63401         nProgressOps = 0;
63402       }
63403       nProgressOps++;
63404     }
63405 #endif
63406
63407     /* On any opcode with the "out2-prerelase" tag, free any
63408     ** external allocations out of mem[p2] and set mem[p2] to be
63409     ** an undefined integer.  Opcodes will either fill in the integer
63410     ** value or convert mem[p2] to a different type.
63411     */
63412     assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
63413     if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
63414       assert( pOp->p2>0 );
63415       assert( pOp->p2<=p->nMem );
63416       pOut = &aMem[pOp->p2];
63417       memAboutToChange(p, pOut);
63418       sqlite3VdbeMemReleaseExternal(pOut);
63419       pOut->flags = MEM_Int;
63420     }
63421
63422     /* Sanity checking on other operands */
63423 #ifdef SQLITE_DEBUG
63424     if( (pOp->opflags & OPFLG_IN1)!=0 ){
63425       assert( pOp->p1>0 );
63426       assert( pOp->p1<=p->nMem );
63427       assert( memIsValid(&aMem[pOp->p1]) );
63428       REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
63429     }
63430     if( (pOp->opflags & OPFLG_IN2)!=0 ){
63431       assert( pOp->p2>0 );
63432       assert( pOp->p2<=p->nMem );
63433       assert( memIsValid(&aMem[pOp->p2]) );
63434       REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
63435     }
63436     if( (pOp->opflags & OPFLG_IN3)!=0 ){
63437       assert( pOp->p3>0 );
63438       assert( pOp->p3<=p->nMem );
63439       assert( memIsValid(&aMem[pOp->p3]) );
63440       REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
63441     }
63442     if( (pOp->opflags & OPFLG_OUT2)!=0 ){
63443       assert( pOp->p2>0 );
63444       assert( pOp->p2<=p->nMem );
63445       memAboutToChange(p, &aMem[pOp->p2]);
63446     }
63447     if( (pOp->opflags & OPFLG_OUT3)!=0 ){
63448       assert( pOp->p3>0 );
63449       assert( pOp->p3<=p->nMem );
63450       memAboutToChange(p, &aMem[pOp->p3]);
63451     }
63452 #endif
63453   
63454     switch( pOp->opcode ){
63455
63456 /*****************************************************************************
63457 ** What follows is a massive switch statement where each case implements a
63458 ** separate instruction in the virtual machine.  If we follow the usual
63459 ** indentation conventions, each case should be indented by 6 spaces.  But
63460 ** that is a lot of wasted space on the left margin.  So the code within
63461 ** the switch statement will break with convention and be flush-left. Another
63462 ** big comment (similar to this one) will mark the point in the code where
63463 ** we transition back to normal indentation.
63464 **
63465 ** The formatting of each case is important.  The makefile for SQLite
63466 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
63467 ** file looking for lines that begin with "case OP_".  The opcodes.h files
63468 ** will be filled with #defines that give unique integer values to each
63469 ** opcode and the opcodes.c file is filled with an array of strings where
63470 ** each string is the symbolic name for the corresponding opcode.  If the
63471 ** case statement is followed by a comment of the form "/# same as ... #/"
63472 ** that comment is used to determine the particular value of the opcode.
63473 **
63474 ** Other keywords in the comment that follows each case are used to
63475 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
63476 ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3.  See
63477 ** the mkopcodeh.awk script for additional information.
63478 **
63479 ** Documentation about VDBE opcodes is generated by scanning this file
63480 ** for lines of that contain "Opcode:".  That line and all subsequent
63481 ** comment lines are used in the generation of the opcode.html documentation
63482 ** file.
63483 **
63484 ** SUMMARY:
63485 **
63486 **     Formatting is important to scripts that scan this file.
63487 **     Do not deviate from the formatting style currently in use.
63488 **
63489 *****************************************************************************/
63490
63491 /* Opcode:  Goto * P2 * * *
63492 **
63493 ** An unconditional jump to address P2.
63494 ** The next instruction executed will be 
63495 ** the one at index P2 from the beginning of
63496 ** the program.
63497 */
63498 case OP_Goto: {             /* jump */
63499   CHECK_FOR_INTERRUPT;
63500   pc = pOp->p2 - 1;
63501   break;
63502 }
63503
63504 /* Opcode:  Gosub P1 P2 * * *
63505 **
63506 ** Write the current address onto register P1
63507 ** and then jump to address P2.
63508 */
63509 case OP_Gosub: {            /* jump, in1 */
63510   pIn1 = &aMem[pOp->p1];
63511   assert( (pIn1->flags & MEM_Dyn)==0 );
63512   memAboutToChange(p, pIn1);
63513   pIn1->flags = MEM_Int;
63514   pIn1->u.i = pc;
63515   REGISTER_TRACE(pOp->p1, pIn1);
63516   pc = pOp->p2 - 1;
63517   break;
63518 }
63519
63520 /* Opcode:  Return P1 * * * *
63521 **
63522 ** Jump to the next instruction after the address in register P1.
63523 */
63524 case OP_Return: {           /* in1 */
63525   pIn1 = &aMem[pOp->p1];
63526   assert( pIn1->flags & MEM_Int );
63527   pc = (int)pIn1->u.i;
63528   break;
63529 }
63530
63531 /* Opcode:  Yield P1 * * * *
63532 **
63533 ** Swap the program counter with the value in register P1.
63534 */
63535 case OP_Yield: {            /* in1 */
63536 #if 0  /* local variables moved into u.aa */
63537   int pcDest;
63538 #endif /* local variables moved into u.aa */
63539   pIn1 = &aMem[pOp->p1];
63540   assert( (pIn1->flags & MEM_Dyn)==0 );
63541   pIn1->flags = MEM_Int;
63542   u.aa.pcDest = (int)pIn1->u.i;
63543   pIn1->u.i = pc;
63544   REGISTER_TRACE(pOp->p1, pIn1);
63545   pc = u.aa.pcDest;
63546   break;
63547 }
63548
63549 /* Opcode:  HaltIfNull  P1 P2 P3 P4 *
63550 **
63551 ** Check the value in register P3.  If it is NULL then Halt using
63552 ** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
63553 ** value in register P3 is not NULL, then this routine is a no-op.
63554 */
63555 case OP_HaltIfNull: {      /* in3 */
63556   pIn3 = &aMem[pOp->p3];
63557   if( (pIn3->flags & MEM_Null)==0 ) break;
63558   /* Fall through into OP_Halt */
63559 }
63560
63561 /* Opcode:  Halt P1 P2 * P4 *
63562 **
63563 ** Exit immediately.  All open cursors, etc are closed
63564 ** automatically.
63565 **
63566 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
63567 ** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
63568 ** For errors, it can be some other value.  If P1!=0 then P2 will determine
63569 ** whether or not to rollback the current transaction.  Do not rollback
63570 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
63571 ** then back out all changes that have occurred during this execution of the
63572 ** VDBE, but do not rollback the transaction. 
63573 **
63574 ** If P4 is not null then it is an error message string.
63575 **
63576 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
63577 ** every program.  So a jump past the last instruction of the program
63578 ** is the same as executing Halt.
63579 */
63580 case OP_Halt: {
63581   if( pOp->p1==SQLITE_OK && p->pFrame ){
63582     /* Halt the sub-program. Return control to the parent frame. */
63583     VdbeFrame *pFrame = p->pFrame;
63584     p->pFrame = pFrame->pParent;
63585     p->nFrame--;
63586     sqlite3VdbeSetChanges(db, p->nChange);
63587     pc = sqlite3VdbeFrameRestore(pFrame);
63588     lastRowid = db->lastRowid;
63589     if( pOp->p2==OE_Ignore ){
63590       /* Instruction pc is the OP_Program that invoked the sub-program 
63591       ** currently being halted. If the p2 instruction of this OP_Halt
63592       ** instruction is set to OE_Ignore, then the sub-program is throwing
63593       ** an IGNORE exception. In this case jump to the address specified
63594       ** as the p2 of the calling OP_Program.  */
63595       pc = p->aOp[pc].p2-1;
63596     }
63597     aOp = p->aOp;
63598     aMem = p->aMem;
63599     break;
63600   }
63601
63602   p->rc = pOp->p1;
63603   p->errorAction = (u8)pOp->p2;
63604   p->pc = pc;
63605   if( pOp->p4.z ){
63606     assert( p->rc!=SQLITE_OK );
63607     sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
63608     testcase( sqlite3GlobalConfig.xLog!=0 );
63609     sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pc, p->zSql, pOp->p4.z);
63610   }else if( p->rc ){
63611     testcase( sqlite3GlobalConfig.xLog!=0 );
63612     sqlite3_log(pOp->p1, "constraint failed at %d in [%s]", pc, p->zSql);
63613   }
63614   rc = sqlite3VdbeHalt(p);
63615   assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
63616   if( rc==SQLITE_BUSY ){
63617     p->rc = rc = SQLITE_BUSY;
63618   }else{
63619     assert( rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT );
63620     assert( rc==SQLITE_OK || db->nDeferredCons>0 );
63621     rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
63622   }
63623   goto vdbe_return;
63624 }
63625
63626 /* Opcode: Integer P1 P2 * * *
63627 **
63628 ** The 32-bit integer value P1 is written into register P2.
63629 */
63630 case OP_Integer: {         /* out2-prerelease */
63631   pOut->u.i = pOp->p1;
63632   break;
63633 }
63634
63635 /* Opcode: Int64 * P2 * P4 *
63636 **
63637 ** P4 is a pointer to a 64-bit integer value.
63638 ** Write that value into register P2.
63639 */
63640 case OP_Int64: {           /* out2-prerelease */
63641   assert( pOp->p4.pI64!=0 );
63642   pOut->u.i = *pOp->p4.pI64;
63643   break;
63644 }
63645
63646 #ifndef SQLITE_OMIT_FLOATING_POINT
63647 /* Opcode: Real * P2 * P4 *
63648 **
63649 ** P4 is a pointer to a 64-bit floating point value.
63650 ** Write that value into register P2.
63651 */
63652 case OP_Real: {            /* same as TK_FLOAT, out2-prerelease */
63653   pOut->flags = MEM_Real;
63654   assert( !sqlite3IsNaN(*pOp->p4.pReal) );
63655   pOut->r = *pOp->p4.pReal;
63656   break;
63657 }
63658 #endif
63659
63660 /* Opcode: String8 * P2 * P4 *
63661 **
63662 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed 
63663 ** into an OP_String before it is executed for the first time.
63664 */
63665 case OP_String8: {         /* same as TK_STRING, out2-prerelease */
63666   assert( pOp->p4.z!=0 );
63667   pOp->opcode = OP_String;
63668   pOp->p1 = sqlite3Strlen30(pOp->p4.z);
63669
63670 #ifndef SQLITE_OMIT_UTF16
63671   if( encoding!=SQLITE_UTF8 ){
63672     rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
63673     if( rc==SQLITE_TOOBIG ) goto too_big;
63674     if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
63675     assert( pOut->zMalloc==pOut->z );
63676     assert( pOut->flags & MEM_Dyn );
63677     pOut->zMalloc = 0;
63678     pOut->flags |= MEM_Static;
63679     pOut->flags &= ~MEM_Dyn;
63680     if( pOp->p4type==P4_DYNAMIC ){
63681       sqlite3DbFree(db, pOp->p4.z);
63682     }
63683     pOp->p4type = P4_DYNAMIC;
63684     pOp->p4.z = pOut->z;
63685     pOp->p1 = pOut->n;
63686   }
63687 #endif
63688   if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
63689     goto too_big;
63690   }
63691   /* Fall through to the next case, OP_String */
63692 }
63693   
63694 /* Opcode: String P1 P2 * P4 *
63695 **
63696 ** The string value P4 of length P1 (bytes) is stored in register P2.
63697 */
63698 case OP_String: {          /* out2-prerelease */
63699   assert( pOp->p4.z!=0 );
63700   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
63701   pOut->z = pOp->p4.z;
63702   pOut->n = pOp->p1;
63703   pOut->enc = encoding;
63704   UPDATE_MAX_BLOBSIZE(pOut);
63705   break;
63706 }
63707
63708 /* Opcode: Null * P2 * * *
63709 **
63710 ** Write a NULL into register P2.
63711 */
63712 case OP_Null: {           /* out2-prerelease */
63713   pOut->flags = MEM_Null;
63714   break;
63715 }
63716
63717
63718 /* Opcode: Blob P1 P2 * P4
63719 **
63720 ** P4 points to a blob of data P1 bytes long.  Store this
63721 ** blob in register P2.
63722 */
63723 case OP_Blob: {                /* out2-prerelease */
63724   assert( pOp->p1 <= SQLITE_MAX_LENGTH );
63725   sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
63726   pOut->enc = encoding;
63727   UPDATE_MAX_BLOBSIZE(pOut);
63728   break;
63729 }
63730
63731 /* Opcode: Variable P1 P2 * P4 *
63732 **
63733 ** Transfer the values of bound parameter P1 into register P2
63734 **
63735 ** If the parameter is named, then its name appears in P4 and P3==1.
63736 ** The P4 value is used by sqlite3_bind_parameter_name().
63737 */
63738 case OP_Variable: {            /* out2-prerelease */
63739 #if 0  /* local variables moved into u.ab */
63740   Mem *pVar;       /* Value being transferred */
63741 #endif /* local variables moved into u.ab */
63742
63743   assert( pOp->p1>0 && pOp->p1<=p->nVar );
63744   assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
63745   u.ab.pVar = &p->aVar[pOp->p1 - 1];
63746   if( sqlite3VdbeMemTooBig(u.ab.pVar) ){
63747     goto too_big;
63748   }
63749   sqlite3VdbeMemShallowCopy(pOut, u.ab.pVar, MEM_Static);
63750   UPDATE_MAX_BLOBSIZE(pOut);
63751   break;
63752 }
63753
63754 /* Opcode: Move P1 P2 P3 * *
63755 **
63756 ** Move the values in register P1..P1+P3-1 over into
63757 ** registers P2..P2+P3-1.  Registers P1..P1+P1-1 are
63758 ** left holding a NULL.  It is an error for register ranges
63759 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap.
63760 */
63761 case OP_Move: {
63762 #if 0  /* local variables moved into u.ac */
63763   char *zMalloc;   /* Holding variable for allocated memory */
63764   int n;           /* Number of registers left to copy */
63765   int p1;          /* Register to copy from */
63766   int p2;          /* Register to copy to */
63767 #endif /* local variables moved into u.ac */
63768
63769   u.ac.n = pOp->p3;
63770   u.ac.p1 = pOp->p1;
63771   u.ac.p2 = pOp->p2;
63772   assert( u.ac.n>0 && u.ac.p1>0 && u.ac.p2>0 );
63773   assert( u.ac.p1+u.ac.n<=u.ac.p2 || u.ac.p2+u.ac.n<=u.ac.p1 );
63774
63775   pIn1 = &aMem[u.ac.p1];
63776   pOut = &aMem[u.ac.p2];
63777   while( u.ac.n-- ){
63778     assert( pOut<=&aMem[p->nMem] );
63779     assert( pIn1<=&aMem[p->nMem] );
63780     assert( memIsValid(pIn1) );
63781     memAboutToChange(p, pOut);
63782     u.ac.zMalloc = pOut->zMalloc;
63783     pOut->zMalloc = 0;
63784     sqlite3VdbeMemMove(pOut, pIn1);
63785     pIn1->zMalloc = u.ac.zMalloc;
63786     REGISTER_TRACE(u.ac.p2++, pOut);
63787     pIn1++;
63788     pOut++;
63789   }
63790   break;
63791 }
63792
63793 /* Opcode: Copy P1 P2 * * *
63794 **
63795 ** Make a copy of register P1 into register P2.
63796 **
63797 ** This instruction makes a deep copy of the value.  A duplicate
63798 ** is made of any string or blob constant.  See also OP_SCopy.
63799 */
63800 case OP_Copy: {             /* in1, out2 */
63801   pIn1 = &aMem[pOp->p1];
63802   pOut = &aMem[pOp->p2];
63803   assert( pOut!=pIn1 );
63804   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
63805   Deephemeralize(pOut);
63806   REGISTER_TRACE(pOp->p2, pOut);
63807   break;
63808 }
63809
63810 /* Opcode: SCopy P1 P2 * * *
63811 **
63812 ** Make a shallow copy of register P1 into register P2.
63813 **
63814 ** This instruction makes a shallow copy of the value.  If the value
63815 ** is a string or blob, then the copy is only a pointer to the
63816 ** original and hence if the original changes so will the copy.
63817 ** Worse, if the original is deallocated, the copy becomes invalid.
63818 ** Thus the program must guarantee that the original will not change
63819 ** during the lifetime of the copy.  Use OP_Copy to make a complete
63820 ** copy.
63821 */
63822 case OP_SCopy: {            /* in1, out2 */
63823   pIn1 = &aMem[pOp->p1];
63824   pOut = &aMem[pOp->p2];
63825   assert( pOut!=pIn1 );
63826   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
63827 #ifdef SQLITE_DEBUG
63828   if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
63829 #endif
63830   REGISTER_TRACE(pOp->p2, pOut);
63831   break;
63832 }
63833
63834 /* Opcode: ResultRow P1 P2 * * *
63835 **
63836 ** The registers P1 through P1+P2-1 contain a single row of
63837 ** results. This opcode causes the sqlite3_step() call to terminate
63838 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
63839 ** structure to provide access to the top P1 values as the result
63840 ** row.
63841 */
63842 case OP_ResultRow: {
63843 #if 0  /* local variables moved into u.ad */
63844   Mem *pMem;
63845   int i;
63846 #endif /* local variables moved into u.ad */
63847   assert( p->nResColumn==pOp->p2 );
63848   assert( pOp->p1>0 );
63849   assert( pOp->p1+pOp->p2<=p->nMem+1 );
63850
63851   /* If this statement has violated immediate foreign key constraints, do
63852   ** not return the number of rows modified. And do not RELEASE the statement
63853   ** transaction. It needs to be rolled back.  */
63854   if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
63855     assert( db->flags&SQLITE_CountRows );
63856     assert( p->usesStmtJournal );
63857     break;
63858   }
63859
63860   /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
63861   ** DML statements invoke this opcode to return the number of rows
63862   ** modified to the user. This is the only way that a VM that
63863   ** opens a statement transaction may invoke this opcode.
63864   **
63865   ** In case this is such a statement, close any statement transaction
63866   ** opened by this VM before returning control to the user. This is to
63867   ** ensure that statement-transactions are always nested, not overlapping.
63868   ** If the open statement-transaction is not closed here, then the user
63869   ** may step another VM that opens its own statement transaction. This
63870   ** may lead to overlapping statement transactions.
63871   **
63872   ** The statement transaction is never a top-level transaction.  Hence
63873   ** the RELEASE call below can never fail.
63874   */
63875   assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
63876   rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
63877   if( NEVER(rc!=SQLITE_OK) ){
63878     break;
63879   }
63880
63881   /* Invalidate all ephemeral cursor row caches */
63882   p->cacheCtr = (p->cacheCtr + 2)|1;
63883
63884   /* Make sure the results of the current row are \000 terminated
63885   ** and have an assigned type.  The results are de-ephemeralized as
63886   ** as side effect.
63887   */
63888   u.ad.pMem = p->pResultSet = &aMem[pOp->p1];
63889   for(u.ad.i=0; u.ad.i<pOp->p2; u.ad.i++){
63890     assert( memIsValid(&u.ad.pMem[u.ad.i]) );
63891     Deephemeralize(&u.ad.pMem[u.ad.i]);
63892     assert( (u.ad.pMem[u.ad.i].flags & MEM_Ephem)==0
63893             || (u.ad.pMem[u.ad.i].flags & (MEM_Str|MEM_Blob))==0 );
63894     sqlite3VdbeMemNulTerminate(&u.ad.pMem[u.ad.i]);
63895     sqlite3VdbeMemStoreType(&u.ad.pMem[u.ad.i]);
63896     REGISTER_TRACE(pOp->p1+u.ad.i, &u.ad.pMem[u.ad.i]);
63897   }
63898   if( db->mallocFailed ) goto no_mem;
63899
63900   /* Return SQLITE_ROW
63901   */
63902   p->pc = pc + 1;
63903   rc = SQLITE_ROW;
63904   goto vdbe_return;
63905 }
63906
63907 /* Opcode: Concat P1 P2 P3 * *
63908 **
63909 ** Add the text in register P1 onto the end of the text in
63910 ** register P2 and store the result in register P3.
63911 ** If either the P1 or P2 text are NULL then store NULL in P3.
63912 **
63913 **   P3 = P2 || P1
63914 **
63915 ** It is illegal for P1 and P3 to be the same register. Sometimes,
63916 ** if P3 is the same register as P2, the implementation is able
63917 ** to avoid a memcpy().
63918 */
63919 case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
63920 #if 0  /* local variables moved into u.ae */
63921   i64 nByte;
63922 #endif /* local variables moved into u.ae */
63923
63924   pIn1 = &aMem[pOp->p1];
63925   pIn2 = &aMem[pOp->p2];
63926   pOut = &aMem[pOp->p3];
63927   assert( pIn1!=pOut );
63928   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
63929     sqlite3VdbeMemSetNull(pOut);
63930     break;
63931   }
63932   if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
63933   Stringify(pIn1, encoding);
63934   Stringify(pIn2, encoding);
63935   u.ae.nByte = pIn1->n + pIn2->n;
63936   if( u.ae.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
63937     goto too_big;
63938   }
63939   MemSetTypeFlag(pOut, MEM_Str);
63940   if( sqlite3VdbeMemGrow(pOut, (int)u.ae.nByte+2, pOut==pIn2) ){
63941     goto no_mem;
63942   }
63943   if( pOut!=pIn2 ){
63944     memcpy(pOut->z, pIn2->z, pIn2->n);
63945   }
63946   memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
63947   pOut->z[u.ae.nByte] = 0;
63948   pOut->z[u.ae.nByte+1] = 0;
63949   pOut->flags |= MEM_Term;
63950   pOut->n = (int)u.ae.nByte;
63951   pOut->enc = encoding;
63952   UPDATE_MAX_BLOBSIZE(pOut);
63953   break;
63954 }
63955
63956 /* Opcode: Add P1 P2 P3 * *
63957 **
63958 ** Add the value in register P1 to the value in register P2
63959 ** and store the result in register P3.
63960 ** If either input is NULL, the result is NULL.
63961 */
63962 /* Opcode: Multiply P1 P2 P3 * *
63963 **
63964 **
63965 ** Multiply the value in register P1 by the value in register P2
63966 ** and store the result in register P3.
63967 ** If either input is NULL, the result is NULL.
63968 */
63969 /* Opcode: Subtract P1 P2 P3 * *
63970 **
63971 ** Subtract the value in register P1 from the value in register P2
63972 ** and store the result in register P3.
63973 ** If either input is NULL, the result is NULL.
63974 */
63975 /* Opcode: Divide P1 P2 P3 * *
63976 **
63977 ** Divide the value in register P1 by the value in register P2
63978 ** and store the result in register P3 (P3=P2/P1). If the value in 
63979 ** register P1 is zero, then the result is NULL. If either input is 
63980 ** NULL, the result is NULL.
63981 */
63982 /* Opcode: Remainder P1 P2 P3 * *
63983 **
63984 ** Compute the remainder after integer division of the value in
63985 ** register P1 by the value in register P2 and store the result in P3. 
63986 ** If the value in register P2 is zero the result is NULL.
63987 ** If either operand is NULL, the result is NULL.
63988 */
63989 case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
63990 case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
63991 case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
63992 case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
63993 case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
63994 #if 0  /* local variables moved into u.af */
63995   int flags;      /* Combined MEM_* flags from both inputs */
63996   i64 iA;         /* Integer value of left operand */
63997   i64 iB;         /* Integer value of right operand */
63998   double rA;      /* Real value of left operand */
63999   double rB;      /* Real value of right operand */
64000 #endif /* local variables moved into u.af */
64001
64002   pIn1 = &aMem[pOp->p1];
64003   applyNumericAffinity(pIn1);
64004   pIn2 = &aMem[pOp->p2];
64005   applyNumericAffinity(pIn2);
64006   pOut = &aMem[pOp->p3];
64007   u.af.flags = pIn1->flags | pIn2->flags;
64008   if( (u.af.flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
64009   if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
64010     u.af.iA = pIn1->u.i;
64011     u.af.iB = pIn2->u.i;
64012     switch( pOp->opcode ){
64013       case OP_Add:       if( sqlite3AddInt64(&u.af.iB,u.af.iA) ) goto fp_math;  break;
64014       case OP_Subtract:  if( sqlite3SubInt64(&u.af.iB,u.af.iA) ) goto fp_math;  break;
64015       case OP_Multiply:  if( sqlite3MulInt64(&u.af.iB,u.af.iA) ) goto fp_math;  break;
64016       case OP_Divide: {
64017         if( u.af.iA==0 ) goto arithmetic_result_is_null;
64018         if( u.af.iA==-1 && u.af.iB==SMALLEST_INT64 ) goto fp_math;
64019         u.af.iB /= u.af.iA;
64020         break;
64021       }
64022       default: {
64023         if( u.af.iA==0 ) goto arithmetic_result_is_null;
64024         if( u.af.iA==-1 ) u.af.iA = 1;
64025         u.af.iB %= u.af.iA;
64026         break;
64027       }
64028     }
64029     pOut->u.i = u.af.iB;
64030     MemSetTypeFlag(pOut, MEM_Int);
64031   }else{
64032 fp_math:
64033     u.af.rA = sqlite3VdbeRealValue(pIn1);
64034     u.af.rB = sqlite3VdbeRealValue(pIn2);
64035     switch( pOp->opcode ){
64036       case OP_Add:         u.af.rB += u.af.rA;       break;
64037       case OP_Subtract:    u.af.rB -= u.af.rA;       break;
64038       case OP_Multiply:    u.af.rB *= u.af.rA;       break;
64039       case OP_Divide: {
64040         /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
64041         if( u.af.rA==(double)0 ) goto arithmetic_result_is_null;
64042         u.af.rB /= u.af.rA;
64043         break;
64044       }
64045       default: {
64046         u.af.iA = (i64)u.af.rA;
64047         u.af.iB = (i64)u.af.rB;
64048         if( u.af.iA==0 ) goto arithmetic_result_is_null;
64049         if( u.af.iA==-1 ) u.af.iA = 1;
64050         u.af.rB = (double)(u.af.iB % u.af.iA);
64051         break;
64052       }
64053     }
64054 #ifdef SQLITE_OMIT_FLOATING_POINT
64055     pOut->u.i = u.af.rB;
64056     MemSetTypeFlag(pOut, MEM_Int);
64057 #else
64058     if( sqlite3IsNaN(u.af.rB) ){
64059       goto arithmetic_result_is_null;
64060     }
64061     pOut->r = u.af.rB;
64062     MemSetTypeFlag(pOut, MEM_Real);
64063     if( (u.af.flags & MEM_Real)==0 ){
64064       sqlite3VdbeIntegerAffinity(pOut);
64065     }
64066 #endif
64067   }
64068   break;
64069
64070 arithmetic_result_is_null:
64071   sqlite3VdbeMemSetNull(pOut);
64072   break;
64073 }
64074
64075 /* Opcode: CollSeq * * P4
64076 **
64077 ** P4 is a pointer to a CollSeq struct. If the next call to a user function
64078 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
64079 ** be returned. This is used by the built-in min(), max() and nullif()
64080 ** functions.
64081 **
64082 ** The interface used by the implementation of the aforementioned functions
64083 ** to retrieve the collation sequence set by this opcode is not available
64084 ** publicly, only to user functions defined in func.c.
64085 */
64086 case OP_CollSeq: {
64087   assert( pOp->p4type==P4_COLLSEQ );
64088   break;
64089 }
64090
64091 /* Opcode: Function P1 P2 P3 P4 P5
64092 **
64093 ** Invoke a user function (P4 is a pointer to a Function structure that
64094 ** defines the function) with P5 arguments taken from register P2 and
64095 ** successors.  The result of the function is stored in register P3.
64096 ** Register P3 must not be one of the function inputs.
64097 **
64098 ** P1 is a 32-bit bitmask indicating whether or not each argument to the 
64099 ** function was determined to be constant at compile time. If the first
64100 ** argument was constant then bit 0 of P1 is set. This is used to determine
64101 ** whether meta data associated with a user function argument using the
64102 ** sqlite3_set_auxdata() API may be safely retained until the next
64103 ** invocation of this opcode.
64104 **
64105 ** See also: AggStep and AggFinal
64106 */
64107 case OP_Function: {
64108 #if 0  /* local variables moved into u.ag */
64109   int i;
64110   Mem *pArg;
64111   sqlite3_context ctx;
64112   sqlite3_value **apVal;
64113   int n;
64114 #endif /* local variables moved into u.ag */
64115
64116   u.ag.n = pOp->p5;
64117   u.ag.apVal = p->apArg;
64118   assert( u.ag.apVal || u.ag.n==0 );
64119   assert( pOp->p3>0 && pOp->p3<=p->nMem );
64120   pOut = &aMem[pOp->p3];
64121   memAboutToChange(p, pOut);
64122
64123   assert( u.ag.n==0 || (pOp->p2>0 && pOp->p2+u.ag.n<=p->nMem+1) );
64124   assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+u.ag.n );
64125   u.ag.pArg = &aMem[pOp->p2];
64126   for(u.ag.i=0; u.ag.i<u.ag.n; u.ag.i++, u.ag.pArg++){
64127     assert( memIsValid(u.ag.pArg) );
64128     u.ag.apVal[u.ag.i] = u.ag.pArg;
64129     Deephemeralize(u.ag.pArg);
64130     sqlite3VdbeMemStoreType(u.ag.pArg);
64131     REGISTER_TRACE(pOp->p2+u.ag.i, u.ag.pArg);
64132   }
64133
64134   assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
64135   if( pOp->p4type==P4_FUNCDEF ){
64136     u.ag.ctx.pFunc = pOp->p4.pFunc;
64137     u.ag.ctx.pVdbeFunc = 0;
64138   }else{
64139     u.ag.ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
64140     u.ag.ctx.pFunc = u.ag.ctx.pVdbeFunc->pFunc;
64141   }
64142
64143   u.ag.ctx.s.flags = MEM_Null;
64144   u.ag.ctx.s.db = db;
64145   u.ag.ctx.s.xDel = 0;
64146   u.ag.ctx.s.zMalloc = 0;
64147
64148   /* The output cell may already have a buffer allocated. Move
64149   ** the pointer to u.ag.ctx.s so in case the user-function can use
64150   ** the already allocated buffer instead of allocating a new one.
64151   */
64152   sqlite3VdbeMemMove(&u.ag.ctx.s, pOut);
64153   MemSetTypeFlag(&u.ag.ctx.s, MEM_Null);
64154
64155   u.ag.ctx.isError = 0;
64156   if( u.ag.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
64157     assert( pOp>aOp );
64158     assert( pOp[-1].p4type==P4_COLLSEQ );
64159     assert( pOp[-1].opcode==OP_CollSeq );
64160     u.ag.ctx.pColl = pOp[-1].p4.pColl;
64161   }
64162   db->lastRowid = lastRowid;
64163   (*u.ag.ctx.pFunc->xFunc)(&u.ag.ctx, u.ag.n, u.ag.apVal); /* IMP: R-24505-23230 */
64164   lastRowid = db->lastRowid;
64165
64166   /* If any auxiliary data functions have been called by this user function,
64167   ** immediately call the destructor for any non-static values.
64168   */
64169   if( u.ag.ctx.pVdbeFunc ){
64170     sqlite3VdbeDeleteAuxData(u.ag.ctx.pVdbeFunc, pOp->p1);
64171     pOp->p4.pVdbeFunc = u.ag.ctx.pVdbeFunc;
64172     pOp->p4type = P4_VDBEFUNC;
64173   }
64174
64175   if( db->mallocFailed ){
64176     /* Even though a malloc() has failed, the implementation of the
64177     ** user function may have called an sqlite3_result_XXX() function
64178     ** to return a value. The following call releases any resources
64179     ** associated with such a value.
64180     */
64181     sqlite3VdbeMemRelease(&u.ag.ctx.s);
64182     goto no_mem;
64183   }
64184
64185   /* If the function returned an error, throw an exception */
64186   if( u.ag.ctx.isError ){
64187     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.ag.ctx.s));
64188     rc = u.ag.ctx.isError;
64189   }
64190
64191   /* Copy the result of the function into register P3 */
64192   sqlite3VdbeChangeEncoding(&u.ag.ctx.s, encoding);
64193   sqlite3VdbeMemMove(pOut, &u.ag.ctx.s);
64194   if( sqlite3VdbeMemTooBig(pOut) ){
64195     goto too_big;
64196   }
64197
64198 #if 0
64199   /* The app-defined function has done something that as caused this
64200   ** statement to expire.  (Perhaps the function called sqlite3_exec()
64201   ** with a CREATE TABLE statement.)
64202   */
64203   if( p->expired ) rc = SQLITE_ABORT;
64204 #endif
64205
64206   REGISTER_TRACE(pOp->p3, pOut);
64207   UPDATE_MAX_BLOBSIZE(pOut);
64208   break;
64209 }
64210
64211 /* Opcode: BitAnd P1 P2 P3 * *
64212 **
64213 ** Take the bit-wise AND of the values in register P1 and P2 and
64214 ** store the result in register P3.
64215 ** If either input is NULL, the result is NULL.
64216 */
64217 /* Opcode: BitOr P1 P2 P3 * *
64218 **
64219 ** Take the bit-wise OR of the values in register P1 and P2 and
64220 ** store the result in register P3.
64221 ** If either input is NULL, the result is NULL.
64222 */
64223 /* Opcode: ShiftLeft P1 P2 P3 * *
64224 **
64225 ** Shift the integer value in register P2 to the left by the
64226 ** number of bits specified by the integer in register P1.
64227 ** Store the result in register P3.
64228 ** If either input is NULL, the result is NULL.
64229 */
64230 /* Opcode: ShiftRight P1 P2 P3 * *
64231 **
64232 ** Shift the integer value in register P2 to the right by the
64233 ** number of bits specified by the integer in register P1.
64234 ** Store the result in register P3.
64235 ** If either input is NULL, the result is NULL.
64236 */
64237 case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
64238 case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
64239 case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
64240 case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
64241 #if 0  /* local variables moved into u.ah */
64242   i64 iA;
64243   u64 uA;
64244   i64 iB;
64245   u8 op;
64246 #endif /* local variables moved into u.ah */
64247
64248   pIn1 = &aMem[pOp->p1];
64249   pIn2 = &aMem[pOp->p2];
64250   pOut = &aMem[pOp->p3];
64251   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
64252     sqlite3VdbeMemSetNull(pOut);
64253     break;
64254   }
64255   u.ah.iA = sqlite3VdbeIntValue(pIn2);
64256   u.ah.iB = sqlite3VdbeIntValue(pIn1);
64257   u.ah.op = pOp->opcode;
64258   if( u.ah.op==OP_BitAnd ){
64259     u.ah.iA &= u.ah.iB;
64260   }else if( u.ah.op==OP_BitOr ){
64261     u.ah.iA |= u.ah.iB;
64262   }else if( u.ah.iB!=0 ){
64263     assert( u.ah.op==OP_ShiftRight || u.ah.op==OP_ShiftLeft );
64264
64265     /* If shifting by a negative amount, shift in the other direction */
64266     if( u.ah.iB<0 ){
64267       assert( OP_ShiftRight==OP_ShiftLeft+1 );
64268       u.ah.op = 2*OP_ShiftLeft + 1 - u.ah.op;
64269       u.ah.iB = u.ah.iB>(-64) ? -u.ah.iB : 64;
64270     }
64271
64272     if( u.ah.iB>=64 ){
64273       u.ah.iA = (u.ah.iA>=0 || u.ah.op==OP_ShiftLeft) ? 0 : -1;
64274     }else{
64275       memcpy(&u.ah.uA, &u.ah.iA, sizeof(u.ah.uA));
64276       if( u.ah.op==OP_ShiftLeft ){
64277         u.ah.uA <<= u.ah.iB;
64278       }else{
64279         u.ah.uA >>= u.ah.iB;
64280         /* Sign-extend on a right shift of a negative number */
64281         if( u.ah.iA<0 ) u.ah.uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-u.ah.iB);
64282       }
64283       memcpy(&u.ah.iA, &u.ah.uA, sizeof(u.ah.iA));
64284     }
64285   }
64286   pOut->u.i = u.ah.iA;
64287   MemSetTypeFlag(pOut, MEM_Int);
64288   break;
64289 }
64290
64291 /* Opcode: AddImm  P1 P2 * * *
64292 ** 
64293 ** Add the constant P2 to the value in register P1.
64294 ** The result is always an integer.
64295 **
64296 ** To force any register to be an integer, just add 0.
64297 */
64298 case OP_AddImm: {            /* in1 */
64299   pIn1 = &aMem[pOp->p1];
64300   memAboutToChange(p, pIn1);
64301   sqlite3VdbeMemIntegerify(pIn1);
64302   pIn1->u.i += pOp->p2;
64303   break;
64304 }
64305
64306 /* Opcode: MustBeInt P1 P2 * * *
64307 ** 
64308 ** Force the value in register P1 to be an integer.  If the value
64309 ** in P1 is not an integer and cannot be converted into an integer
64310 ** without data loss, then jump immediately to P2, or if P2==0
64311 ** raise an SQLITE_MISMATCH exception.
64312 */
64313 case OP_MustBeInt: {            /* jump, in1 */
64314   pIn1 = &aMem[pOp->p1];
64315   applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
64316   if( (pIn1->flags & MEM_Int)==0 ){
64317     if( pOp->p2==0 ){
64318       rc = SQLITE_MISMATCH;
64319       goto abort_due_to_error;
64320     }else{
64321       pc = pOp->p2 - 1;
64322     }
64323   }else{
64324     MemSetTypeFlag(pIn1, MEM_Int);
64325   }
64326   break;
64327 }
64328
64329 #ifndef SQLITE_OMIT_FLOATING_POINT
64330 /* Opcode: RealAffinity P1 * * * *
64331 **
64332 ** If register P1 holds an integer convert it to a real value.
64333 **
64334 ** This opcode is used when extracting information from a column that
64335 ** has REAL affinity.  Such column values may still be stored as
64336 ** integers, for space efficiency, but after extraction we want them
64337 ** to have only a real value.
64338 */
64339 case OP_RealAffinity: {                  /* in1 */
64340   pIn1 = &aMem[pOp->p1];
64341   if( pIn1->flags & MEM_Int ){
64342     sqlite3VdbeMemRealify(pIn1);
64343   }
64344   break;
64345 }
64346 #endif
64347
64348 #ifndef SQLITE_OMIT_CAST
64349 /* Opcode: ToText P1 * * * *
64350 **
64351 ** Force the value in register P1 to be text.
64352 ** If the value is numeric, convert it to a string using the
64353 ** equivalent of printf().  Blob values are unchanged and
64354 ** are afterwards simply interpreted as text.
64355 **
64356 ** A NULL value is not changed by this routine.  It remains NULL.
64357 */
64358 case OP_ToText: {                  /* same as TK_TO_TEXT, in1 */
64359   pIn1 = &aMem[pOp->p1];
64360   memAboutToChange(p, pIn1);
64361   if( pIn1->flags & MEM_Null ) break;
64362   assert( MEM_Str==(MEM_Blob>>3) );
64363   pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
64364   applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
64365   rc = ExpandBlob(pIn1);
64366   assert( pIn1->flags & MEM_Str || db->mallocFailed );
64367   pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
64368   UPDATE_MAX_BLOBSIZE(pIn1);
64369   break;
64370 }
64371
64372 /* Opcode: ToBlob P1 * * * *
64373 **
64374 ** Force the value in register P1 to be a BLOB.
64375 ** If the value is numeric, convert it to a string first.
64376 ** Strings are simply reinterpreted as blobs with no change
64377 ** to the underlying data.
64378 **
64379 ** A NULL value is not changed by this routine.  It remains NULL.
64380 */
64381 case OP_ToBlob: {                  /* same as TK_TO_BLOB, in1 */
64382   pIn1 = &aMem[pOp->p1];
64383   if( pIn1->flags & MEM_Null ) break;
64384   if( (pIn1->flags & MEM_Blob)==0 ){
64385     applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
64386     assert( pIn1->flags & MEM_Str || db->mallocFailed );
64387     MemSetTypeFlag(pIn1, MEM_Blob);
64388   }else{
64389     pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
64390   }
64391   UPDATE_MAX_BLOBSIZE(pIn1);
64392   break;
64393 }
64394
64395 /* Opcode: ToNumeric P1 * * * *
64396 **
64397 ** Force the value in register P1 to be numeric (either an
64398 ** integer or a floating-point number.)
64399 ** If the value is text or blob, try to convert it to an using the
64400 ** equivalent of atoi() or atof() and store 0 if no such conversion 
64401 ** is possible.
64402 **
64403 ** A NULL value is not changed by this routine.  It remains NULL.
64404 */
64405 case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, in1 */
64406   pIn1 = &aMem[pOp->p1];
64407   sqlite3VdbeMemNumerify(pIn1);
64408   break;
64409 }
64410 #endif /* SQLITE_OMIT_CAST */
64411
64412 /* Opcode: ToInt P1 * * * *
64413 **
64414 ** Force the value in register P1 to be an integer.  If
64415 ** The value is currently a real number, drop its fractional part.
64416 ** If the value is text or blob, try to convert it to an integer using the
64417 ** equivalent of atoi() and store 0 if no such conversion is possible.
64418 **
64419 ** A NULL value is not changed by this routine.  It remains NULL.
64420 */
64421 case OP_ToInt: {                  /* same as TK_TO_INT, in1 */
64422   pIn1 = &aMem[pOp->p1];
64423   if( (pIn1->flags & MEM_Null)==0 ){
64424     sqlite3VdbeMemIntegerify(pIn1);
64425   }
64426   break;
64427 }
64428
64429 #if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT)
64430 /* Opcode: ToReal P1 * * * *
64431 **
64432 ** Force the value in register P1 to be a floating point number.
64433 ** If The value is currently an integer, convert it.
64434 ** If the value is text or blob, try to convert it to an integer using the
64435 ** equivalent of atoi() and store 0.0 if no such conversion is possible.
64436 **
64437 ** A NULL value is not changed by this routine.  It remains NULL.
64438 */
64439 case OP_ToReal: {                  /* same as TK_TO_REAL, in1 */
64440   pIn1 = &aMem[pOp->p1];
64441   memAboutToChange(p, pIn1);
64442   if( (pIn1->flags & MEM_Null)==0 ){
64443     sqlite3VdbeMemRealify(pIn1);
64444   }
64445   break;
64446 }
64447 #endif /* !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) */
64448
64449 /* Opcode: Lt P1 P2 P3 P4 P5
64450 **
64451 ** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
64452 ** jump to address P2.  
64453 **
64454 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
64455 ** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL 
64456 ** bit is clear then fall through if either operand is NULL.
64457 **
64458 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
64459 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made 
64460 ** to coerce both inputs according to this affinity before the
64461 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
64462 ** affinity is used. Note that the affinity conversions are stored
64463 ** back into the input registers P1 and P3.  So this opcode can cause
64464 ** persistent changes to registers P1 and P3.
64465 **
64466 ** Once any conversions have taken place, and neither value is NULL, 
64467 ** the values are compared. If both values are blobs then memcmp() is
64468 ** used to determine the results of the comparison.  If both values
64469 ** are text, then the appropriate collating function specified in
64470 ** P4 is  used to do the comparison.  If P4 is not specified then
64471 ** memcmp() is used to compare text string.  If both values are
64472 ** numeric, then a numeric comparison is used. If the two values
64473 ** are of different types, then numbers are considered less than
64474 ** strings and strings are considered less than blobs.
64475 **
64476 ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
64477 ** store a boolean result (either 0, or 1, or NULL) in register P2.
64478 */
64479 /* Opcode: Ne P1 P2 P3 P4 P5
64480 **
64481 ** This works just like the Lt opcode except that the jump is taken if
64482 ** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
64483 ** additional information.
64484 **
64485 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
64486 ** true or false and is never NULL.  If both operands are NULL then the result
64487 ** of comparison is false.  If either operand is NULL then the result is true.
64488 ** If neither operand is NULL the result is the same as it would be if
64489 ** the SQLITE_NULLEQ flag were omitted from P5.
64490 */
64491 /* Opcode: Eq P1 P2 P3 P4 P5
64492 **
64493 ** This works just like the Lt opcode except that the jump is taken if
64494 ** the operands in registers P1 and P3 are equal.
64495 ** See the Lt opcode for additional information.
64496 **
64497 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
64498 ** true or false and is never NULL.  If both operands are NULL then the result
64499 ** of comparison is true.  If either operand is NULL then the result is false.
64500 ** If neither operand is NULL the result is the same as it would be if
64501 ** the SQLITE_NULLEQ flag were omitted from P5.
64502 */
64503 /* Opcode: Le P1 P2 P3 P4 P5
64504 **
64505 ** This works just like the Lt opcode except that the jump is taken if
64506 ** the content of register P3 is less than or equal to the content of
64507 ** register P1.  See the Lt opcode for additional information.
64508 */
64509 /* Opcode: Gt P1 P2 P3 P4 P5
64510 **
64511 ** This works just like the Lt opcode except that the jump is taken if
64512 ** the content of register P3 is greater than the content of
64513 ** register P1.  See the Lt opcode for additional information.
64514 */
64515 /* Opcode: Ge P1 P2 P3 P4 P5
64516 **
64517 ** This works just like the Lt opcode except that the jump is taken if
64518 ** the content of register P3 is greater than or equal to the content of
64519 ** register P1.  See the Lt opcode for additional information.
64520 */
64521 case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
64522 case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
64523 case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
64524 case OP_Le:               /* same as TK_LE, jump, in1, in3 */
64525 case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
64526 case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
64527 #if 0  /* local variables moved into u.ai */
64528   int res;            /* Result of the comparison of pIn1 against pIn3 */
64529   char affinity;      /* Affinity to use for comparison */
64530   u16 flags1;         /* Copy of initial value of pIn1->flags */
64531   u16 flags3;         /* Copy of initial value of pIn3->flags */
64532 #endif /* local variables moved into u.ai */
64533
64534   pIn1 = &aMem[pOp->p1];
64535   pIn3 = &aMem[pOp->p3];
64536   u.ai.flags1 = pIn1->flags;
64537   u.ai.flags3 = pIn3->flags;
64538   if( (u.ai.flags1 | u.ai.flags3)&MEM_Null ){
64539     /* One or both operands are NULL */
64540     if( pOp->p5 & SQLITE_NULLEQ ){
64541       /* If SQLITE_NULLEQ is set (which will only happen if the operator is
64542       ** OP_Eq or OP_Ne) then take the jump or not depending on whether
64543       ** or not both operands are null.
64544       */
64545       assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
64546       u.ai.res = (u.ai.flags1 & u.ai.flags3 & MEM_Null)==0;
64547     }else{
64548       /* SQLITE_NULLEQ is clear and at least one operand is NULL,
64549       ** then the result is always NULL.
64550       ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
64551       */
64552       if( pOp->p5 & SQLITE_STOREP2 ){
64553         pOut = &aMem[pOp->p2];
64554         MemSetTypeFlag(pOut, MEM_Null);
64555         REGISTER_TRACE(pOp->p2, pOut);
64556       }else if( pOp->p5 & SQLITE_JUMPIFNULL ){
64557         pc = pOp->p2-1;
64558       }
64559       break;
64560     }
64561   }else{
64562     /* Neither operand is NULL.  Do a comparison. */
64563     u.ai.affinity = pOp->p5 & SQLITE_AFF_MASK;
64564     if( u.ai.affinity ){
64565       applyAffinity(pIn1, u.ai.affinity, encoding);
64566       applyAffinity(pIn3, u.ai.affinity, encoding);
64567       if( db->mallocFailed ) goto no_mem;
64568     }
64569
64570     assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
64571     ExpandBlob(pIn1);
64572     ExpandBlob(pIn3);
64573     u.ai.res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
64574   }
64575   switch( pOp->opcode ){
64576     case OP_Eq:    u.ai.res = u.ai.res==0;     break;
64577     case OP_Ne:    u.ai.res = u.ai.res!=0;     break;
64578     case OP_Lt:    u.ai.res = u.ai.res<0;      break;
64579     case OP_Le:    u.ai.res = u.ai.res<=0;     break;
64580     case OP_Gt:    u.ai.res = u.ai.res>0;      break;
64581     default:       u.ai.res = u.ai.res>=0;     break;
64582   }
64583
64584   if( pOp->p5 & SQLITE_STOREP2 ){
64585     pOut = &aMem[pOp->p2];
64586     memAboutToChange(p, pOut);
64587     MemSetTypeFlag(pOut, MEM_Int);
64588     pOut->u.i = u.ai.res;
64589     REGISTER_TRACE(pOp->p2, pOut);
64590   }else if( u.ai.res ){
64591     pc = pOp->p2-1;
64592   }
64593
64594   /* Undo any changes made by applyAffinity() to the input registers. */
64595   pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (u.ai.flags1&MEM_TypeMask);
64596   pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (u.ai.flags3&MEM_TypeMask);
64597   break;
64598 }
64599
64600 /* Opcode: Permutation * * * P4 *
64601 **
64602 ** Set the permutation used by the OP_Compare operator to be the array
64603 ** of integers in P4.
64604 **
64605 ** The permutation is only valid until the next OP_Permutation, OP_Compare,
64606 ** OP_Halt, or OP_ResultRow.  Typically the OP_Permutation should occur
64607 ** immediately prior to the OP_Compare.
64608 */
64609 case OP_Permutation: {
64610   assert( pOp->p4type==P4_INTARRAY );
64611   assert( pOp->p4.ai );
64612   aPermute = pOp->p4.ai;
64613   break;
64614 }
64615
64616 /* Opcode: Compare P1 P2 P3 P4 *
64617 **
64618 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
64619 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
64620 ** the comparison for use by the next OP_Jump instruct.
64621 **
64622 ** P4 is a KeyInfo structure that defines collating sequences and sort
64623 ** orders for the comparison.  The permutation applies to registers
64624 ** only.  The KeyInfo elements are used sequentially.
64625 **
64626 ** The comparison is a sort comparison, so NULLs compare equal,
64627 ** NULLs are less than numbers, numbers are less than strings,
64628 ** and strings are less than blobs.
64629 */
64630 case OP_Compare: {
64631 #if 0  /* local variables moved into u.aj */
64632   int n;
64633   int i;
64634   int p1;
64635   int p2;
64636   const KeyInfo *pKeyInfo;
64637   int idx;
64638   CollSeq *pColl;    /* Collating sequence to use on this term */
64639   int bRev;          /* True for DESCENDING sort order */
64640 #endif /* local variables moved into u.aj */
64641
64642   u.aj.n = pOp->p3;
64643   u.aj.pKeyInfo = pOp->p4.pKeyInfo;
64644   assert( u.aj.n>0 );
64645   assert( u.aj.pKeyInfo!=0 );
64646   u.aj.p1 = pOp->p1;
64647   u.aj.p2 = pOp->p2;
64648 #if SQLITE_DEBUG
64649   if( aPermute ){
64650     int k, mx = 0;
64651     for(k=0; k<u.aj.n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
64652     assert( u.aj.p1>0 && u.aj.p1+mx<=p->nMem+1 );
64653     assert( u.aj.p2>0 && u.aj.p2+mx<=p->nMem+1 );
64654   }else{
64655     assert( u.aj.p1>0 && u.aj.p1+u.aj.n<=p->nMem+1 );
64656     assert( u.aj.p2>0 && u.aj.p2+u.aj.n<=p->nMem+1 );
64657   }
64658 #endif /* SQLITE_DEBUG */
64659   for(u.aj.i=0; u.aj.i<u.aj.n; u.aj.i++){
64660     u.aj.idx = aPermute ? aPermute[u.aj.i] : u.aj.i;
64661     assert( memIsValid(&aMem[u.aj.p1+u.aj.idx]) );
64662     assert( memIsValid(&aMem[u.aj.p2+u.aj.idx]) );
64663     REGISTER_TRACE(u.aj.p1+u.aj.idx, &aMem[u.aj.p1+u.aj.idx]);
64664     REGISTER_TRACE(u.aj.p2+u.aj.idx, &aMem[u.aj.p2+u.aj.idx]);
64665     assert( u.aj.i<u.aj.pKeyInfo->nField );
64666     u.aj.pColl = u.aj.pKeyInfo->aColl[u.aj.i];
64667     u.aj.bRev = u.aj.pKeyInfo->aSortOrder[u.aj.i];
64668     iCompare = sqlite3MemCompare(&aMem[u.aj.p1+u.aj.idx], &aMem[u.aj.p2+u.aj.idx], u.aj.pColl);
64669     if( iCompare ){
64670       if( u.aj.bRev ) iCompare = -iCompare;
64671       break;
64672     }
64673   }
64674   aPermute = 0;
64675   break;
64676 }
64677
64678 /* Opcode: Jump P1 P2 P3 * *
64679 **
64680 ** Jump to the instruction at address P1, P2, or P3 depending on whether
64681 ** in the most recent OP_Compare instruction the P1 vector was less than
64682 ** equal to, or greater than the P2 vector, respectively.
64683 */
64684 case OP_Jump: {             /* jump */
64685   if( iCompare<0 ){
64686     pc = pOp->p1 - 1;
64687   }else if( iCompare==0 ){
64688     pc = pOp->p2 - 1;
64689   }else{
64690     pc = pOp->p3 - 1;
64691   }
64692   break;
64693 }
64694
64695 /* Opcode: And P1 P2 P3 * *
64696 **
64697 ** Take the logical AND of the values in registers P1 and P2 and
64698 ** write the result into register P3.
64699 **
64700 ** If either P1 or P2 is 0 (false) then the result is 0 even if
64701 ** the other input is NULL.  A NULL and true or two NULLs give
64702 ** a NULL output.
64703 */
64704 /* Opcode: Or P1 P2 P3 * *
64705 **
64706 ** Take the logical OR of the values in register P1 and P2 and
64707 ** store the answer in register P3.
64708 **
64709 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
64710 ** even if the other input is NULL.  A NULL and false or two NULLs
64711 ** give a NULL output.
64712 */
64713 case OP_And:              /* same as TK_AND, in1, in2, out3 */
64714 case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
64715 #if 0  /* local variables moved into u.ak */
64716   int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
64717   int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
64718 #endif /* local variables moved into u.ak */
64719
64720   pIn1 = &aMem[pOp->p1];
64721   if( pIn1->flags & MEM_Null ){
64722     u.ak.v1 = 2;
64723   }else{
64724     u.ak.v1 = sqlite3VdbeIntValue(pIn1)!=0;
64725   }
64726   pIn2 = &aMem[pOp->p2];
64727   if( pIn2->flags & MEM_Null ){
64728     u.ak.v2 = 2;
64729   }else{
64730     u.ak.v2 = sqlite3VdbeIntValue(pIn2)!=0;
64731   }
64732   if( pOp->opcode==OP_And ){
64733     static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
64734     u.ak.v1 = and_logic[u.ak.v1*3+u.ak.v2];
64735   }else{
64736     static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
64737     u.ak.v1 = or_logic[u.ak.v1*3+u.ak.v2];
64738   }
64739   pOut = &aMem[pOp->p3];
64740   if( u.ak.v1==2 ){
64741     MemSetTypeFlag(pOut, MEM_Null);
64742   }else{
64743     pOut->u.i = u.ak.v1;
64744     MemSetTypeFlag(pOut, MEM_Int);
64745   }
64746   break;
64747 }
64748
64749 /* Opcode: Not P1 P2 * * *
64750 **
64751 ** Interpret the value in register P1 as a boolean value.  Store the
64752 ** boolean complement in register P2.  If the value in register P1 is 
64753 ** NULL, then a NULL is stored in P2.
64754 */
64755 case OP_Not: {                /* same as TK_NOT, in1, out2 */
64756   pIn1 = &aMem[pOp->p1];
64757   pOut = &aMem[pOp->p2];
64758   if( pIn1->flags & MEM_Null ){
64759     sqlite3VdbeMemSetNull(pOut);
64760   }else{
64761     sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
64762   }
64763   break;
64764 }
64765
64766 /* Opcode: BitNot P1 P2 * * *
64767 **
64768 ** Interpret the content of register P1 as an integer.  Store the
64769 ** ones-complement of the P1 value into register P2.  If P1 holds
64770 ** a NULL then store a NULL in P2.
64771 */
64772 case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
64773   pIn1 = &aMem[pOp->p1];
64774   pOut = &aMem[pOp->p2];
64775   if( pIn1->flags & MEM_Null ){
64776     sqlite3VdbeMemSetNull(pOut);
64777   }else{
64778     sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
64779   }
64780   break;
64781 }
64782
64783 /* Opcode: If P1 P2 P3 * *
64784 **
64785 ** Jump to P2 if the value in register P1 is true.  The value
64786 ** is considered true if it is numeric and non-zero.  If the value
64787 ** in P1 is NULL then take the jump if P3 is true.
64788 */
64789 /* Opcode: IfNot P1 P2 P3 * *
64790 **
64791 ** Jump to P2 if the value in register P1 is False.  The value
64792 ** is considered true if it has a numeric value of zero.  If the value
64793 ** in P1 is NULL then take the jump if P3 is true.
64794 */
64795 case OP_If:                 /* jump, in1 */
64796 case OP_IfNot: {            /* jump, in1 */
64797 #if 0  /* local variables moved into u.al */
64798   int c;
64799 #endif /* local variables moved into u.al */
64800   pIn1 = &aMem[pOp->p1];
64801   if( pIn1->flags & MEM_Null ){
64802     u.al.c = pOp->p3;
64803   }else{
64804 #ifdef SQLITE_OMIT_FLOATING_POINT
64805     u.al.c = sqlite3VdbeIntValue(pIn1)!=0;
64806 #else
64807     u.al.c = sqlite3VdbeRealValue(pIn1)!=0.0;
64808 #endif
64809     if( pOp->opcode==OP_IfNot ) u.al.c = !u.al.c;
64810   }
64811   if( u.al.c ){
64812     pc = pOp->p2-1;
64813   }
64814   break;
64815 }
64816
64817 /* Opcode: IsNull P1 P2 * * *
64818 **
64819 ** Jump to P2 if the value in register P1 is NULL.
64820 */
64821 case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
64822   pIn1 = &aMem[pOp->p1];
64823   if( (pIn1->flags & MEM_Null)!=0 ){
64824     pc = pOp->p2 - 1;
64825   }
64826   break;
64827 }
64828
64829 /* Opcode: NotNull P1 P2 * * *
64830 **
64831 ** Jump to P2 if the value in register P1 is not NULL.  
64832 */
64833 case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
64834   pIn1 = &aMem[pOp->p1];
64835   if( (pIn1->flags & MEM_Null)==0 ){
64836     pc = pOp->p2 - 1;
64837   }
64838   break;
64839 }
64840
64841 /* Opcode: Column P1 P2 P3 P4 P5
64842 **
64843 ** Interpret the data that cursor P1 points to as a structure built using
64844 ** the MakeRecord instruction.  (See the MakeRecord opcode for additional
64845 ** information about the format of the data.)  Extract the P2-th column
64846 ** from this record.  If there are less that (P2+1) 
64847 ** values in the record, extract a NULL.
64848 **
64849 ** The value extracted is stored in register P3.
64850 **
64851 ** If the column contains fewer than P2 fields, then extract a NULL.  Or,
64852 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
64853 ** the result.
64854 **
64855 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
64856 ** then the cache of the cursor is reset prior to extracting the column.
64857 ** The first OP_Column against a pseudo-table after the value of the content
64858 ** register has changed should have this bit set.
64859 */
64860 case OP_Column: {
64861 #if 0  /* local variables moved into u.am */
64862   u32 payloadSize;   /* Number of bytes in the record */
64863   i64 payloadSize64; /* Number of bytes in the record */
64864   int p1;            /* P1 value of the opcode */
64865   int p2;            /* column number to retrieve */
64866   VdbeCursor *pC;    /* The VDBE cursor */
64867   char *zRec;        /* Pointer to complete record-data */
64868   BtCursor *pCrsr;   /* The BTree cursor */
64869   u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
64870   u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
64871   int nField;        /* number of fields in the record */
64872   int len;           /* The length of the serialized data for the column */
64873   int i;             /* Loop counter */
64874   char *zData;       /* Part of the record being decoded */
64875   Mem *pDest;        /* Where to write the extracted value */
64876   Mem sMem;          /* For storing the record being decoded */
64877   u8 *zIdx;          /* Index into header */
64878   u8 *zEndHdr;       /* Pointer to first byte after the header */
64879   u32 offset;        /* Offset into the data */
64880   u32 szField;       /* Number of bytes in the content of a field */
64881   int szHdr;         /* Size of the header size field at start of record */
64882   int avail;         /* Number of bytes of available data */
64883   Mem *pReg;         /* PseudoTable input register */
64884 #endif /* local variables moved into u.am */
64885
64886
64887   u.am.p1 = pOp->p1;
64888   u.am.p2 = pOp->p2;
64889   u.am.pC = 0;
64890   memset(&u.am.sMem, 0, sizeof(u.am.sMem));
64891   assert( u.am.p1<p->nCursor );
64892   assert( pOp->p3>0 && pOp->p3<=p->nMem );
64893   u.am.pDest = &aMem[pOp->p3];
64894   memAboutToChange(p, u.am.pDest);
64895   MemSetTypeFlag(u.am.pDest, MEM_Null);
64896   u.am.zRec = 0;
64897
64898   /* This block sets the variable u.am.payloadSize to be the total number of
64899   ** bytes in the record.
64900   **
64901   ** u.am.zRec is set to be the complete text of the record if it is available.
64902   ** The complete record text is always available for pseudo-tables
64903   ** If the record is stored in a cursor, the complete record text
64904   ** might be available in the  u.am.pC->aRow cache.  Or it might not be.
64905   ** If the data is unavailable,  u.am.zRec is set to NULL.
64906   **
64907   ** We also compute the number of columns in the record.  For cursors,
64908   ** the number of columns is stored in the VdbeCursor.nField element.
64909   */
64910   u.am.pC = p->apCsr[u.am.p1];
64911   assert( u.am.pC!=0 );
64912 #ifndef SQLITE_OMIT_VIRTUALTABLE
64913   assert( u.am.pC->pVtabCursor==0 );
64914 #endif
64915   u.am.pCrsr = u.am.pC->pCursor;
64916   if( u.am.pCrsr!=0 ){
64917     /* The record is stored in a B-Tree */
64918     rc = sqlite3VdbeCursorMoveto(u.am.pC);
64919     if( rc ) goto abort_due_to_error;
64920     if( u.am.pC->nullRow ){
64921       u.am.payloadSize = 0;
64922     }else if( u.am.pC->cacheStatus==p->cacheCtr ){
64923       u.am.payloadSize = u.am.pC->payloadSize;
64924       u.am.zRec = (char*)u.am.pC->aRow;
64925     }else if( u.am.pC->isIndex ){
64926       assert( sqlite3BtreeCursorIsValid(u.am.pCrsr) );
64927       rc = sqlite3BtreeKeySize(u.am.pCrsr, &u.am.payloadSize64);
64928       assert( rc==SQLITE_OK );   /* True because of CursorMoveto() call above */
64929       /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
64930       ** payload size, so it is impossible for u.am.payloadSize64 to be
64931       ** larger than 32 bits. */
64932       assert( (u.am.payloadSize64 & SQLITE_MAX_U32)==(u64)u.am.payloadSize64 );
64933       u.am.payloadSize = (u32)u.am.payloadSize64;
64934     }else{
64935       assert( sqlite3BtreeCursorIsValid(u.am.pCrsr) );
64936       rc = sqlite3BtreeDataSize(u.am.pCrsr, &u.am.payloadSize);
64937       assert( rc==SQLITE_OK );   /* DataSize() cannot fail */
64938     }
64939   }else if( u.am.pC->pseudoTableReg>0 ){
64940     u.am.pReg = &aMem[u.am.pC->pseudoTableReg];
64941     assert( u.am.pReg->flags & MEM_Blob );
64942     assert( memIsValid(u.am.pReg) );
64943     u.am.payloadSize = u.am.pReg->n;
64944     u.am.zRec = u.am.pReg->z;
64945     u.am.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;
64946     assert( u.am.payloadSize==0 || u.am.zRec!=0 );
64947   }else{
64948     /* Consider the row to be NULL */
64949     u.am.payloadSize = 0;
64950   }
64951
64952   /* If u.am.payloadSize is 0, then just store a NULL */
64953   if( u.am.payloadSize==0 ){
64954     assert( u.am.pDest->flags&MEM_Null );
64955     goto op_column_out;
64956   }
64957   assert( db->aLimit[SQLITE_LIMIT_LENGTH]>=0 );
64958   if( u.am.payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
64959     goto too_big;
64960   }
64961
64962   u.am.nField = u.am.pC->nField;
64963   assert( u.am.p2<u.am.nField );
64964
64965   /* Read and parse the table header.  Store the results of the parse
64966   ** into the record header cache fields of the cursor.
64967   */
64968   u.am.aType = u.am.pC->aType;
64969   if( u.am.pC->cacheStatus==p->cacheCtr ){
64970     u.am.aOffset = u.am.pC->aOffset;
64971   }else{
64972     assert(u.am.aType);
64973     u.am.avail = 0;
64974     u.am.pC->aOffset = u.am.aOffset = &u.am.aType[u.am.nField];
64975     u.am.pC->payloadSize = u.am.payloadSize;
64976     u.am.pC->cacheStatus = p->cacheCtr;
64977
64978     /* Figure out how many bytes are in the header */
64979     if( u.am.zRec ){
64980       u.am.zData = u.am.zRec;
64981     }else{
64982       if( u.am.pC->isIndex ){
64983         u.am.zData = (char*)sqlite3BtreeKeyFetch(u.am.pCrsr, &u.am.avail);
64984       }else{
64985         u.am.zData = (char*)sqlite3BtreeDataFetch(u.am.pCrsr, &u.am.avail);
64986       }
64987       /* If KeyFetch()/DataFetch() managed to get the entire payload,
64988       ** save the payload in the u.am.pC->aRow cache.  That will save us from
64989       ** having to make additional calls to fetch the content portion of
64990       ** the record.
64991       */
64992       assert( u.am.avail>=0 );
64993       if( u.am.payloadSize <= (u32)u.am.avail ){
64994         u.am.zRec = u.am.zData;
64995         u.am.pC->aRow = (u8*)u.am.zData;
64996       }else{
64997         u.am.pC->aRow = 0;
64998       }
64999     }
65000     /* The following assert is true in all cases accept when
65001     ** the database file has been corrupted externally.
65002     **    assert( u.am.zRec!=0 || u.am.avail>=u.am.payloadSize || u.am.avail>=9 ); */
65003     u.am.szHdr = getVarint32((u8*)u.am.zData, u.am.offset);
65004
65005     /* Make sure a corrupt database has not given us an oversize header.
65006     ** Do this now to avoid an oversize memory allocation.
65007     **
65008     ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
65009     ** types use so much data space that there can only be 4096 and 32 of
65010     ** them, respectively.  So the maximum header length results from a
65011     ** 3-byte type for each of the maximum of 32768 columns plus three
65012     ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
65013     */
65014     if( u.am.offset > 98307 ){
65015       rc = SQLITE_CORRUPT_BKPT;
65016       goto op_column_out;
65017     }
65018
65019     /* Compute in u.am.len the number of bytes of data we need to read in order
65020     ** to get u.am.nField type values.  u.am.offset is an upper bound on this.  But
65021     ** u.am.nField might be significantly less than the true number of columns
65022     ** in the table, and in that case, 5*u.am.nField+3 might be smaller than u.am.offset.
65023     ** We want to minimize u.am.len in order to limit the size of the memory
65024     ** allocation, especially if a corrupt database file has caused u.am.offset
65025     ** to be oversized. Offset is limited to 98307 above.  But 98307 might
65026     ** still exceed Robson memory allocation limits on some configurations.
65027     ** On systems that cannot tolerate large memory allocations, u.am.nField*5+3
65028     ** will likely be much smaller since u.am.nField will likely be less than
65029     ** 20 or so.  This insures that Robson memory allocation limits are
65030     ** not exceeded even for corrupt database files.
65031     */
65032     u.am.len = u.am.nField*5 + 3;
65033     if( u.am.len > (int)u.am.offset ) u.am.len = (int)u.am.offset;
65034
65035     /* The KeyFetch() or DataFetch() above are fast and will get the entire
65036     ** record header in most cases.  But they will fail to get the complete
65037     ** record header if the record header does not fit on a single page
65038     ** in the B-Tree.  When that happens, use sqlite3VdbeMemFromBtree() to
65039     ** acquire the complete header text.
65040     */
65041     if( !u.am.zRec && u.am.avail<u.am.len ){
65042       u.am.sMem.flags = 0;
65043       u.am.sMem.db = 0;
65044       rc = sqlite3VdbeMemFromBtree(u.am.pCrsr, 0, u.am.len, u.am.pC->isIndex, &u.am.sMem);
65045       if( rc!=SQLITE_OK ){
65046         goto op_column_out;
65047       }
65048       u.am.zData = u.am.sMem.z;
65049     }
65050     u.am.zEndHdr = (u8 *)&u.am.zData[u.am.len];
65051     u.am.zIdx = (u8 *)&u.am.zData[u.am.szHdr];
65052
65053     /* Scan the header and use it to fill in the u.am.aType[] and u.am.aOffset[]
65054     ** arrays.  u.am.aType[u.am.i] will contain the type integer for the u.am.i-th
65055     ** column and u.am.aOffset[u.am.i] will contain the u.am.offset from the beginning
65056     ** of the record to the start of the data for the u.am.i-th column
65057     */
65058     for(u.am.i=0; u.am.i<u.am.nField; u.am.i++){
65059       if( u.am.zIdx<u.am.zEndHdr ){
65060         u.am.aOffset[u.am.i] = u.am.offset;
65061         u.am.zIdx += getVarint32(u.am.zIdx, u.am.aType[u.am.i]);
65062         u.am.szField = sqlite3VdbeSerialTypeLen(u.am.aType[u.am.i]);
65063         u.am.offset += u.am.szField;
65064         if( u.am.offset<u.am.szField ){  /* True if u.am.offset overflows */
65065           u.am.zIdx = &u.am.zEndHdr[1];  /* Forces SQLITE_CORRUPT return below */
65066           break;
65067         }
65068       }else{
65069         /* If u.am.i is less that u.am.nField, then there are less fields in this
65070         ** record than SetNumColumns indicated there are columns in the
65071         ** table. Set the u.am.offset for any extra columns not present in
65072         ** the record to 0. This tells code below to store a NULL
65073         ** instead of deserializing a value from the record.
65074         */
65075         u.am.aOffset[u.am.i] = 0;
65076       }
65077     }
65078     sqlite3VdbeMemRelease(&u.am.sMem);
65079     u.am.sMem.flags = MEM_Null;
65080
65081     /* If we have read more header data than was contained in the header,
65082     ** or if the end of the last field appears to be past the end of the
65083     ** record, or if the end of the last field appears to be before the end
65084     ** of the record (when all fields present), then we must be dealing
65085     ** with a corrupt database.
65086     */
65087     if( (u.am.zIdx > u.am.zEndHdr) || (u.am.offset > u.am.payloadSize)
65088          || (u.am.zIdx==u.am.zEndHdr && u.am.offset!=u.am.payloadSize) ){
65089       rc = SQLITE_CORRUPT_BKPT;
65090       goto op_column_out;
65091     }
65092   }
65093
65094   /* Get the column information. If u.am.aOffset[u.am.p2] is non-zero, then
65095   ** deserialize the value from the record. If u.am.aOffset[u.am.p2] is zero,
65096   ** then there are not enough fields in the record to satisfy the
65097   ** request.  In this case, set the value NULL or to P4 if P4 is
65098   ** a pointer to a Mem object.
65099   */
65100   if( u.am.aOffset[u.am.p2] ){
65101     assert( rc==SQLITE_OK );
65102     if( u.am.zRec ){
65103       sqlite3VdbeMemReleaseExternal(u.am.pDest);
65104       sqlite3VdbeSerialGet((u8 *)&u.am.zRec[u.am.aOffset[u.am.p2]], u.am.aType[u.am.p2], u.am.pDest);
65105     }else{
65106       u.am.len = sqlite3VdbeSerialTypeLen(u.am.aType[u.am.p2]);
65107       sqlite3VdbeMemMove(&u.am.sMem, u.am.pDest);
65108       rc = sqlite3VdbeMemFromBtree(u.am.pCrsr, u.am.aOffset[u.am.p2], u.am.len, u.am.pC->isIndex, &u.am.sMem);
65109       if( rc!=SQLITE_OK ){
65110         goto op_column_out;
65111       }
65112       u.am.zData = u.am.sMem.z;
65113       sqlite3VdbeSerialGet((u8*)u.am.zData, u.am.aType[u.am.p2], u.am.pDest);
65114     }
65115     u.am.pDest->enc = encoding;
65116   }else{
65117     if( pOp->p4type==P4_MEM ){
65118       sqlite3VdbeMemShallowCopy(u.am.pDest, pOp->p4.pMem, MEM_Static);
65119     }else{
65120       assert( u.am.pDest->flags&MEM_Null );
65121     }
65122   }
65123
65124   /* If we dynamically allocated space to hold the data (in the
65125   ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
65126   ** dynamically allocated space over to the u.am.pDest structure.
65127   ** This prevents a memory copy.
65128   */
65129   if( u.am.sMem.zMalloc ){
65130     assert( u.am.sMem.z==u.am.sMem.zMalloc );
65131     assert( !(u.am.pDest->flags & MEM_Dyn) );
65132     assert( !(u.am.pDest->flags & (MEM_Blob|MEM_Str)) || u.am.pDest->z==u.am.sMem.z );
65133     u.am.pDest->flags &= ~(MEM_Ephem|MEM_Static);
65134     u.am.pDest->flags |= MEM_Term;
65135     u.am.pDest->z = u.am.sMem.z;
65136     u.am.pDest->zMalloc = u.am.sMem.zMalloc;
65137   }
65138
65139   rc = sqlite3VdbeMemMakeWriteable(u.am.pDest);
65140
65141 op_column_out:
65142   UPDATE_MAX_BLOBSIZE(u.am.pDest);
65143   REGISTER_TRACE(pOp->p3, u.am.pDest);
65144   break;
65145 }
65146
65147 /* Opcode: Affinity P1 P2 * P4 *
65148 **
65149 ** Apply affinities to a range of P2 registers starting with P1.
65150 **
65151 ** P4 is a string that is P2 characters long. The nth character of the
65152 ** string indicates the column affinity that should be used for the nth
65153 ** memory cell in the range.
65154 */
65155 case OP_Affinity: {
65156 #if 0  /* local variables moved into u.an */
65157   const char *zAffinity;   /* The affinity to be applied */
65158   char cAff;               /* A single character of affinity */
65159 #endif /* local variables moved into u.an */
65160
65161   u.an.zAffinity = pOp->p4.z;
65162   assert( u.an.zAffinity!=0 );
65163   assert( u.an.zAffinity[pOp->p2]==0 );
65164   pIn1 = &aMem[pOp->p1];
65165   while( (u.an.cAff = *(u.an.zAffinity++))!=0 ){
65166     assert( pIn1 <= &p->aMem[p->nMem] );
65167     assert( memIsValid(pIn1) );
65168     ExpandBlob(pIn1);
65169     applyAffinity(pIn1, u.an.cAff, encoding);
65170     pIn1++;
65171   }
65172   break;
65173 }
65174
65175 /* Opcode: MakeRecord P1 P2 P3 P4 *
65176 **
65177 ** Convert P2 registers beginning with P1 into the [record format]
65178 ** use as a data record in a database table or as a key
65179 ** in an index.  The OP_Column opcode can decode the record later.
65180 **
65181 ** P4 may be a string that is P2 characters long.  The nth character of the
65182 ** string indicates the column affinity that should be used for the nth
65183 ** field of the index key.
65184 **
65185 ** The mapping from character to affinity is given by the SQLITE_AFF_
65186 ** macros defined in sqliteInt.h.
65187 **
65188 ** If P4 is NULL then all index fields have the affinity NONE.
65189 */
65190 case OP_MakeRecord: {
65191 #if 0  /* local variables moved into u.ao */
65192   u8 *zNewRecord;        /* A buffer to hold the data for the new record */
65193   Mem *pRec;             /* The new record */
65194   u64 nData;             /* Number of bytes of data space */
65195   int nHdr;              /* Number of bytes of header space */
65196   i64 nByte;             /* Data space required for this record */
65197   int nZero;             /* Number of zero bytes at the end of the record */
65198   int nVarint;           /* Number of bytes in a varint */
65199   u32 serial_type;       /* Type field */
65200   Mem *pData0;           /* First field to be combined into the record */
65201   Mem *pLast;            /* Last field of the record */
65202   int nField;            /* Number of fields in the record */
65203   char *zAffinity;       /* The affinity string for the record */
65204   int file_format;       /* File format to use for encoding */
65205   int i;                 /* Space used in zNewRecord[] */
65206   int len;               /* Length of a field */
65207 #endif /* local variables moved into u.ao */
65208
65209   /* Assuming the record contains N fields, the record format looks
65210   ** like this:
65211   **
65212   ** ------------------------------------------------------------------------
65213   ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
65214   ** ------------------------------------------------------------------------
65215   **
65216   ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
65217   ** and so froth.
65218   **
65219   ** Each type field is a varint representing the serial type of the
65220   ** corresponding data element (see sqlite3VdbeSerialType()). The
65221   ** hdr-size field is also a varint which is the offset from the beginning
65222   ** of the record to data0.
65223   */
65224   u.ao.nData = 0;         /* Number of bytes of data space */
65225   u.ao.nHdr = 0;          /* Number of bytes of header space */
65226   u.ao.nZero = 0;         /* Number of zero bytes at the end of the record */
65227   u.ao.nField = pOp->p1;
65228   u.ao.zAffinity = pOp->p4.z;
65229   assert( u.ao.nField>0 && pOp->p2>0 && pOp->p2+u.ao.nField<=p->nMem+1 );
65230   u.ao.pData0 = &aMem[u.ao.nField];
65231   u.ao.nField = pOp->p2;
65232   u.ao.pLast = &u.ao.pData0[u.ao.nField-1];
65233   u.ao.file_format = p->minWriteFileFormat;
65234
65235   /* Identify the output register */
65236   assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
65237   pOut = &aMem[pOp->p3];
65238   memAboutToChange(p, pOut);
65239
65240   /* Loop through the elements that will make up the record to figure
65241   ** out how much space is required for the new record.
65242   */
65243   for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
65244     assert( memIsValid(u.ao.pRec) );
65245     if( u.ao.zAffinity ){
65246       applyAffinity(u.ao.pRec, u.ao.zAffinity[u.ao.pRec-u.ao.pData0], encoding);
65247     }
65248     if( u.ao.pRec->flags&MEM_Zero && u.ao.pRec->n>0 ){
65249       sqlite3VdbeMemExpandBlob(u.ao.pRec);
65250     }
65251     u.ao.serial_type = sqlite3VdbeSerialType(u.ao.pRec, u.ao.file_format);
65252     u.ao.len = sqlite3VdbeSerialTypeLen(u.ao.serial_type);
65253     u.ao.nData += u.ao.len;
65254     u.ao.nHdr += sqlite3VarintLen(u.ao.serial_type);
65255     if( u.ao.pRec->flags & MEM_Zero ){
65256       /* Only pure zero-filled BLOBs can be input to this Opcode.
65257       ** We do not allow blobs with a prefix and a zero-filled tail. */
65258       u.ao.nZero += u.ao.pRec->u.nZero;
65259     }else if( u.ao.len ){
65260       u.ao.nZero = 0;
65261     }
65262   }
65263
65264   /* Add the initial header varint and total the size */
65265   u.ao.nHdr += u.ao.nVarint = sqlite3VarintLen(u.ao.nHdr);
65266   if( u.ao.nVarint<sqlite3VarintLen(u.ao.nHdr) ){
65267     u.ao.nHdr++;
65268   }
65269   u.ao.nByte = u.ao.nHdr+u.ao.nData-u.ao.nZero;
65270   if( u.ao.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
65271     goto too_big;
65272   }
65273
65274   /* Make sure the output register has a buffer large enough to store
65275   ** the new record. The output register (pOp->p3) is not allowed to
65276   ** be one of the input registers (because the following call to
65277   ** sqlite3VdbeMemGrow() could clobber the value before it is used).
65278   */
65279   if( sqlite3VdbeMemGrow(pOut, (int)u.ao.nByte, 0) ){
65280     goto no_mem;
65281   }
65282   u.ao.zNewRecord = (u8 *)pOut->z;
65283
65284   /* Write the record */
65285   u.ao.i = putVarint32(u.ao.zNewRecord, u.ao.nHdr);
65286   for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
65287     u.ao.serial_type = sqlite3VdbeSerialType(u.ao.pRec, u.ao.file_format);
65288     u.ao.i += putVarint32(&u.ao.zNewRecord[u.ao.i], u.ao.serial_type);      /* serial type */
65289   }
65290   for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){  /* serial data */
65291     u.ao.i += sqlite3VdbeSerialPut(&u.ao.zNewRecord[u.ao.i], (int)(u.ao.nByte-u.ao.i), u.ao.pRec,u.ao.file_format);
65292   }
65293   assert( u.ao.i==u.ao.nByte );
65294
65295   assert( pOp->p3>0 && pOp->p3<=p->nMem );
65296   pOut->n = (int)u.ao.nByte;
65297   pOut->flags = MEM_Blob | MEM_Dyn;
65298   pOut->xDel = 0;
65299   if( u.ao.nZero ){
65300     pOut->u.nZero = u.ao.nZero;
65301     pOut->flags |= MEM_Zero;
65302   }
65303   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
65304   REGISTER_TRACE(pOp->p3, pOut);
65305   UPDATE_MAX_BLOBSIZE(pOut);
65306   break;
65307 }
65308
65309 /* Opcode: Count P1 P2 * * *
65310 **
65311 ** Store the number of entries (an integer value) in the table or index 
65312 ** opened by cursor P1 in register P2
65313 */
65314 #ifndef SQLITE_OMIT_BTREECOUNT
65315 case OP_Count: {         /* out2-prerelease */
65316 #if 0  /* local variables moved into u.ap */
65317   i64 nEntry;
65318   BtCursor *pCrsr;
65319 #endif /* local variables moved into u.ap */
65320
65321   u.ap.pCrsr = p->apCsr[pOp->p1]->pCursor;
65322   if( u.ap.pCrsr ){
65323     rc = sqlite3BtreeCount(u.ap.pCrsr, &u.ap.nEntry);
65324   }else{
65325     u.ap.nEntry = 0;
65326   }
65327   pOut->u.i = u.ap.nEntry;
65328   break;
65329 }
65330 #endif
65331
65332 /* Opcode: Savepoint P1 * * P4 *
65333 **
65334 ** Open, release or rollback the savepoint named by parameter P4, depending
65335 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
65336 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
65337 */
65338 case OP_Savepoint: {
65339 #if 0  /* local variables moved into u.aq */
65340   int p1;                         /* Value of P1 operand */
65341   char *zName;                    /* Name of savepoint */
65342   int nName;
65343   Savepoint *pNew;
65344   Savepoint *pSavepoint;
65345   Savepoint *pTmp;
65346   int iSavepoint;
65347   int ii;
65348 #endif /* local variables moved into u.aq */
65349
65350   u.aq.p1 = pOp->p1;
65351   u.aq.zName = pOp->p4.z;
65352
65353   /* Assert that the u.aq.p1 parameter is valid. Also that if there is no open
65354   ** transaction, then there cannot be any savepoints.
65355   */
65356   assert( db->pSavepoint==0 || db->autoCommit==0 );
65357   assert( u.aq.p1==SAVEPOINT_BEGIN||u.aq.p1==SAVEPOINT_RELEASE||u.aq.p1==SAVEPOINT_ROLLBACK );
65358   assert( db->pSavepoint || db->isTransactionSavepoint==0 );
65359   assert( checkSavepointCount(db) );
65360
65361   if( u.aq.p1==SAVEPOINT_BEGIN ){
65362     if( db->writeVdbeCnt>0 ){
65363       /* A new savepoint cannot be created if there are active write
65364       ** statements (i.e. open read/write incremental blob handles).
65365       */
65366       sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
65367         "SQL statements in progress");
65368       rc = SQLITE_BUSY;
65369     }else{
65370       u.aq.nName = sqlite3Strlen30(u.aq.zName);
65371
65372 #ifndef SQLITE_OMIT_VIRTUALTABLE
65373       /* This call is Ok even if this savepoint is actually a transaction
65374       ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
65375       ** If this is a transaction savepoint being opened, it is guaranteed
65376       ** that the db->aVTrans[] array is empty.  */
65377       assert( db->autoCommit==0 || db->nVTrans==0 );
65378       rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
65379                                 db->nStatement+db->nSavepoint);
65380       if( rc!=SQLITE_OK ) goto abort_due_to_error;
65381 #endif
65382
65383       /* Create a new savepoint structure. */
65384       u.aq.pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+u.aq.nName+1);
65385       if( u.aq.pNew ){
65386         u.aq.pNew->zName = (char *)&u.aq.pNew[1];
65387         memcpy(u.aq.pNew->zName, u.aq.zName, u.aq.nName+1);
65388
65389         /* If there is no open transaction, then mark this as a special
65390         ** "transaction savepoint". */
65391         if( db->autoCommit ){
65392           db->autoCommit = 0;
65393           db->isTransactionSavepoint = 1;
65394         }else{
65395           db->nSavepoint++;
65396         }
65397
65398         /* Link the new savepoint into the database handle's list. */
65399         u.aq.pNew->pNext = db->pSavepoint;
65400         db->pSavepoint = u.aq.pNew;
65401         u.aq.pNew->nDeferredCons = db->nDeferredCons;
65402       }
65403     }
65404   }else{
65405     u.aq.iSavepoint = 0;
65406
65407     /* Find the named savepoint. If there is no such savepoint, then an
65408     ** an error is returned to the user.  */
65409     for(
65410       u.aq.pSavepoint = db->pSavepoint;
65411       u.aq.pSavepoint && sqlite3StrICmp(u.aq.pSavepoint->zName, u.aq.zName);
65412       u.aq.pSavepoint = u.aq.pSavepoint->pNext
65413     ){
65414       u.aq.iSavepoint++;
65415     }
65416     if( !u.aq.pSavepoint ){
65417       sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", u.aq.zName);
65418       rc = SQLITE_ERROR;
65419     }else if(
65420         db->writeVdbeCnt>0 || (u.aq.p1==SAVEPOINT_ROLLBACK && db->activeVdbeCnt>1)
65421     ){
65422       /* It is not possible to release (commit) a savepoint if there are
65423       ** active write statements. It is not possible to rollback a savepoint
65424       ** if there are any active statements at all.
65425       */
65426       sqlite3SetString(&p->zErrMsg, db,
65427         "cannot %s savepoint - SQL statements in progress",
65428         (u.aq.p1==SAVEPOINT_ROLLBACK ? "rollback": "release")
65429       );
65430       rc = SQLITE_BUSY;
65431     }else{
65432
65433       /* Determine whether or not this is a transaction savepoint. If so,
65434       ** and this is a RELEASE command, then the current transaction
65435       ** is committed.
65436       */
65437       int isTransaction = u.aq.pSavepoint->pNext==0 && db->isTransactionSavepoint;
65438       if( isTransaction && u.aq.p1==SAVEPOINT_RELEASE ){
65439         if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
65440           goto vdbe_return;
65441         }
65442         db->autoCommit = 1;
65443         if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
65444           p->pc = pc;
65445           db->autoCommit = 0;
65446           p->rc = rc = SQLITE_BUSY;
65447           goto vdbe_return;
65448         }
65449         db->isTransactionSavepoint = 0;
65450         rc = p->rc;
65451       }else{
65452         u.aq.iSavepoint = db->nSavepoint - u.aq.iSavepoint - 1;
65453         for(u.aq.ii=0; u.aq.ii<db->nDb; u.aq.ii++){
65454           rc = sqlite3BtreeSavepoint(db->aDb[u.aq.ii].pBt, u.aq.p1, u.aq.iSavepoint);
65455           if( rc!=SQLITE_OK ){
65456             goto abort_due_to_error;
65457           }
65458         }
65459         if( u.aq.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
65460           sqlite3ExpirePreparedStatements(db);
65461           sqlite3ResetInternalSchema(db, -1);
65462           db->flags = (db->flags | SQLITE_InternChanges);
65463         }
65464       }
65465
65466       /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
65467       ** savepoints nested inside of the savepoint being operated on. */
65468       while( db->pSavepoint!=u.aq.pSavepoint ){
65469         u.aq.pTmp = db->pSavepoint;
65470         db->pSavepoint = u.aq.pTmp->pNext;
65471         sqlite3DbFree(db, u.aq.pTmp);
65472         db->nSavepoint--;
65473       }
65474
65475       /* If it is a RELEASE, then destroy the savepoint being operated on
65476       ** too. If it is a ROLLBACK TO, then set the number of deferred
65477       ** constraint violations present in the database to the value stored
65478       ** when the savepoint was created.  */
65479       if( u.aq.p1==SAVEPOINT_RELEASE ){
65480         assert( u.aq.pSavepoint==db->pSavepoint );
65481         db->pSavepoint = u.aq.pSavepoint->pNext;
65482         sqlite3DbFree(db, u.aq.pSavepoint);
65483         if( !isTransaction ){
65484           db->nSavepoint--;
65485         }
65486       }else{
65487         db->nDeferredCons = u.aq.pSavepoint->nDeferredCons;
65488       }
65489
65490       if( !isTransaction ){
65491         rc = sqlite3VtabSavepoint(db, u.aq.p1, u.aq.iSavepoint);
65492         if( rc!=SQLITE_OK ) goto abort_due_to_error;
65493       }
65494     }
65495   }
65496
65497   break;
65498 }
65499
65500 /* Opcode: AutoCommit P1 P2 * * *
65501 **
65502 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
65503 ** back any currently active btree transactions. If there are any active
65504 ** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
65505 ** there are active writing VMs or active VMs that use shared cache.
65506 **
65507 ** This instruction causes the VM to halt.
65508 */
65509 case OP_AutoCommit: {
65510 #if 0  /* local variables moved into u.ar */
65511   int desiredAutoCommit;
65512   int iRollback;
65513   int turnOnAC;
65514 #endif /* local variables moved into u.ar */
65515
65516   u.ar.desiredAutoCommit = pOp->p1;
65517   u.ar.iRollback = pOp->p2;
65518   u.ar.turnOnAC = u.ar.desiredAutoCommit && !db->autoCommit;
65519   assert( u.ar.desiredAutoCommit==1 || u.ar.desiredAutoCommit==0 );
65520   assert( u.ar.desiredAutoCommit==1 || u.ar.iRollback==0 );
65521   assert( db->activeVdbeCnt>0 );  /* At least this one VM is active */
65522
65523   if( u.ar.turnOnAC && u.ar.iRollback && db->activeVdbeCnt>1 ){
65524     /* If this instruction implements a ROLLBACK and other VMs are
65525     ** still running, and a transaction is active, return an error indicating
65526     ** that the other VMs must complete first.
65527     */
65528     sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
65529         "SQL statements in progress");
65530     rc = SQLITE_BUSY;
65531   }else if( u.ar.turnOnAC && !u.ar.iRollback && db->writeVdbeCnt>0 ){
65532     /* If this instruction implements a COMMIT and other VMs are writing
65533     ** return an error indicating that the other VMs must complete first.
65534     */
65535     sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
65536         "SQL statements in progress");
65537     rc = SQLITE_BUSY;
65538   }else if( u.ar.desiredAutoCommit!=db->autoCommit ){
65539     if( u.ar.iRollback ){
65540       assert( u.ar.desiredAutoCommit==1 );
65541       sqlite3RollbackAll(db);
65542       db->autoCommit = 1;
65543     }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
65544       goto vdbe_return;
65545     }else{
65546       db->autoCommit = (u8)u.ar.desiredAutoCommit;
65547       if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
65548         p->pc = pc;
65549         db->autoCommit = (u8)(1-u.ar.desiredAutoCommit);
65550         p->rc = rc = SQLITE_BUSY;
65551         goto vdbe_return;
65552       }
65553     }
65554     assert( db->nStatement==0 );
65555     sqlite3CloseSavepoints(db);
65556     if( p->rc==SQLITE_OK ){
65557       rc = SQLITE_DONE;
65558     }else{
65559       rc = SQLITE_ERROR;
65560     }
65561     goto vdbe_return;
65562   }else{
65563     sqlite3SetString(&p->zErrMsg, db,
65564         (!u.ar.desiredAutoCommit)?"cannot start a transaction within a transaction":(
65565         (u.ar.iRollback)?"cannot rollback - no transaction is active":
65566                    "cannot commit - no transaction is active"));
65567
65568     rc = SQLITE_ERROR;
65569   }
65570   break;
65571 }
65572
65573 /* Opcode: Transaction P1 P2 * * *
65574 **
65575 ** Begin a transaction.  The transaction ends when a Commit or Rollback
65576 ** opcode is encountered.  Depending on the ON CONFLICT setting, the
65577 ** transaction might also be rolled back if an error is encountered.
65578 **
65579 ** P1 is the index of the database file on which the transaction is
65580 ** started.  Index 0 is the main database file and index 1 is the
65581 ** file used for temporary tables.  Indices of 2 or more are used for
65582 ** attached databases.
65583 **
65584 ** If P2 is non-zero, then a write-transaction is started.  A RESERVED lock is
65585 ** obtained on the database file when a write-transaction is started.  No
65586 ** other process can start another write transaction while this transaction is
65587 ** underway.  Starting a write transaction also creates a rollback journal. A
65588 ** write transaction must be started before any changes can be made to the
65589 ** database.  If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
65590 ** on the file.
65591 **
65592 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
65593 ** true (this flag is set if the Vdbe may modify more than one row and may
65594 ** throw an ABORT exception), a statement transaction may also be opened.
65595 ** More specifically, a statement transaction is opened iff the database
65596 ** connection is currently not in autocommit mode, or if there are other
65597 ** active statements. A statement transaction allows the affects of this
65598 ** VDBE to be rolled back after an error without having to roll back the
65599 ** entire transaction. If no error is encountered, the statement transaction
65600 ** will automatically commit when the VDBE halts.
65601 **
65602 ** If P2 is zero, then a read-lock is obtained on the database file.
65603 */
65604 case OP_Transaction: {
65605 #if 0  /* local variables moved into u.as */
65606   Btree *pBt;
65607 #endif /* local variables moved into u.as */
65608
65609   assert( pOp->p1>=0 && pOp->p1<db->nDb );
65610   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
65611   u.as.pBt = db->aDb[pOp->p1].pBt;
65612
65613   if( u.as.pBt ){
65614     rc = sqlite3BtreeBeginTrans(u.as.pBt, pOp->p2);
65615     if( rc==SQLITE_BUSY ){
65616       p->pc = pc;
65617       p->rc = rc = SQLITE_BUSY;
65618       goto vdbe_return;
65619     }
65620     if( rc!=SQLITE_OK ){
65621       goto abort_due_to_error;
65622     }
65623
65624     if( pOp->p2 && p->usesStmtJournal
65625      && (db->autoCommit==0 || db->activeVdbeCnt>1)
65626     ){
65627       assert( sqlite3BtreeIsInTrans(u.as.pBt) );
65628       if( p->iStatement==0 ){
65629         assert( db->nStatement>=0 && db->nSavepoint>=0 );
65630         db->nStatement++;
65631         p->iStatement = db->nSavepoint + db->nStatement;
65632       }
65633
65634       rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
65635       if( rc==SQLITE_OK ){
65636         rc = sqlite3BtreeBeginStmt(u.as.pBt, p->iStatement);
65637       }
65638
65639       /* Store the current value of the database handles deferred constraint
65640       ** counter. If the statement transaction needs to be rolled back,
65641       ** the value of this counter needs to be restored too.  */
65642       p->nStmtDefCons = db->nDeferredCons;
65643     }
65644   }
65645   break;
65646 }
65647
65648 /* Opcode: ReadCookie P1 P2 P3 * *
65649 **
65650 ** Read cookie number P3 from database P1 and write it into register P2.
65651 ** P3==1 is the schema version.  P3==2 is the database format.
65652 ** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
65653 ** the main database file and P1==1 is the database file used to store
65654 ** temporary tables.
65655 **
65656 ** There must be a read-lock on the database (either a transaction
65657 ** must be started or there must be an open cursor) before
65658 ** executing this instruction.
65659 */
65660 case OP_ReadCookie: {               /* out2-prerelease */
65661 #if 0  /* local variables moved into u.at */
65662   int iMeta;
65663   int iDb;
65664   int iCookie;
65665 #endif /* local variables moved into u.at */
65666
65667   u.at.iDb = pOp->p1;
65668   u.at.iCookie = pOp->p3;
65669   assert( pOp->p3<SQLITE_N_BTREE_META );
65670   assert( u.at.iDb>=0 && u.at.iDb<db->nDb );
65671   assert( db->aDb[u.at.iDb].pBt!=0 );
65672   assert( (p->btreeMask & (((yDbMask)1)<<u.at.iDb))!=0 );
65673
65674   sqlite3BtreeGetMeta(db->aDb[u.at.iDb].pBt, u.at.iCookie, (u32 *)&u.at.iMeta);
65675   pOut->u.i = u.at.iMeta;
65676   break;
65677 }
65678
65679 /* Opcode: SetCookie P1 P2 P3 * *
65680 **
65681 ** Write the content of register P3 (interpreted as an integer)
65682 ** into cookie number P2 of database P1.  P2==1 is the schema version.  
65683 ** P2==2 is the database format. P2==3 is the recommended pager cache 
65684 ** size, and so forth.  P1==0 is the main database file and P1==1 is the 
65685 ** database file used to store temporary tables.
65686 **
65687 ** A transaction must be started before executing this opcode.
65688 */
65689 case OP_SetCookie: {       /* in3 */
65690 #if 0  /* local variables moved into u.au */
65691   Db *pDb;
65692 #endif /* local variables moved into u.au */
65693   assert( pOp->p2<SQLITE_N_BTREE_META );
65694   assert( pOp->p1>=0 && pOp->p1<db->nDb );
65695   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
65696   u.au.pDb = &db->aDb[pOp->p1];
65697   assert( u.au.pDb->pBt!=0 );
65698   assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
65699   pIn3 = &aMem[pOp->p3];
65700   sqlite3VdbeMemIntegerify(pIn3);
65701   /* See note about index shifting on OP_ReadCookie */
65702   rc = sqlite3BtreeUpdateMeta(u.au.pDb->pBt, pOp->p2, (int)pIn3->u.i);
65703   if( pOp->p2==BTREE_SCHEMA_VERSION ){
65704     /* When the schema cookie changes, record the new cookie internally */
65705     u.au.pDb->pSchema->schema_cookie = (int)pIn3->u.i;
65706     db->flags |= SQLITE_InternChanges;
65707   }else if( pOp->p2==BTREE_FILE_FORMAT ){
65708     /* Record changes in the file format */
65709     u.au.pDb->pSchema->file_format = (u8)pIn3->u.i;
65710   }
65711   if( pOp->p1==1 ){
65712     /* Invalidate all prepared statements whenever the TEMP database
65713     ** schema is changed.  Ticket #1644 */
65714     sqlite3ExpirePreparedStatements(db);
65715     p->expired = 0;
65716   }
65717   break;
65718 }
65719
65720 /* Opcode: VerifyCookie P1 P2 P3 * *
65721 **
65722 ** Check the value of global database parameter number 0 (the
65723 ** schema version) and make sure it is equal to P2 and that the
65724 ** generation counter on the local schema parse equals P3.
65725 **
65726 ** P1 is the database number which is 0 for the main database file
65727 ** and 1 for the file holding temporary tables and some higher number
65728 ** for auxiliary databases.
65729 **
65730 ** The cookie changes its value whenever the database schema changes.
65731 ** This operation is used to detect when that the cookie has changed
65732 ** and that the current process needs to reread the schema.
65733 **
65734 ** Either a transaction needs to have been started or an OP_Open needs
65735 ** to be executed (to establish a read lock) before this opcode is
65736 ** invoked.
65737 */
65738 case OP_VerifyCookie: {
65739 #if 0  /* local variables moved into u.av */
65740   int iMeta;
65741   int iGen;
65742   Btree *pBt;
65743 #endif /* local variables moved into u.av */
65744
65745   assert( pOp->p1>=0 && pOp->p1<db->nDb );
65746   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
65747   assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
65748   u.av.pBt = db->aDb[pOp->p1].pBt;
65749   if( u.av.pBt ){
65750     sqlite3BtreeGetMeta(u.av.pBt, BTREE_SCHEMA_VERSION, (u32 *)&u.av.iMeta);
65751     u.av.iGen = db->aDb[pOp->p1].pSchema->iGeneration;
65752   }else{
65753     u.av.iGen = u.av.iMeta = 0;
65754   }
65755   if( u.av.iMeta!=pOp->p2 || u.av.iGen!=pOp->p3 ){
65756     sqlite3DbFree(db, p->zErrMsg);
65757     p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
65758     /* If the schema-cookie from the database file matches the cookie
65759     ** stored with the in-memory representation of the schema, do
65760     ** not reload the schema from the database file.
65761     **
65762     ** If virtual-tables are in use, this is not just an optimization.
65763     ** Often, v-tables store their data in other SQLite tables, which
65764     ** are queried from within xNext() and other v-table methods using
65765     ** prepared queries. If such a query is out-of-date, we do not want to
65766     ** discard the database schema, as the user code implementing the
65767     ** v-table would have to be ready for the sqlite3_vtab structure itself
65768     ** to be invalidated whenever sqlite3_step() is called from within
65769     ** a v-table method.
65770     */
65771     if( db->aDb[pOp->p1].pSchema->schema_cookie!=u.av.iMeta ){
65772       sqlite3ResetInternalSchema(db, pOp->p1);
65773     }
65774
65775     p->expired = 1;
65776     rc = SQLITE_SCHEMA;
65777   }
65778   break;
65779 }
65780
65781 /* Opcode: OpenRead P1 P2 P3 P4 P5
65782 **
65783 ** Open a read-only cursor for the database table whose root page is
65784 ** P2 in a database file.  The database file is determined by P3. 
65785 ** P3==0 means the main database, P3==1 means the database used for 
65786 ** temporary tables, and P3>1 means used the corresponding attached
65787 ** database.  Give the new cursor an identifier of P1.  The P1
65788 ** values need not be contiguous but all P1 values should be small integers.
65789 ** It is an error for P1 to be negative.
65790 **
65791 ** If P5!=0 then use the content of register P2 as the root page, not
65792 ** the value of P2 itself.
65793 **
65794 ** There will be a read lock on the database whenever there is an
65795 ** open cursor.  If the database was unlocked prior to this instruction
65796 ** then a read lock is acquired as part of this instruction.  A read
65797 ** lock allows other processes to read the database but prohibits
65798 ** any other process from modifying the database.  The read lock is
65799 ** released when all cursors are closed.  If this instruction attempts
65800 ** to get a read lock but fails, the script terminates with an
65801 ** SQLITE_BUSY error code.
65802 **
65803 ** The P4 value may be either an integer (P4_INT32) or a pointer to
65804 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 
65805 ** structure, then said structure defines the content and collating 
65806 ** sequence of the index being opened. Otherwise, if P4 is an integer 
65807 ** value, it is set to the number of columns in the table.
65808 **
65809 ** See also OpenWrite.
65810 */
65811 /* Opcode: OpenWrite P1 P2 P3 P4 P5
65812 **
65813 ** Open a read/write cursor named P1 on the table or index whose root
65814 ** page is P2.  Or if P5!=0 use the content of register P2 to find the
65815 ** root page.
65816 **
65817 ** The P4 value may be either an integer (P4_INT32) or a pointer to
65818 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 
65819 ** structure, then said structure defines the content and collating 
65820 ** sequence of the index being opened. Otherwise, if P4 is an integer 
65821 ** value, it is set to the number of columns in the table, or to the
65822 ** largest index of any column of the table that is actually used.
65823 **
65824 ** This instruction works just like OpenRead except that it opens the cursor
65825 ** in read/write mode.  For a given table, there can be one or more read-only
65826 ** cursors or a single read/write cursor but not both.
65827 **
65828 ** See also OpenRead.
65829 */
65830 case OP_OpenRead:
65831 case OP_OpenWrite: {
65832 #if 0  /* local variables moved into u.aw */
65833   int nField;
65834   KeyInfo *pKeyInfo;
65835   int p2;
65836   int iDb;
65837   int wrFlag;
65838   Btree *pX;
65839   VdbeCursor *pCur;
65840   Db *pDb;
65841 #endif /* local variables moved into u.aw */
65842
65843   if( p->expired ){
65844     rc = SQLITE_ABORT;
65845     break;
65846   }
65847
65848   u.aw.nField = 0;
65849   u.aw.pKeyInfo = 0;
65850   u.aw.p2 = pOp->p2;
65851   u.aw.iDb = pOp->p3;
65852   assert( u.aw.iDb>=0 && u.aw.iDb<db->nDb );
65853   assert( (p->btreeMask & (((yDbMask)1)<<u.aw.iDb))!=0 );
65854   u.aw.pDb = &db->aDb[u.aw.iDb];
65855   u.aw.pX = u.aw.pDb->pBt;
65856   assert( u.aw.pX!=0 );
65857   if( pOp->opcode==OP_OpenWrite ){
65858     u.aw.wrFlag = 1;
65859     assert( sqlite3SchemaMutexHeld(db, u.aw.iDb, 0) );
65860     if( u.aw.pDb->pSchema->file_format < p->minWriteFileFormat ){
65861       p->minWriteFileFormat = u.aw.pDb->pSchema->file_format;
65862     }
65863   }else{
65864     u.aw.wrFlag = 0;
65865   }
65866   if( pOp->p5 ){
65867     assert( u.aw.p2>0 );
65868     assert( u.aw.p2<=p->nMem );
65869     pIn2 = &aMem[u.aw.p2];
65870     assert( memIsValid(pIn2) );
65871     assert( (pIn2->flags & MEM_Int)!=0 );
65872     sqlite3VdbeMemIntegerify(pIn2);
65873     u.aw.p2 = (int)pIn2->u.i;
65874     /* The u.aw.p2 value always comes from a prior OP_CreateTable opcode and
65875     ** that opcode will always set the u.aw.p2 value to 2 or more or else fail.
65876     ** If there were a failure, the prepared statement would have halted
65877     ** before reaching this instruction. */
65878     if( NEVER(u.aw.p2<2) ) {
65879       rc = SQLITE_CORRUPT_BKPT;
65880       goto abort_due_to_error;
65881     }
65882   }
65883   if( pOp->p4type==P4_KEYINFO ){
65884     u.aw.pKeyInfo = pOp->p4.pKeyInfo;
65885     u.aw.pKeyInfo->enc = ENC(p->db);
65886     u.aw.nField = u.aw.pKeyInfo->nField+1;
65887   }else if( pOp->p4type==P4_INT32 ){
65888     u.aw.nField = pOp->p4.i;
65889   }
65890   assert( pOp->p1>=0 );
65891   u.aw.pCur = allocateCursor(p, pOp->p1, u.aw.nField, u.aw.iDb, 1);
65892   if( u.aw.pCur==0 ) goto no_mem;
65893   u.aw.pCur->nullRow = 1;
65894   u.aw.pCur->isOrdered = 1;
65895   rc = sqlite3BtreeCursor(u.aw.pX, u.aw.p2, u.aw.wrFlag, u.aw.pKeyInfo, u.aw.pCur->pCursor);
65896   u.aw.pCur->pKeyInfo = u.aw.pKeyInfo;
65897
65898   /* Since it performs no memory allocation or IO, the only values that
65899   ** sqlite3BtreeCursor() may return are SQLITE_EMPTY and SQLITE_OK.
65900   ** SQLITE_EMPTY is only returned when attempting to open the table
65901   ** rooted at page 1 of a zero-byte database.  */
65902   assert( rc==SQLITE_EMPTY || rc==SQLITE_OK );
65903   if( rc==SQLITE_EMPTY ){
65904     u.aw.pCur->pCursor = 0;
65905     rc = SQLITE_OK;
65906   }
65907
65908   /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of
65909   ** SQLite used to check if the root-page flags were sane at this point
65910   ** and report database corruption if they were not, but this check has
65911   ** since moved into the btree layer.  */
65912   u.aw.pCur->isTable = pOp->p4type!=P4_KEYINFO;
65913   u.aw.pCur->isIndex = !u.aw.pCur->isTable;
65914   break;
65915 }
65916
65917 /* Opcode: OpenEphemeral P1 P2 * P4 *
65918 **
65919 ** Open a new cursor P1 to a transient table.
65920 ** The cursor is always opened read/write even if 
65921 ** the main database is read-only.  The ephemeral
65922 ** table is deleted automatically when the cursor is closed.
65923 **
65924 ** P2 is the number of columns in the ephemeral table.
65925 ** The cursor points to a BTree table if P4==0 and to a BTree index
65926 ** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
65927 ** that defines the format of keys in the index.
65928 **
65929 ** This opcode was once called OpenTemp.  But that created
65930 ** confusion because the term "temp table", might refer either
65931 ** to a TEMP table at the SQL level, or to a table opened by
65932 ** this opcode.  Then this opcode was call OpenVirtual.  But
65933 ** that created confusion with the whole virtual-table idea.
65934 */
65935 /* Opcode: OpenAutoindex P1 P2 * P4 *
65936 **
65937 ** This opcode works the same as OP_OpenEphemeral.  It has a
65938 ** different name to distinguish its use.  Tables created using
65939 ** by this opcode will be used for automatically created transient
65940 ** indices in joins.
65941 */
65942 case OP_OpenAutoindex: 
65943 case OP_OpenEphemeral: {
65944 #if 0  /* local variables moved into u.ax */
65945   VdbeCursor *pCx;
65946 #endif /* local variables moved into u.ax */
65947   static const int vfsFlags =
65948       SQLITE_OPEN_READWRITE |
65949       SQLITE_OPEN_CREATE |
65950       SQLITE_OPEN_EXCLUSIVE |
65951       SQLITE_OPEN_DELETEONCLOSE |
65952       SQLITE_OPEN_TRANSIENT_DB;
65953
65954   assert( pOp->p1>=0 );
65955   u.ax.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
65956   if( u.ax.pCx==0 ) goto no_mem;
65957   u.ax.pCx->nullRow = 1;
65958   rc = sqlite3BtreeOpen(db->pVfs, 0, db, &u.ax.pCx->pBt,
65959                         BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
65960   if( rc==SQLITE_OK ){
65961     rc = sqlite3BtreeBeginTrans(u.ax.pCx->pBt, 1);
65962   }
65963   if( rc==SQLITE_OK ){
65964     /* If a transient index is required, create it by calling
65965     ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
65966     ** opening it. If a transient table is required, just use the
65967     ** automatically created table with root-page 1 (an BLOB_INTKEY table).
65968     */
65969     if( pOp->p4.pKeyInfo ){
65970       int pgno;
65971       assert( pOp->p4type==P4_KEYINFO );
65972       rc = sqlite3BtreeCreateTable(u.ax.pCx->pBt, &pgno, BTREE_BLOBKEY);
65973       if( rc==SQLITE_OK ){
65974         assert( pgno==MASTER_ROOT+1 );
65975         rc = sqlite3BtreeCursor(u.ax.pCx->pBt, pgno, 1,
65976                                 (KeyInfo*)pOp->p4.z, u.ax.pCx->pCursor);
65977         u.ax.pCx->pKeyInfo = pOp->p4.pKeyInfo;
65978         u.ax.pCx->pKeyInfo->enc = ENC(p->db);
65979       }
65980       u.ax.pCx->isTable = 0;
65981     }else{
65982       rc = sqlite3BtreeCursor(u.ax.pCx->pBt, MASTER_ROOT, 1, 0, u.ax.pCx->pCursor);
65983       u.ax.pCx->isTable = 1;
65984     }
65985   }
65986   u.ax.pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
65987   u.ax.pCx->isIndex = !u.ax.pCx->isTable;
65988   break;
65989 }
65990
65991 /* Opcode: OpenPseudo P1 P2 P3 * *
65992 **
65993 ** Open a new cursor that points to a fake table that contains a single
65994 ** row of data.  The content of that one row in the content of memory
65995 ** register P2.  In other words, cursor P1 becomes an alias for the 
65996 ** MEM_Blob content contained in register P2.
65997 **
65998 ** A pseudo-table created by this opcode is used to hold a single
65999 ** row output from the sorter so that the row can be decomposed into
66000 ** individual columns using the OP_Column opcode.  The OP_Column opcode
66001 ** is the only cursor opcode that works with a pseudo-table.
66002 **
66003 ** P3 is the number of fields in the records that will be stored by
66004 ** the pseudo-table.
66005 */
66006 case OP_OpenPseudo: {
66007 #if 0  /* local variables moved into u.ay */
66008   VdbeCursor *pCx;
66009 #endif /* local variables moved into u.ay */
66010
66011   assert( pOp->p1>=0 );
66012   u.ay.pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
66013   if( u.ay.pCx==0 ) goto no_mem;
66014   u.ay.pCx->nullRow = 1;
66015   u.ay.pCx->pseudoTableReg = pOp->p2;
66016   u.ay.pCx->isTable = 1;
66017   u.ay.pCx->isIndex = 0;
66018   break;
66019 }
66020
66021 /* Opcode: Close P1 * * * *
66022 **
66023 ** Close a cursor previously opened as P1.  If P1 is not
66024 ** currently open, this instruction is a no-op.
66025 */
66026 case OP_Close: {
66027   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66028   sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
66029   p->apCsr[pOp->p1] = 0;
66030   break;
66031 }
66032
66033 /* Opcode: SeekGe P1 P2 P3 P4 *
66034 **
66035 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
66036 ** use the value in register P3 as the key.  If cursor P1 refers 
66037 ** to an SQL index, then P3 is the first in an array of P4 registers 
66038 ** that are used as an unpacked index key. 
66039 **
66040 ** Reposition cursor P1 so that  it points to the smallest entry that 
66041 ** is greater than or equal to the key value. If there are no records 
66042 ** greater than or equal to the key and P2 is not zero, then jump to P2.
66043 **
66044 ** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
66045 */
66046 /* Opcode: SeekGt P1 P2 P3 P4 *
66047 **
66048 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
66049 ** use the value in register P3 as a key. If cursor P1 refers 
66050 ** to an SQL index, then P3 is the first in an array of P4 registers 
66051 ** that are used as an unpacked index key. 
66052 **
66053 ** Reposition cursor P1 so that  it points to the smallest entry that 
66054 ** is greater than the key value. If there are no records greater than 
66055 ** the key and P2 is not zero, then jump to P2.
66056 **
66057 ** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
66058 */
66059 /* Opcode: SeekLt P1 P2 P3 P4 * 
66060 **
66061 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
66062 ** use the value in register P3 as a key. If cursor P1 refers 
66063 ** to an SQL index, then P3 is the first in an array of P4 registers 
66064 ** that are used as an unpacked index key. 
66065 **
66066 ** Reposition cursor P1 so that  it points to the largest entry that 
66067 ** is less than the key value. If there are no records less than 
66068 ** the key and P2 is not zero, then jump to P2.
66069 **
66070 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
66071 */
66072 /* Opcode: SeekLe P1 P2 P3 P4 *
66073 **
66074 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
66075 ** use the value in register P3 as a key. If cursor P1 refers 
66076 ** to an SQL index, then P3 is the first in an array of P4 registers 
66077 ** that are used as an unpacked index key. 
66078 **
66079 ** Reposition cursor P1 so that it points to the largest entry that 
66080 ** is less than or equal to the key value. If there are no records 
66081 ** less than or equal to the key and P2 is not zero, then jump to P2.
66082 **
66083 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
66084 */
66085 case OP_SeekLt:         /* jump, in3 */
66086 case OP_SeekLe:         /* jump, in3 */
66087 case OP_SeekGe:         /* jump, in3 */
66088 case OP_SeekGt: {       /* jump, in3 */
66089 #if 0  /* local variables moved into u.az */
66090   int res;
66091   int oc;
66092   VdbeCursor *pC;
66093   UnpackedRecord r;
66094   int nField;
66095   i64 iKey;      /* The rowid we are to seek to */
66096 #endif /* local variables moved into u.az */
66097
66098   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66099   assert( pOp->p2!=0 );
66100   u.az.pC = p->apCsr[pOp->p1];
66101   assert( u.az.pC!=0 );
66102   assert( u.az.pC->pseudoTableReg==0 );
66103   assert( OP_SeekLe == OP_SeekLt+1 );
66104   assert( OP_SeekGe == OP_SeekLt+2 );
66105   assert( OP_SeekGt == OP_SeekLt+3 );
66106   assert( u.az.pC->isOrdered );
66107   if( u.az.pC->pCursor!=0 ){
66108     u.az.oc = pOp->opcode;
66109     u.az.pC->nullRow = 0;
66110     if( u.az.pC->isTable ){
66111       /* The input value in P3 might be of any type: integer, real, string,
66112       ** blob, or NULL.  But it needs to be an integer before we can do
66113       ** the seek, so covert it. */
66114       pIn3 = &aMem[pOp->p3];
66115       applyNumericAffinity(pIn3);
66116       u.az.iKey = sqlite3VdbeIntValue(pIn3);
66117       u.az.pC->rowidIsValid = 0;
66118
66119       /* If the P3 value could not be converted into an integer without
66120       ** loss of information, then special processing is required... */
66121       if( (pIn3->flags & MEM_Int)==0 ){
66122         if( (pIn3->flags & MEM_Real)==0 ){
66123           /* If the P3 value cannot be converted into any kind of a number,
66124           ** then the seek is not possible, so jump to P2 */
66125           pc = pOp->p2 - 1;
66126           break;
66127         }
66128         /* If we reach this point, then the P3 value must be a floating
66129         ** point number. */
66130         assert( (pIn3->flags & MEM_Real)!=0 );
66131
66132         if( u.az.iKey==SMALLEST_INT64 && (pIn3->r<(double)u.az.iKey || pIn3->r>0) ){
66133           /* The P3 value is too large in magnitude to be expressed as an
66134           ** integer. */
66135           u.az.res = 1;
66136           if( pIn3->r<0 ){
66137             if( u.az.oc>=OP_SeekGe ){  assert( u.az.oc==OP_SeekGe || u.az.oc==OP_SeekGt );
66138               rc = sqlite3BtreeFirst(u.az.pC->pCursor, &u.az.res);
66139               if( rc!=SQLITE_OK ) goto abort_due_to_error;
66140             }
66141           }else{
66142             if( u.az.oc<=OP_SeekLe ){  assert( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekLe );
66143               rc = sqlite3BtreeLast(u.az.pC->pCursor, &u.az.res);
66144               if( rc!=SQLITE_OK ) goto abort_due_to_error;
66145             }
66146           }
66147           if( u.az.res ){
66148             pc = pOp->p2 - 1;
66149           }
66150           break;
66151         }else if( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekGe ){
66152           /* Use the ceiling() function to convert real->int */
66153           if( pIn3->r > (double)u.az.iKey ) u.az.iKey++;
66154         }else{
66155           /* Use the floor() function to convert real->int */
66156           assert( u.az.oc==OP_SeekLe || u.az.oc==OP_SeekGt );
66157           if( pIn3->r < (double)u.az.iKey ) u.az.iKey--;
66158         }
66159       }
66160       rc = sqlite3BtreeMovetoUnpacked(u.az.pC->pCursor, 0, (u64)u.az.iKey, 0, &u.az.res);
66161       if( rc!=SQLITE_OK ){
66162         goto abort_due_to_error;
66163       }
66164       if( u.az.res==0 ){
66165         u.az.pC->rowidIsValid = 1;
66166         u.az.pC->lastRowid = u.az.iKey;
66167       }
66168     }else{
66169       u.az.nField = pOp->p4.i;
66170       assert( pOp->p4type==P4_INT32 );
66171       assert( u.az.nField>0 );
66172       u.az.r.pKeyInfo = u.az.pC->pKeyInfo;
66173       u.az.r.nField = (u16)u.az.nField;
66174
66175       /* The next line of code computes as follows, only faster:
66176       **   if( u.az.oc==OP_SeekGt || u.az.oc==OP_SeekLe ){
66177       **     u.az.r.flags = UNPACKED_INCRKEY;
66178       **   }else{
66179       **     u.az.r.flags = 0;
66180       **   }
66181       */
66182       u.az.r.flags = (u16)(UNPACKED_INCRKEY * (1 & (u.az.oc - OP_SeekLt)));
66183       assert( u.az.oc!=OP_SeekGt || u.az.r.flags==UNPACKED_INCRKEY );
66184       assert( u.az.oc!=OP_SeekLe || u.az.r.flags==UNPACKED_INCRKEY );
66185       assert( u.az.oc!=OP_SeekGe || u.az.r.flags==0 );
66186       assert( u.az.oc!=OP_SeekLt || u.az.r.flags==0 );
66187
66188       u.az.r.aMem = &aMem[pOp->p3];
66189 #ifdef SQLITE_DEBUG
66190       { int i; for(i=0; i<u.az.r.nField; i++) assert( memIsValid(&u.az.r.aMem[i]) ); }
66191 #endif
66192       ExpandBlob(u.az.r.aMem);
66193       rc = sqlite3BtreeMovetoUnpacked(u.az.pC->pCursor, &u.az.r, 0, 0, &u.az.res);
66194       if( rc!=SQLITE_OK ){
66195         goto abort_due_to_error;
66196       }
66197       u.az.pC->rowidIsValid = 0;
66198     }
66199     u.az.pC->deferredMoveto = 0;
66200     u.az.pC->cacheStatus = CACHE_STALE;
66201 #ifdef SQLITE_TEST
66202     sqlite3_search_count++;
66203 #endif
66204     if( u.az.oc>=OP_SeekGe ){  assert( u.az.oc==OP_SeekGe || u.az.oc==OP_SeekGt );
66205       if( u.az.res<0 || (u.az.res==0 && u.az.oc==OP_SeekGt) ){
66206         rc = sqlite3BtreeNext(u.az.pC->pCursor, &u.az.res);
66207         if( rc!=SQLITE_OK ) goto abort_due_to_error;
66208         u.az.pC->rowidIsValid = 0;
66209       }else{
66210         u.az.res = 0;
66211       }
66212     }else{
66213       assert( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekLe );
66214       if( u.az.res>0 || (u.az.res==0 && u.az.oc==OP_SeekLt) ){
66215         rc = sqlite3BtreePrevious(u.az.pC->pCursor, &u.az.res);
66216         if( rc!=SQLITE_OK ) goto abort_due_to_error;
66217         u.az.pC->rowidIsValid = 0;
66218       }else{
66219         /* u.az.res might be negative because the table is empty.  Check to
66220         ** see if this is the case.
66221         */
66222         u.az.res = sqlite3BtreeEof(u.az.pC->pCursor);
66223       }
66224     }
66225     assert( pOp->p2>0 );
66226     if( u.az.res ){
66227       pc = pOp->p2 - 1;
66228     }
66229   }else{
66230     /* This happens when attempting to open the sqlite3_master table
66231     ** for read access returns SQLITE_EMPTY. In this case always
66232     ** take the jump (since there are no records in the table).
66233     */
66234     pc = pOp->p2 - 1;
66235   }
66236   break;
66237 }
66238
66239 /* Opcode: Seek P1 P2 * * *
66240 **
66241 ** P1 is an open table cursor and P2 is a rowid integer.  Arrange
66242 ** for P1 to move so that it points to the rowid given by P2.
66243 **
66244 ** This is actually a deferred seek.  Nothing actually happens until
66245 ** the cursor is used to read a record.  That way, if no reads
66246 ** occur, no unnecessary I/O happens.
66247 */
66248 case OP_Seek: {    /* in2 */
66249 #if 0  /* local variables moved into u.ba */
66250   VdbeCursor *pC;
66251 #endif /* local variables moved into u.ba */
66252
66253   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66254   u.ba.pC = p->apCsr[pOp->p1];
66255   assert( u.ba.pC!=0 );
66256   if( ALWAYS(u.ba.pC->pCursor!=0) ){
66257     assert( u.ba.pC->isTable );
66258     u.ba.pC->nullRow = 0;
66259     pIn2 = &aMem[pOp->p2];
66260     u.ba.pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
66261     u.ba.pC->rowidIsValid = 0;
66262     u.ba.pC->deferredMoveto = 1;
66263   }
66264   break;
66265 }
66266   
66267
66268 /* Opcode: Found P1 P2 P3 P4 *
66269 **
66270 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
66271 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
66272 ** record.
66273 **
66274 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
66275 ** is a prefix of any entry in P1 then a jump is made to P2 and
66276 ** P1 is left pointing at the matching entry.
66277 */
66278 /* Opcode: NotFound P1 P2 P3 P4 *
66279 **
66280 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
66281 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
66282 ** record.
66283 ** 
66284 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
66285 ** is not the prefix of any entry in P1 then a jump is made to P2.  If P1 
66286 ** does contain an entry whose prefix matches the P3/P4 record then control
66287 ** falls through to the next instruction and P1 is left pointing at the
66288 ** matching entry.
66289 **
66290 ** See also: Found, NotExists, IsUnique
66291 */
66292 case OP_NotFound:       /* jump, in3 */
66293 case OP_Found: {        /* jump, in3 */
66294 #if 0  /* local variables moved into u.bb */
66295   int alreadyExists;
66296   VdbeCursor *pC;
66297   int res;
66298   UnpackedRecord *pIdxKey;
66299   UnpackedRecord r;
66300   char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
66301 #endif /* local variables moved into u.bb */
66302
66303 #ifdef SQLITE_TEST
66304   sqlite3_found_count++;
66305 #endif
66306
66307   u.bb.alreadyExists = 0;
66308   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66309   assert( pOp->p4type==P4_INT32 );
66310   u.bb.pC = p->apCsr[pOp->p1];
66311   assert( u.bb.pC!=0 );
66312   pIn3 = &aMem[pOp->p3];
66313   if( ALWAYS(u.bb.pC->pCursor!=0) ){
66314
66315     assert( u.bb.pC->isTable==0 );
66316     if( pOp->p4.i>0 ){
66317       u.bb.r.pKeyInfo = u.bb.pC->pKeyInfo;
66318       u.bb.r.nField = (u16)pOp->p4.i;
66319       u.bb.r.aMem = pIn3;
66320 #ifdef SQLITE_DEBUG
66321       { int i; for(i=0; i<u.bb.r.nField; i++) assert( memIsValid(&u.bb.r.aMem[i]) ); }
66322 #endif
66323       u.bb.r.flags = UNPACKED_PREFIX_MATCH;
66324       u.bb.pIdxKey = &u.bb.r;
66325     }else{
66326       assert( pIn3->flags & MEM_Blob );
66327       assert( (pIn3->flags & MEM_Zero)==0 );  /* zeroblobs already expanded */
66328       u.bb.pIdxKey = sqlite3VdbeRecordUnpack(u.bb.pC->pKeyInfo, pIn3->n, pIn3->z,
66329                                         u.bb.aTempRec, sizeof(u.bb.aTempRec));
66330       if( u.bb.pIdxKey==0 ){
66331         goto no_mem;
66332       }
66333       u.bb.pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
66334     }
66335     rc = sqlite3BtreeMovetoUnpacked(u.bb.pC->pCursor, u.bb.pIdxKey, 0, 0, &u.bb.res);
66336     if( pOp->p4.i==0 ){
66337       sqlite3VdbeDeleteUnpackedRecord(u.bb.pIdxKey);
66338     }
66339     if( rc!=SQLITE_OK ){
66340       break;
66341     }
66342     u.bb.alreadyExists = (u.bb.res==0);
66343     u.bb.pC->deferredMoveto = 0;
66344     u.bb.pC->cacheStatus = CACHE_STALE;
66345   }
66346   if( pOp->opcode==OP_Found ){
66347     if( u.bb.alreadyExists ) pc = pOp->p2 - 1;
66348   }else{
66349     if( !u.bb.alreadyExists ) pc = pOp->p2 - 1;
66350   }
66351   break;
66352 }
66353
66354 /* Opcode: IsUnique P1 P2 P3 P4 *
66355 **
66356 ** Cursor P1 is open on an index b-tree - that is to say, a btree which
66357 ** no data and where the key are records generated by OP_MakeRecord with
66358 ** the list field being the integer ROWID of the entry that the index
66359 ** entry refers to.
66360 **
66361 ** The P3 register contains an integer record number. Call this record 
66362 ** number R. Register P4 is the first in a set of N contiguous registers
66363 ** that make up an unpacked index key that can be used with cursor P1.
66364 ** The value of N can be inferred from the cursor. N includes the rowid
66365 ** value appended to the end of the index record. This rowid value may
66366 ** or may not be the same as R.
66367 **
66368 ** If any of the N registers beginning with register P4 contains a NULL
66369 ** value, jump immediately to P2.
66370 **
66371 ** Otherwise, this instruction checks if cursor P1 contains an entry
66372 ** where the first (N-1) fields match but the rowid value at the end
66373 ** of the index entry is not R. If there is no such entry, control jumps
66374 ** to instruction P2. Otherwise, the rowid of the conflicting index
66375 ** entry is copied to register P3 and control falls through to the next
66376 ** instruction.
66377 **
66378 ** See also: NotFound, NotExists, Found
66379 */
66380 case OP_IsUnique: {        /* jump, in3 */
66381 #if 0  /* local variables moved into u.bc */
66382   u16 ii;
66383   VdbeCursor *pCx;
66384   BtCursor *pCrsr;
66385   u16 nField;
66386   Mem *aMx;
66387   UnpackedRecord r;                  /* B-Tree index search key */
66388   i64 R;                             /* Rowid stored in register P3 */
66389 #endif /* local variables moved into u.bc */
66390
66391   pIn3 = &aMem[pOp->p3];
66392   u.bc.aMx = &aMem[pOp->p4.i];
66393   /* Assert that the values of parameters P1 and P4 are in range. */
66394   assert( pOp->p4type==P4_INT32 );
66395   assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
66396   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66397
66398   /* Find the index cursor. */
66399   u.bc.pCx = p->apCsr[pOp->p1];
66400   assert( u.bc.pCx->deferredMoveto==0 );
66401   u.bc.pCx->seekResult = 0;
66402   u.bc.pCx->cacheStatus = CACHE_STALE;
66403   u.bc.pCrsr = u.bc.pCx->pCursor;
66404
66405   /* If any of the values are NULL, take the jump. */
66406   u.bc.nField = u.bc.pCx->pKeyInfo->nField;
66407   for(u.bc.ii=0; u.bc.ii<u.bc.nField; u.bc.ii++){
66408     if( u.bc.aMx[u.bc.ii].flags & MEM_Null ){
66409       pc = pOp->p2 - 1;
66410       u.bc.pCrsr = 0;
66411       break;
66412     }
66413   }
66414   assert( (u.bc.aMx[u.bc.nField].flags & MEM_Null)==0 );
66415
66416   if( u.bc.pCrsr!=0 ){
66417     /* Populate the index search key. */
66418     u.bc.r.pKeyInfo = u.bc.pCx->pKeyInfo;
66419     u.bc.r.nField = u.bc.nField + 1;
66420     u.bc.r.flags = UNPACKED_PREFIX_SEARCH;
66421     u.bc.r.aMem = u.bc.aMx;
66422 #ifdef SQLITE_DEBUG
66423     { int i; for(i=0; i<u.bc.r.nField; i++) assert( memIsValid(&u.bc.r.aMem[i]) ); }
66424 #endif
66425
66426     /* Extract the value of u.bc.R from register P3. */
66427     sqlite3VdbeMemIntegerify(pIn3);
66428     u.bc.R = pIn3->u.i;
66429
66430     /* Search the B-Tree index. If no conflicting record is found, jump
66431     ** to P2. Otherwise, copy the rowid of the conflicting record to
66432     ** register P3 and fall through to the next instruction.  */
66433     rc = sqlite3BtreeMovetoUnpacked(u.bc.pCrsr, &u.bc.r, 0, 0, &u.bc.pCx->seekResult);
66434     if( (u.bc.r.flags & UNPACKED_PREFIX_SEARCH) || u.bc.r.rowid==u.bc.R ){
66435       pc = pOp->p2 - 1;
66436     }else{
66437       pIn3->u.i = u.bc.r.rowid;
66438     }
66439   }
66440   break;
66441 }
66442
66443 /* Opcode: NotExists P1 P2 P3 * *
66444 **
66445 ** Use the content of register P3 as an integer key.  If a record 
66446 ** with that key does not exist in table of P1, then jump to P2. 
66447 ** If the record does exist, then fall through.  The cursor is left 
66448 ** pointing to the record if it exists.
66449 **
66450 ** The difference between this operation and NotFound is that this
66451 ** operation assumes the key is an integer and that P1 is a table whereas
66452 ** NotFound assumes key is a blob constructed from MakeRecord and
66453 ** P1 is an index.
66454 **
66455 ** See also: Found, NotFound, IsUnique
66456 */
66457 case OP_NotExists: {        /* jump, in3 */
66458 #if 0  /* local variables moved into u.bd */
66459   VdbeCursor *pC;
66460   BtCursor *pCrsr;
66461   int res;
66462   u64 iKey;
66463 #endif /* local variables moved into u.bd */
66464
66465   pIn3 = &aMem[pOp->p3];
66466   assert( pIn3->flags & MEM_Int );
66467   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66468   u.bd.pC = p->apCsr[pOp->p1];
66469   assert( u.bd.pC!=0 );
66470   assert( u.bd.pC->isTable );
66471   assert( u.bd.pC->pseudoTableReg==0 );
66472   u.bd.pCrsr = u.bd.pC->pCursor;
66473   if( u.bd.pCrsr!=0 ){
66474     u.bd.res = 0;
66475     u.bd.iKey = pIn3->u.i;
66476     rc = sqlite3BtreeMovetoUnpacked(u.bd.pCrsr, 0, u.bd.iKey, 0, &u.bd.res);
66477     u.bd.pC->lastRowid = pIn3->u.i;
66478     u.bd.pC->rowidIsValid = u.bd.res==0 ?1:0;
66479     u.bd.pC->nullRow = 0;
66480     u.bd.pC->cacheStatus = CACHE_STALE;
66481     u.bd.pC->deferredMoveto = 0;
66482     if( u.bd.res!=0 ){
66483       pc = pOp->p2 - 1;
66484       assert( u.bd.pC->rowidIsValid==0 );
66485     }
66486     u.bd.pC->seekResult = u.bd.res;
66487   }else{
66488     /* This happens when an attempt to open a read cursor on the
66489     ** sqlite_master table returns SQLITE_EMPTY.
66490     */
66491     pc = pOp->p2 - 1;
66492     assert( u.bd.pC->rowidIsValid==0 );
66493     u.bd.pC->seekResult = 0;
66494   }
66495   break;
66496 }
66497
66498 /* Opcode: Sequence P1 P2 * * *
66499 **
66500 ** Find the next available sequence number for cursor P1.
66501 ** Write the sequence number into register P2.
66502 ** The sequence number on the cursor is incremented after this
66503 ** instruction.  
66504 */
66505 case OP_Sequence: {           /* out2-prerelease */
66506   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66507   assert( p->apCsr[pOp->p1]!=0 );
66508   pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
66509   break;
66510 }
66511
66512
66513 /* Opcode: NewRowid P1 P2 P3 * *
66514 **
66515 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
66516 ** The record number is not previously used as a key in the database
66517 ** table that cursor P1 points to.  The new record number is written
66518 ** written to register P2.
66519 **
66520 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds 
66521 ** the largest previously generated record number. No new record numbers are
66522 ** allowed to be less than this value. When this value reaches its maximum, 
66523 ** an SQLITE_FULL error is generated. The P3 register is updated with the '
66524 ** generated record number. This P3 mechanism is used to help implement the
66525 ** AUTOINCREMENT feature.
66526 */
66527 case OP_NewRowid: {           /* out2-prerelease */
66528 #if 0  /* local variables moved into u.be */
66529   i64 v;                 /* The new rowid */
66530   VdbeCursor *pC;        /* Cursor of table to get the new rowid */
66531   int res;               /* Result of an sqlite3BtreeLast() */
66532   int cnt;               /* Counter to limit the number of searches */
66533   Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
66534   VdbeFrame *pFrame;     /* Root frame of VDBE */
66535 #endif /* local variables moved into u.be */
66536
66537   u.be.v = 0;
66538   u.be.res = 0;
66539   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66540   u.be.pC = p->apCsr[pOp->p1];
66541   assert( u.be.pC!=0 );
66542   if( NEVER(u.be.pC->pCursor==0) ){
66543     /* The zero initialization above is all that is needed */
66544   }else{
66545     /* The next rowid or record number (different terms for the same
66546     ** thing) is obtained in a two-step algorithm.
66547     **
66548     ** First we attempt to find the largest existing rowid and add one
66549     ** to that.  But if the largest existing rowid is already the maximum
66550     ** positive integer, we have to fall through to the second
66551     ** probabilistic algorithm
66552     **
66553     ** The second algorithm is to select a rowid at random and see if
66554     ** it already exists in the table.  If it does not exist, we have
66555     ** succeeded.  If the random rowid does exist, we select a new one
66556     ** and try again, up to 100 times.
66557     */
66558     assert( u.be.pC->isTable );
66559
66560 #ifdef SQLITE_32BIT_ROWID
66561 #   define MAX_ROWID 0x7fffffff
66562 #else
66563     /* Some compilers complain about constants of the form 0x7fffffffffffffff.
66564     ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
66565     ** to provide the constant while making all compilers happy.
66566     */
66567 #   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
66568 #endif
66569
66570     if( !u.be.pC->useRandomRowid ){
66571       u.be.v = sqlite3BtreeGetCachedRowid(u.be.pC->pCursor);
66572       if( u.be.v==0 ){
66573         rc = sqlite3BtreeLast(u.be.pC->pCursor, &u.be.res);
66574         if( rc!=SQLITE_OK ){
66575           goto abort_due_to_error;
66576         }
66577         if( u.be.res ){
66578           u.be.v = 1;   /* IMP: R-61914-48074 */
66579         }else{
66580           assert( sqlite3BtreeCursorIsValid(u.be.pC->pCursor) );
66581           rc = sqlite3BtreeKeySize(u.be.pC->pCursor, &u.be.v);
66582           assert( rc==SQLITE_OK );   /* Cannot fail following BtreeLast() */
66583           if( u.be.v==MAX_ROWID ){
66584             u.be.pC->useRandomRowid = 1;
66585           }else{
66586             u.be.v++;   /* IMP: R-29538-34987 */
66587           }
66588         }
66589       }
66590
66591 #ifndef SQLITE_OMIT_AUTOINCREMENT
66592       if( pOp->p3 ){
66593         /* Assert that P3 is a valid memory cell. */
66594         assert( pOp->p3>0 );
66595         if( p->pFrame ){
66596           for(u.be.pFrame=p->pFrame; u.be.pFrame->pParent; u.be.pFrame=u.be.pFrame->pParent);
66597           /* Assert that P3 is a valid memory cell. */
66598           assert( pOp->p3<=u.be.pFrame->nMem );
66599           u.be.pMem = &u.be.pFrame->aMem[pOp->p3];
66600         }else{
66601           /* Assert that P3 is a valid memory cell. */
66602           assert( pOp->p3<=p->nMem );
66603           u.be.pMem = &aMem[pOp->p3];
66604           memAboutToChange(p, u.be.pMem);
66605         }
66606         assert( memIsValid(u.be.pMem) );
66607
66608         REGISTER_TRACE(pOp->p3, u.be.pMem);
66609         sqlite3VdbeMemIntegerify(u.be.pMem);
66610         assert( (u.be.pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
66611         if( u.be.pMem->u.i==MAX_ROWID || u.be.pC->useRandomRowid ){
66612           rc = SQLITE_FULL;   /* IMP: R-12275-61338 */
66613           goto abort_due_to_error;
66614         }
66615         if( u.be.v<u.be.pMem->u.i+1 ){
66616           u.be.v = u.be.pMem->u.i + 1;
66617         }
66618         u.be.pMem->u.i = u.be.v;
66619       }
66620 #endif
66621
66622       sqlite3BtreeSetCachedRowid(u.be.pC->pCursor, u.be.v<MAX_ROWID ? u.be.v+1 : 0);
66623     }
66624     if( u.be.pC->useRandomRowid ){
66625       /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
66626       ** largest possible integer (9223372036854775807) then the database
66627       ** engine starts picking positive candidate ROWIDs at random until
66628       ** it finds one that is not previously used. */
66629       assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
66630                              ** an AUTOINCREMENT table. */
66631       /* on the first attempt, simply do one more than previous */
66632       u.be.v = lastRowid;
66633       u.be.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
66634       u.be.v++; /* ensure non-zero */
66635       u.be.cnt = 0;
66636       while(   ((rc = sqlite3BtreeMovetoUnpacked(u.be.pC->pCursor, 0, (u64)u.be.v,
66637                                                  0, &u.be.res))==SQLITE_OK)
66638             && (u.be.res==0)
66639             && (++u.be.cnt<100)){
66640         /* collision - try another random rowid */
66641         sqlite3_randomness(sizeof(u.be.v), &u.be.v);
66642         if( u.be.cnt<5 ){
66643           /* try "small" random rowids for the initial attempts */
66644           u.be.v &= 0xffffff;
66645         }else{
66646           u.be.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
66647         }
66648         u.be.v++; /* ensure non-zero */
66649       }
66650       if( rc==SQLITE_OK && u.be.res==0 ){
66651         rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
66652         goto abort_due_to_error;
66653       }
66654       assert( u.be.v>0 );  /* EV: R-40812-03570 */
66655     }
66656     u.be.pC->rowidIsValid = 0;
66657     u.be.pC->deferredMoveto = 0;
66658     u.be.pC->cacheStatus = CACHE_STALE;
66659   }
66660   pOut->u.i = u.be.v;
66661   break;
66662 }
66663
66664 /* Opcode: Insert P1 P2 P3 P4 P5
66665 **
66666 ** Write an entry into the table of cursor P1.  A new entry is
66667 ** created if it doesn't already exist or the data for an existing
66668 ** entry is overwritten.  The data is the value MEM_Blob stored in register
66669 ** number P2. The key is stored in register P3. The key must
66670 ** be a MEM_Int.
66671 **
66672 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
66673 ** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
66674 ** then rowid is stored for subsequent return by the
66675 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
66676 **
66677 ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
66678 ** the last seek operation (OP_NotExists) was a success, then this
66679 ** operation will not attempt to find the appropriate row before doing
66680 ** the insert but will instead overwrite the row that the cursor is
66681 ** currently pointing to.  Presumably, the prior OP_NotExists opcode
66682 ** has already positioned the cursor correctly.  This is an optimization
66683 ** that boosts performance by avoiding redundant seeks.
66684 **
66685 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
66686 ** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
66687 ** is part of an INSERT operation.  The difference is only important to
66688 ** the update hook.
66689 **
66690 ** Parameter P4 may point to a string containing the table-name, or
66691 ** may be NULL. If it is not NULL, then the update-hook 
66692 ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
66693 **
66694 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
66695 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
66696 ** and register P2 becomes ephemeral.  If the cursor is changed, the
66697 ** value of register P2 will then change.  Make sure this does not
66698 ** cause any problems.)
66699 **
66700 ** This instruction only works on tables.  The equivalent instruction
66701 ** for indices is OP_IdxInsert.
66702 */
66703 /* Opcode: InsertInt P1 P2 P3 P4 P5
66704 **
66705 ** This works exactly like OP_Insert except that the key is the
66706 ** integer value P3, not the value of the integer stored in register P3.
66707 */
66708 case OP_Insert: 
66709 case OP_InsertInt: {
66710 #if 0  /* local variables moved into u.bf */
66711   Mem *pData;       /* MEM cell holding data for the record to be inserted */
66712   Mem *pKey;        /* MEM cell holding key  for the record */
66713   i64 iKey;         /* The integer ROWID or key for the record to be inserted */
66714   VdbeCursor *pC;   /* Cursor to table into which insert is written */
66715   int nZero;        /* Number of zero-bytes to append */
66716   int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
66717   const char *zDb;  /* database name - used by the update hook */
66718   const char *zTbl; /* Table name - used by the opdate hook */
66719   int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
66720 #endif /* local variables moved into u.bf */
66721
66722   u.bf.pData = &aMem[pOp->p2];
66723   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66724   assert( memIsValid(u.bf.pData) );
66725   u.bf.pC = p->apCsr[pOp->p1];
66726   assert( u.bf.pC!=0 );
66727   assert( u.bf.pC->pCursor!=0 );
66728   assert( u.bf.pC->pseudoTableReg==0 );
66729   assert( u.bf.pC->isTable );
66730   REGISTER_TRACE(pOp->p2, u.bf.pData);
66731
66732   if( pOp->opcode==OP_Insert ){
66733     u.bf.pKey = &aMem[pOp->p3];
66734     assert( u.bf.pKey->flags & MEM_Int );
66735     assert( memIsValid(u.bf.pKey) );
66736     REGISTER_TRACE(pOp->p3, u.bf.pKey);
66737     u.bf.iKey = u.bf.pKey->u.i;
66738   }else{
66739     assert( pOp->opcode==OP_InsertInt );
66740     u.bf.iKey = pOp->p3;
66741   }
66742
66743   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
66744   if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = u.bf.iKey;
66745   if( u.bf.pData->flags & MEM_Null ){
66746     u.bf.pData->z = 0;
66747     u.bf.pData->n = 0;
66748   }else{
66749     assert( u.bf.pData->flags & (MEM_Blob|MEM_Str) );
66750   }
66751   u.bf.seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bf.pC->seekResult : 0);
66752   if( u.bf.pData->flags & MEM_Zero ){
66753     u.bf.nZero = u.bf.pData->u.nZero;
66754   }else{
66755     u.bf.nZero = 0;
66756   }
66757   sqlite3BtreeSetCachedRowid(u.bf.pC->pCursor, 0);
66758   rc = sqlite3BtreeInsert(u.bf.pC->pCursor, 0, u.bf.iKey,
66759                           u.bf.pData->z, u.bf.pData->n, u.bf.nZero,
66760                           pOp->p5 & OPFLAG_APPEND, u.bf.seekResult
66761   );
66762   u.bf.pC->rowidIsValid = 0;
66763   u.bf.pC->deferredMoveto = 0;
66764   u.bf.pC->cacheStatus = CACHE_STALE;
66765
66766   /* Invoke the update-hook if required. */
66767   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
66768     u.bf.zDb = db->aDb[u.bf.pC->iDb].zName;
66769     u.bf.zTbl = pOp->p4.z;
66770     u.bf.op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
66771     assert( u.bf.pC->isTable );
66772     db->xUpdateCallback(db->pUpdateArg, u.bf.op, u.bf.zDb, u.bf.zTbl, u.bf.iKey);
66773     assert( u.bf.pC->iDb>=0 );
66774   }
66775   break;
66776 }
66777
66778 /* Opcode: Delete P1 P2 * P4 *
66779 **
66780 ** Delete the record at which the P1 cursor is currently pointing.
66781 **
66782 ** The cursor will be left pointing at either the next or the previous
66783 ** record in the table. If it is left pointing at the next record, then
66784 ** the next Next instruction will be a no-op.  Hence it is OK to delete
66785 ** a record from within an Next loop.
66786 **
66787 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
66788 ** incremented (otherwise not).
66789 **
66790 ** P1 must not be pseudo-table.  It has to be a real table with
66791 ** multiple rows.
66792 **
66793 ** If P4 is not NULL, then it is the name of the table that P1 is
66794 ** pointing to.  The update hook will be invoked, if it exists.
66795 ** If P4 is not NULL then the P1 cursor must have been positioned
66796 ** using OP_NotFound prior to invoking this opcode.
66797 */
66798 case OP_Delete: {
66799 #if 0  /* local variables moved into u.bg */
66800   i64 iKey;
66801   VdbeCursor *pC;
66802 #endif /* local variables moved into u.bg */
66803
66804   u.bg.iKey = 0;
66805   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66806   u.bg.pC = p->apCsr[pOp->p1];
66807   assert( u.bg.pC!=0 );
66808   assert( u.bg.pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
66809
66810   /* If the update-hook will be invoked, set u.bg.iKey to the rowid of the
66811   ** row being deleted.
66812   */
66813   if( db->xUpdateCallback && pOp->p4.z ){
66814     assert( u.bg.pC->isTable );
66815     assert( u.bg.pC->rowidIsValid );  /* lastRowid set by previous OP_NotFound */
66816     u.bg.iKey = u.bg.pC->lastRowid;
66817   }
66818
66819   /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
66820   ** OP_Column on the same table without any intervening operations that
66821   ** might move or invalidate the cursor.  Hence cursor u.bg.pC is always pointing
66822   ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
66823   ** below is always a no-op and cannot fail.  We will run it anyhow, though,
66824   ** to guard against future changes to the code generator.
66825   **/
66826   assert( u.bg.pC->deferredMoveto==0 );
66827   rc = sqlite3VdbeCursorMoveto(u.bg.pC);
66828   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
66829
66830   sqlite3BtreeSetCachedRowid(u.bg.pC->pCursor, 0);
66831   rc = sqlite3BtreeDelete(u.bg.pC->pCursor);
66832   u.bg.pC->cacheStatus = CACHE_STALE;
66833
66834   /* Invoke the update-hook if required. */
66835   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
66836     const char *zDb = db->aDb[u.bg.pC->iDb].zName;
66837     const char *zTbl = pOp->p4.z;
66838     db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, u.bg.iKey);
66839     assert( u.bg.pC->iDb>=0 );
66840   }
66841   if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
66842   break;
66843 }
66844 /* Opcode: ResetCount * * * * *
66845 **
66846 ** The value of the change counter is copied to the database handle
66847 ** change counter (returned by subsequent calls to sqlite3_changes()).
66848 ** Then the VMs internal change counter resets to 0.
66849 ** This is used by trigger programs.
66850 */
66851 case OP_ResetCount: {
66852   sqlite3VdbeSetChanges(db, p->nChange);
66853   p->nChange = 0;
66854   break;
66855 }
66856
66857 /* Opcode: RowData P1 P2 * * *
66858 **
66859 ** Write into register P2 the complete row data for cursor P1.
66860 ** There is no interpretation of the data.  
66861 ** It is just copied onto the P2 register exactly as 
66862 ** it is found in the database file.
66863 **
66864 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
66865 ** of a real table, not a pseudo-table.
66866 */
66867 /* Opcode: RowKey P1 P2 * * *
66868 **
66869 ** Write into register P2 the complete row key for cursor P1.
66870 ** There is no interpretation of the data.  
66871 ** The key is copied onto the P3 register exactly as 
66872 ** it is found in the database file.
66873 **
66874 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
66875 ** of a real table, not a pseudo-table.
66876 */
66877 case OP_RowKey:
66878 case OP_RowData: {
66879 #if 0  /* local variables moved into u.bh */
66880   VdbeCursor *pC;
66881   BtCursor *pCrsr;
66882   u32 n;
66883   i64 n64;
66884 #endif /* local variables moved into u.bh */
66885
66886   pOut = &aMem[pOp->p2];
66887   memAboutToChange(p, pOut);
66888
66889   /* Note that RowKey and RowData are really exactly the same instruction */
66890   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66891   u.bh.pC = p->apCsr[pOp->p1];
66892   assert( u.bh.pC->isTable || pOp->opcode==OP_RowKey );
66893   assert( u.bh.pC->isIndex || pOp->opcode==OP_RowData );
66894   assert( u.bh.pC!=0 );
66895   assert( u.bh.pC->nullRow==0 );
66896   assert( u.bh.pC->pseudoTableReg==0 );
66897   assert( u.bh.pC->pCursor!=0 );
66898   u.bh.pCrsr = u.bh.pC->pCursor;
66899   assert( sqlite3BtreeCursorIsValid(u.bh.pCrsr) );
66900
66901   /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
66902   ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
66903   ** the cursor.  Hence the following sqlite3VdbeCursorMoveto() call is always
66904   ** a no-op and can never fail.  But we leave it in place as a safety.
66905   */
66906   assert( u.bh.pC->deferredMoveto==0 );
66907   rc = sqlite3VdbeCursorMoveto(u.bh.pC);
66908   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
66909
66910   if( u.bh.pC->isIndex ){
66911     assert( !u.bh.pC->isTable );
66912     rc = sqlite3BtreeKeySize(u.bh.pCrsr, &u.bh.n64);
66913     assert( rc==SQLITE_OK );    /* True because of CursorMoveto() call above */
66914     if( u.bh.n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
66915       goto too_big;
66916     }
66917     u.bh.n = (u32)u.bh.n64;
66918   }else{
66919     rc = sqlite3BtreeDataSize(u.bh.pCrsr, &u.bh.n);
66920     assert( rc==SQLITE_OK );    /* DataSize() cannot fail */
66921     if( u.bh.n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
66922       goto too_big;
66923     }
66924   }
66925   if( sqlite3VdbeMemGrow(pOut, u.bh.n, 0) ){
66926     goto no_mem;
66927   }
66928   pOut->n = u.bh.n;
66929   MemSetTypeFlag(pOut, MEM_Blob);
66930   if( u.bh.pC->isIndex ){
66931     rc = sqlite3BtreeKey(u.bh.pCrsr, 0, u.bh.n, pOut->z);
66932   }else{
66933     rc = sqlite3BtreeData(u.bh.pCrsr, 0, u.bh.n, pOut->z);
66934   }
66935   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
66936   UPDATE_MAX_BLOBSIZE(pOut);
66937   break;
66938 }
66939
66940 /* Opcode: Rowid P1 P2 * * *
66941 **
66942 ** Store in register P2 an integer which is the key of the table entry that
66943 ** P1 is currently point to.
66944 **
66945 ** P1 can be either an ordinary table or a virtual table.  There used to
66946 ** be a separate OP_VRowid opcode for use with virtual tables, but this
66947 ** one opcode now works for both table types.
66948 */
66949 case OP_Rowid: {                 /* out2-prerelease */
66950 #if 0  /* local variables moved into u.bi */
66951   VdbeCursor *pC;
66952   i64 v;
66953   sqlite3_vtab *pVtab;
66954   const sqlite3_module *pModule;
66955 #endif /* local variables moved into u.bi */
66956
66957   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66958   u.bi.pC = p->apCsr[pOp->p1];
66959   assert( u.bi.pC!=0 );
66960   assert( u.bi.pC->pseudoTableReg==0 );
66961   if( u.bi.pC->nullRow ){
66962     pOut->flags = MEM_Null;
66963     break;
66964   }else if( u.bi.pC->deferredMoveto ){
66965     u.bi.v = u.bi.pC->movetoTarget;
66966 #ifndef SQLITE_OMIT_VIRTUALTABLE
66967   }else if( u.bi.pC->pVtabCursor ){
66968     u.bi.pVtab = u.bi.pC->pVtabCursor->pVtab;
66969     u.bi.pModule = u.bi.pVtab->pModule;
66970     assert( u.bi.pModule->xRowid );
66971     rc = u.bi.pModule->xRowid(u.bi.pC->pVtabCursor, &u.bi.v);
66972     importVtabErrMsg(p, u.bi.pVtab);
66973 #endif /* SQLITE_OMIT_VIRTUALTABLE */
66974   }else{
66975     assert( u.bi.pC->pCursor!=0 );
66976     rc = sqlite3VdbeCursorMoveto(u.bi.pC);
66977     if( rc ) goto abort_due_to_error;
66978     if( u.bi.pC->rowidIsValid ){
66979       u.bi.v = u.bi.pC->lastRowid;
66980     }else{
66981       rc = sqlite3BtreeKeySize(u.bi.pC->pCursor, &u.bi.v);
66982       assert( rc==SQLITE_OK );  /* Always so because of CursorMoveto() above */
66983     }
66984   }
66985   pOut->u.i = u.bi.v;
66986   break;
66987 }
66988
66989 /* Opcode: NullRow P1 * * * *
66990 **
66991 ** Move the cursor P1 to a null row.  Any OP_Column operations
66992 ** that occur while the cursor is on the null row will always
66993 ** write a NULL.
66994 */
66995 case OP_NullRow: {
66996 #if 0  /* local variables moved into u.bj */
66997   VdbeCursor *pC;
66998 #endif /* local variables moved into u.bj */
66999
67000   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67001   u.bj.pC = p->apCsr[pOp->p1];
67002   assert( u.bj.pC!=0 );
67003   u.bj.pC->nullRow = 1;
67004   u.bj.pC->rowidIsValid = 0;
67005   if( u.bj.pC->pCursor ){
67006     sqlite3BtreeClearCursor(u.bj.pC->pCursor);
67007   }
67008   break;
67009 }
67010
67011 /* Opcode: Last P1 P2 * * *
67012 **
67013 ** The next use of the Rowid or Column or Next instruction for P1 
67014 ** will refer to the last entry in the database table or index.
67015 ** If the table or index is empty and P2>0, then jump immediately to P2.
67016 ** If P2 is 0 or if the table or index is not empty, fall through
67017 ** to the following instruction.
67018 */
67019 case OP_Last: {        /* jump */
67020 #if 0  /* local variables moved into u.bk */
67021   VdbeCursor *pC;
67022   BtCursor *pCrsr;
67023   int res;
67024 #endif /* local variables moved into u.bk */
67025
67026   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67027   u.bk.pC = p->apCsr[pOp->p1];
67028   assert( u.bk.pC!=0 );
67029   u.bk.pCrsr = u.bk.pC->pCursor;
67030   if( u.bk.pCrsr==0 ){
67031     u.bk.res = 1;
67032   }else{
67033     rc = sqlite3BtreeLast(u.bk.pCrsr, &u.bk.res);
67034   }
67035   u.bk.pC->nullRow = (u8)u.bk.res;
67036   u.bk.pC->deferredMoveto = 0;
67037   u.bk.pC->rowidIsValid = 0;
67038   u.bk.pC->cacheStatus = CACHE_STALE;
67039   if( pOp->p2>0 && u.bk.res ){
67040     pc = pOp->p2 - 1;
67041   }
67042   break;
67043 }
67044
67045
67046 /* Opcode: Sort P1 P2 * * *
67047 **
67048 ** This opcode does exactly the same thing as OP_Rewind except that
67049 ** it increments an undocumented global variable used for testing.
67050 **
67051 ** Sorting is accomplished by writing records into a sorting index,
67052 ** then rewinding that index and playing it back from beginning to
67053 ** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
67054 ** rewinding so that the global variable will be incremented and
67055 ** regression tests can determine whether or not the optimizer is
67056 ** correctly optimizing out sorts.
67057 */
67058 case OP_Sort: {        /* jump */
67059 #ifdef SQLITE_TEST
67060   sqlite3_sort_count++;
67061   sqlite3_search_count--;
67062 #endif
67063   p->aCounter[SQLITE_STMTSTATUS_SORT-1]++;
67064   /* Fall through into OP_Rewind */
67065 }
67066 /* Opcode: Rewind P1 P2 * * *
67067 **
67068 ** The next use of the Rowid or Column or Next instruction for P1 
67069 ** will refer to the first entry in the database table or index.
67070 ** If the table or index is empty and P2>0, then jump immediately to P2.
67071 ** If P2 is 0 or if the table or index is not empty, fall through
67072 ** to the following instruction.
67073 */
67074 case OP_Rewind: {        /* jump */
67075 #if 0  /* local variables moved into u.bl */
67076   VdbeCursor *pC;
67077   BtCursor *pCrsr;
67078   int res;
67079 #endif /* local variables moved into u.bl */
67080
67081   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67082   u.bl.pC = p->apCsr[pOp->p1];
67083   assert( u.bl.pC!=0 );
67084   u.bl.res = 1;
67085   if( (u.bl.pCrsr = u.bl.pC->pCursor)!=0 ){
67086     rc = sqlite3BtreeFirst(u.bl.pCrsr, &u.bl.res);
67087     u.bl.pC->atFirst = u.bl.res==0 ?1:0;
67088     u.bl.pC->deferredMoveto = 0;
67089     u.bl.pC->cacheStatus = CACHE_STALE;
67090     u.bl.pC->rowidIsValid = 0;
67091   }
67092   u.bl.pC->nullRow = (u8)u.bl.res;
67093   assert( pOp->p2>0 && pOp->p2<p->nOp );
67094   if( u.bl.res ){
67095     pc = pOp->p2 - 1;
67096   }
67097   break;
67098 }
67099
67100 /* Opcode: Next P1 P2 * * P5
67101 **
67102 ** Advance cursor P1 so that it points to the next key/data pair in its
67103 ** table or index.  If there are no more key/value pairs then fall through
67104 ** to the following instruction.  But if the cursor advance was successful,
67105 ** jump immediately to P2.
67106 **
67107 ** The P1 cursor must be for a real table, not a pseudo-table.
67108 **
67109 ** If P5 is positive and the jump is taken, then event counter
67110 ** number P5-1 in the prepared statement is incremented.
67111 **
67112 ** See also: Prev
67113 */
67114 /* Opcode: Prev P1 P2 * * P5
67115 **
67116 ** Back up cursor P1 so that it points to the previous key/data pair in its
67117 ** table or index.  If there is no previous key/value pairs then fall through
67118 ** to the following instruction.  But if the cursor backup was successful,
67119 ** jump immediately to P2.
67120 **
67121 ** The P1 cursor must be for a real table, not a pseudo-table.
67122 **
67123 ** If P5 is positive and the jump is taken, then event counter
67124 ** number P5-1 in the prepared statement is incremented.
67125 */
67126 case OP_Prev:          /* jump */
67127 case OP_Next: {        /* jump */
67128 #if 0  /* local variables moved into u.bm */
67129   VdbeCursor *pC;
67130   BtCursor *pCrsr;
67131   int res;
67132 #endif /* local variables moved into u.bm */
67133
67134   CHECK_FOR_INTERRUPT;
67135   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67136   assert( pOp->p5<=ArraySize(p->aCounter) );
67137   u.bm.pC = p->apCsr[pOp->p1];
67138   if( u.bm.pC==0 ){
67139     break;  /* See ticket #2273 */
67140   }
67141   u.bm.pCrsr = u.bm.pC->pCursor;
67142   if( u.bm.pCrsr==0 ){
67143     u.bm.pC->nullRow = 1;
67144     break;
67145   }
67146   u.bm.res = 1;
67147   assert( u.bm.pC->deferredMoveto==0 );
67148   rc = pOp->opcode==OP_Next ? sqlite3BtreeNext(u.bm.pCrsr, &u.bm.res) :
67149                               sqlite3BtreePrevious(u.bm.pCrsr, &u.bm.res);
67150   u.bm.pC->nullRow = (u8)u.bm.res;
67151   u.bm.pC->cacheStatus = CACHE_STALE;
67152   if( u.bm.res==0 ){
67153     pc = pOp->p2 - 1;
67154     if( pOp->p5 ) p->aCounter[pOp->p5-1]++;
67155 #ifdef SQLITE_TEST
67156     sqlite3_search_count++;
67157 #endif
67158   }
67159   u.bm.pC->rowidIsValid = 0;
67160   break;
67161 }
67162
67163 /* Opcode: IdxInsert P1 P2 P3 * P5
67164 **
67165 ** Register P2 holds an SQL index key made using the
67166 ** MakeRecord instructions.  This opcode writes that key
67167 ** into the index P1.  Data for the entry is nil.
67168 **
67169 ** P3 is a flag that provides a hint to the b-tree layer that this
67170 ** insert is likely to be an append.
67171 **
67172 ** This instruction only works for indices.  The equivalent instruction
67173 ** for tables is OP_Insert.
67174 */
67175 case OP_IdxInsert: {        /* in2 */
67176 #if 0  /* local variables moved into u.bn */
67177   VdbeCursor *pC;
67178   BtCursor *pCrsr;
67179   int nKey;
67180   const char *zKey;
67181 #endif /* local variables moved into u.bn */
67182
67183   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67184   u.bn.pC = p->apCsr[pOp->p1];
67185   assert( u.bn.pC!=0 );
67186   pIn2 = &aMem[pOp->p2];
67187   assert( pIn2->flags & MEM_Blob );
67188   u.bn.pCrsr = u.bn.pC->pCursor;
67189   if( ALWAYS(u.bn.pCrsr!=0) ){
67190     assert( u.bn.pC->isTable==0 );
67191     rc = ExpandBlob(pIn2);
67192     if( rc==SQLITE_OK ){
67193       u.bn.nKey = pIn2->n;
67194       u.bn.zKey = pIn2->z;
67195       rc = sqlite3BtreeInsert(u.bn.pCrsr, u.bn.zKey, u.bn.nKey, "", 0, 0, pOp->p3,
67196           ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bn.pC->seekResult : 0)
67197       );
67198       assert( u.bn.pC->deferredMoveto==0 );
67199       u.bn.pC->cacheStatus = CACHE_STALE;
67200     }
67201   }
67202   break;
67203 }
67204
67205 /* Opcode: IdxDelete P1 P2 P3 * *
67206 **
67207 ** The content of P3 registers starting at register P2 form
67208 ** an unpacked index key. This opcode removes that entry from the 
67209 ** index opened by cursor P1.
67210 */
67211 case OP_IdxDelete: {
67212 #if 0  /* local variables moved into u.bo */
67213   VdbeCursor *pC;
67214   BtCursor *pCrsr;
67215   int res;
67216   UnpackedRecord r;
67217 #endif /* local variables moved into u.bo */
67218
67219   assert( pOp->p3>0 );
67220   assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem+1 );
67221   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67222   u.bo.pC = p->apCsr[pOp->p1];
67223   assert( u.bo.pC!=0 );
67224   u.bo.pCrsr = u.bo.pC->pCursor;
67225   if( ALWAYS(u.bo.pCrsr!=0) ){
67226     u.bo.r.pKeyInfo = u.bo.pC->pKeyInfo;
67227     u.bo.r.nField = (u16)pOp->p3;
67228     u.bo.r.flags = 0;
67229     u.bo.r.aMem = &aMem[pOp->p2];
67230 #ifdef SQLITE_DEBUG
67231     { int i; for(i=0; i<u.bo.r.nField; i++) assert( memIsValid(&u.bo.r.aMem[i]) ); }
67232 #endif
67233     rc = sqlite3BtreeMovetoUnpacked(u.bo.pCrsr, &u.bo.r, 0, 0, &u.bo.res);
67234     if( rc==SQLITE_OK && u.bo.res==0 ){
67235       rc = sqlite3BtreeDelete(u.bo.pCrsr);
67236     }
67237     assert( u.bo.pC->deferredMoveto==0 );
67238     u.bo.pC->cacheStatus = CACHE_STALE;
67239   }
67240   break;
67241 }
67242
67243 /* Opcode: IdxRowid P1 P2 * * *
67244 **
67245 ** Write into register P2 an integer which is the last entry in the record at
67246 ** the end of the index key pointed to by cursor P1.  This integer should be
67247 ** the rowid of the table entry to which this index entry points.
67248 **
67249 ** See also: Rowid, MakeRecord.
67250 */
67251 case OP_IdxRowid: {              /* out2-prerelease */
67252 #if 0  /* local variables moved into u.bp */
67253   BtCursor *pCrsr;
67254   VdbeCursor *pC;
67255   i64 rowid;
67256 #endif /* local variables moved into u.bp */
67257
67258   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67259   u.bp.pC = p->apCsr[pOp->p1];
67260   assert( u.bp.pC!=0 );
67261   u.bp.pCrsr = u.bp.pC->pCursor;
67262   pOut->flags = MEM_Null;
67263   if( ALWAYS(u.bp.pCrsr!=0) ){
67264     rc = sqlite3VdbeCursorMoveto(u.bp.pC);
67265     if( NEVER(rc) ) goto abort_due_to_error;
67266     assert( u.bp.pC->deferredMoveto==0 );
67267     assert( u.bp.pC->isTable==0 );
67268     if( !u.bp.pC->nullRow ){
67269       rc = sqlite3VdbeIdxRowid(db, u.bp.pCrsr, &u.bp.rowid);
67270       if( rc!=SQLITE_OK ){
67271         goto abort_due_to_error;
67272       }
67273       pOut->u.i = u.bp.rowid;
67274       pOut->flags = MEM_Int;
67275     }
67276   }
67277   break;
67278 }
67279
67280 /* Opcode: IdxGE P1 P2 P3 P4 P5
67281 **
67282 ** The P4 register values beginning with P3 form an unpacked index 
67283 ** key that omits the ROWID.  Compare this key value against the index 
67284 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
67285 **
67286 ** If the P1 index entry is greater than or equal to the key value
67287 ** then jump to P2.  Otherwise fall through to the next instruction.
67288 **
67289 ** If P5 is non-zero then the key value is increased by an epsilon 
67290 ** prior to the comparison.  This make the opcode work like IdxGT except
67291 ** that if the key from register P3 is a prefix of the key in the cursor,
67292 ** the result is false whereas it would be true with IdxGT.
67293 */
67294 /* Opcode: IdxLT P1 P2 P3 P4 P5
67295 **
67296 ** The P4 register values beginning with P3 form an unpacked index 
67297 ** key that omits the ROWID.  Compare this key value against the index 
67298 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
67299 **
67300 ** If the P1 index entry is less than the key value then jump to P2.
67301 ** Otherwise fall through to the next instruction.
67302 **
67303 ** If P5 is non-zero then the key value is increased by an epsilon prior 
67304 ** to the comparison.  This makes the opcode work like IdxLE.
67305 */
67306 case OP_IdxLT:          /* jump */
67307 case OP_IdxGE: {        /* jump */
67308 #if 0  /* local variables moved into u.bq */
67309   VdbeCursor *pC;
67310   int res;
67311   UnpackedRecord r;
67312 #endif /* local variables moved into u.bq */
67313
67314   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67315   u.bq.pC = p->apCsr[pOp->p1];
67316   assert( u.bq.pC!=0 );
67317   assert( u.bq.pC->isOrdered );
67318   if( ALWAYS(u.bq.pC->pCursor!=0) ){
67319     assert( u.bq.pC->deferredMoveto==0 );
67320     assert( pOp->p5==0 || pOp->p5==1 );
67321     assert( pOp->p4type==P4_INT32 );
67322     u.bq.r.pKeyInfo = u.bq.pC->pKeyInfo;
67323     u.bq.r.nField = (u16)pOp->p4.i;
67324     if( pOp->p5 ){
67325       u.bq.r.flags = UNPACKED_INCRKEY | UNPACKED_IGNORE_ROWID;
67326     }else{
67327       u.bq.r.flags = UNPACKED_IGNORE_ROWID;
67328     }
67329     u.bq.r.aMem = &aMem[pOp->p3];
67330 #ifdef SQLITE_DEBUG
67331     { int i; for(i=0; i<u.bq.r.nField; i++) assert( memIsValid(&u.bq.r.aMem[i]) ); }
67332 #endif
67333     rc = sqlite3VdbeIdxKeyCompare(u.bq.pC, &u.bq.r, &u.bq.res);
67334     if( pOp->opcode==OP_IdxLT ){
67335       u.bq.res = -u.bq.res;
67336     }else{
67337       assert( pOp->opcode==OP_IdxGE );
67338       u.bq.res++;
67339     }
67340     if( u.bq.res>0 ){
67341       pc = pOp->p2 - 1 ;
67342     }
67343   }
67344   break;
67345 }
67346
67347 /* Opcode: Destroy P1 P2 P3 * *
67348 **
67349 ** Delete an entire database table or index whose root page in the database
67350 ** file is given by P1.
67351 **
67352 ** The table being destroyed is in the main database file if P3==0.  If
67353 ** P3==1 then the table to be clear is in the auxiliary database file
67354 ** that is used to store tables create using CREATE TEMPORARY TABLE.
67355 **
67356 ** If AUTOVACUUM is enabled then it is possible that another root page
67357 ** might be moved into the newly deleted root page in order to keep all
67358 ** root pages contiguous at the beginning of the database.  The former
67359 ** value of the root page that moved - its value before the move occurred -
67360 ** is stored in register P2.  If no page 
67361 ** movement was required (because the table being dropped was already 
67362 ** the last one in the database) then a zero is stored in register P2.
67363 ** If AUTOVACUUM is disabled then a zero is stored in register P2.
67364 **
67365 ** See also: Clear
67366 */
67367 case OP_Destroy: {     /* out2-prerelease */
67368 #if 0  /* local variables moved into u.br */
67369   int iMoved;
67370   int iCnt;
67371   Vdbe *pVdbe;
67372   int iDb;
67373 #endif /* local variables moved into u.br */
67374 #ifndef SQLITE_OMIT_VIRTUALTABLE
67375   u.br.iCnt = 0;
67376   for(u.br.pVdbe=db->pVdbe; u.br.pVdbe; u.br.pVdbe = u.br.pVdbe->pNext){
67377     if( u.br.pVdbe->magic==VDBE_MAGIC_RUN && u.br.pVdbe->inVtabMethod<2 && u.br.pVdbe->pc>=0 ){
67378       u.br.iCnt++;
67379     }
67380   }
67381 #else
67382   u.br.iCnt = db->activeVdbeCnt;
67383 #endif
67384   pOut->flags = MEM_Null;
67385   if( u.br.iCnt>1 ){
67386     rc = SQLITE_LOCKED;
67387     p->errorAction = OE_Abort;
67388   }else{
67389     u.br.iDb = pOp->p3;
67390     assert( u.br.iCnt==1 );
67391     assert( (p->btreeMask & (((yDbMask)1)<<u.br.iDb))!=0 );
67392     rc = sqlite3BtreeDropTable(db->aDb[u.br.iDb].pBt, pOp->p1, &u.br.iMoved);
67393     pOut->flags = MEM_Int;
67394     pOut->u.i = u.br.iMoved;
67395 #ifndef SQLITE_OMIT_AUTOVACUUM
67396     if( rc==SQLITE_OK && u.br.iMoved!=0 ){
67397       sqlite3RootPageMoved(db, u.br.iDb, u.br.iMoved, pOp->p1);
67398       /* All OP_Destroy operations occur on the same btree */
67399       assert( resetSchemaOnFault==0 || resetSchemaOnFault==u.br.iDb+1 );
67400       resetSchemaOnFault = u.br.iDb+1;
67401     }
67402 #endif
67403   }
67404   break;
67405 }
67406
67407 /* Opcode: Clear P1 P2 P3
67408 **
67409 ** Delete all contents of the database table or index whose root page
67410 ** in the database file is given by P1.  But, unlike Destroy, do not
67411 ** remove the table or index from the database file.
67412 **
67413 ** The table being clear is in the main database file if P2==0.  If
67414 ** P2==1 then the table to be clear is in the auxiliary database file
67415 ** that is used to store tables create using CREATE TEMPORARY TABLE.
67416 **
67417 ** If the P3 value is non-zero, then the table referred to must be an
67418 ** intkey table (an SQL table, not an index). In this case the row change 
67419 ** count is incremented by the number of rows in the table being cleared. 
67420 ** If P3 is greater than zero, then the value stored in register P3 is
67421 ** also incremented by the number of rows in the table being cleared.
67422 **
67423 ** See also: Destroy
67424 */
67425 case OP_Clear: {
67426 #if 0  /* local variables moved into u.bs */
67427   int nChange;
67428 #endif /* local variables moved into u.bs */
67429
67430   u.bs.nChange = 0;
67431   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p2))!=0 );
67432   rc = sqlite3BtreeClearTable(
67433       db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bs.nChange : 0)
67434   );
67435   if( pOp->p3 ){
67436     p->nChange += u.bs.nChange;
67437     if( pOp->p3>0 ){
67438       assert( memIsValid(&aMem[pOp->p3]) );
67439       memAboutToChange(p, &aMem[pOp->p3]);
67440       aMem[pOp->p3].u.i += u.bs.nChange;
67441     }
67442   }
67443   break;
67444 }
67445
67446 /* Opcode: CreateTable P1 P2 * * *
67447 **
67448 ** Allocate a new table in the main database file if P1==0 or in the
67449 ** auxiliary database file if P1==1 or in an attached database if
67450 ** P1>1.  Write the root page number of the new table into
67451 ** register P2
67452 **
67453 ** The difference between a table and an index is this:  A table must
67454 ** have a 4-byte integer key and can have arbitrary data.  An index
67455 ** has an arbitrary key but no data.
67456 **
67457 ** See also: CreateIndex
67458 */
67459 /* Opcode: CreateIndex P1 P2 * * *
67460 **
67461 ** Allocate a new index in the main database file if P1==0 or in the
67462 ** auxiliary database file if P1==1 or in an attached database if
67463 ** P1>1.  Write the root page number of the new table into
67464 ** register P2.
67465 **
67466 ** See documentation on OP_CreateTable for additional information.
67467 */
67468 case OP_CreateIndex:            /* out2-prerelease */
67469 case OP_CreateTable: {          /* out2-prerelease */
67470 #if 0  /* local variables moved into u.bt */
67471   int pgno;
67472   int flags;
67473   Db *pDb;
67474 #endif /* local variables moved into u.bt */
67475
67476   u.bt.pgno = 0;
67477   assert( pOp->p1>=0 && pOp->p1<db->nDb );
67478   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
67479   u.bt.pDb = &db->aDb[pOp->p1];
67480   assert( u.bt.pDb->pBt!=0 );
67481   if( pOp->opcode==OP_CreateTable ){
67482     /* u.bt.flags = BTREE_INTKEY; */
67483     u.bt.flags = BTREE_INTKEY;
67484   }else{
67485     u.bt.flags = BTREE_BLOBKEY;
67486   }
67487   rc = sqlite3BtreeCreateTable(u.bt.pDb->pBt, &u.bt.pgno, u.bt.flags);
67488   pOut->u.i = u.bt.pgno;
67489   break;
67490 }
67491
67492 /* Opcode: ParseSchema P1 * * P4 *
67493 **
67494 ** Read and parse all entries from the SQLITE_MASTER table of database P1
67495 ** that match the WHERE clause P4. 
67496 **
67497 ** This opcode invokes the parser to create a new virtual machine,
67498 ** then runs the new virtual machine.  It is thus a re-entrant opcode.
67499 */
67500 case OP_ParseSchema: {
67501 #if 0  /* local variables moved into u.bu */
67502   int iDb;
67503   const char *zMaster;
67504   char *zSql;
67505   InitData initData;
67506 #endif /* local variables moved into u.bu */
67507
67508   /* Any prepared statement that invokes this opcode will hold mutexes
67509   ** on every btree.  This is a prerequisite for invoking
67510   ** sqlite3InitCallback().
67511   */
67512 #ifdef SQLITE_DEBUG
67513   for(u.bu.iDb=0; u.bu.iDb<db->nDb; u.bu.iDb++){
67514     assert( u.bu.iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[u.bu.iDb].pBt) );
67515   }
67516 #endif
67517
67518   u.bu.iDb = pOp->p1;
67519   assert( u.bu.iDb>=0 && u.bu.iDb<db->nDb );
67520   assert( DbHasProperty(db, u.bu.iDb, DB_SchemaLoaded) );
67521   /* Used to be a conditional */ {
67522     u.bu.zMaster = SCHEMA_TABLE(u.bu.iDb);
67523     u.bu.initData.db = db;
67524     u.bu.initData.iDb = pOp->p1;
67525     u.bu.initData.pzErrMsg = &p->zErrMsg;
67526     u.bu.zSql = sqlite3MPrintf(db,
67527        "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
67528        db->aDb[u.bu.iDb].zName, u.bu.zMaster, pOp->p4.z);
67529     if( u.bu.zSql==0 ){
67530       rc = SQLITE_NOMEM;
67531     }else{
67532       assert( db->init.busy==0 );
67533       db->init.busy = 1;
67534       u.bu.initData.rc = SQLITE_OK;
67535       assert( !db->mallocFailed );
67536       rc = sqlite3_exec(db, u.bu.zSql, sqlite3InitCallback, &u.bu.initData, 0);
67537       if( rc==SQLITE_OK ) rc = u.bu.initData.rc;
67538       sqlite3DbFree(db, u.bu.zSql);
67539       db->init.busy = 0;
67540     }
67541   }
67542   if( rc==SQLITE_NOMEM ){
67543     goto no_mem;
67544   }
67545   break;
67546 }
67547
67548 #if !defined(SQLITE_OMIT_ANALYZE)
67549 /* Opcode: LoadAnalysis P1 * * * *
67550 **
67551 ** Read the sqlite_stat1 table for database P1 and load the content
67552 ** of that table into the internal index hash table.  This will cause
67553 ** the analysis to be used when preparing all subsequent queries.
67554 */
67555 case OP_LoadAnalysis: {
67556   assert( pOp->p1>=0 && pOp->p1<db->nDb );
67557   rc = sqlite3AnalysisLoad(db, pOp->p1);
67558   break;  
67559 }
67560 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
67561
67562 /* Opcode: DropTable P1 * * P4 *
67563 **
67564 ** Remove the internal (in-memory) data structures that describe
67565 ** the table named P4 in database P1.  This is called after a table
67566 ** is dropped in order to keep the internal representation of the
67567 ** schema consistent with what is on disk.
67568 */
67569 case OP_DropTable: {
67570   sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
67571   break;
67572 }
67573
67574 /* Opcode: DropIndex P1 * * P4 *
67575 **
67576 ** Remove the internal (in-memory) data structures that describe
67577 ** the index named P4 in database P1.  This is called after an index
67578 ** is dropped in order to keep the internal representation of the
67579 ** schema consistent with what is on disk.
67580 */
67581 case OP_DropIndex: {
67582   sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
67583   break;
67584 }
67585
67586 /* Opcode: DropTrigger P1 * * P4 *
67587 **
67588 ** Remove the internal (in-memory) data structures that describe
67589 ** the trigger named P4 in database P1.  This is called after a trigger
67590 ** is dropped in order to keep the internal representation of the
67591 ** schema consistent with what is on disk.
67592 */
67593 case OP_DropTrigger: {
67594   sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
67595   break;
67596 }
67597
67598
67599 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
67600 /* Opcode: IntegrityCk P1 P2 P3 * P5
67601 **
67602 ** Do an analysis of the currently open database.  Store in
67603 ** register P1 the text of an error message describing any problems.
67604 ** If no problems are found, store a NULL in register P1.
67605 **
67606 ** The register P3 contains the maximum number of allowed errors.
67607 ** At most reg(P3) errors will be reported.
67608 ** In other words, the analysis stops as soon as reg(P1) errors are 
67609 ** seen.  Reg(P1) is updated with the number of errors remaining.
67610 **
67611 ** The root page numbers of all tables in the database are integer
67612 ** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
67613 ** total.
67614 **
67615 ** If P5 is not zero, the check is done on the auxiliary database
67616 ** file, not the main database file.
67617 **
67618 ** This opcode is used to implement the integrity_check pragma.
67619 */
67620 case OP_IntegrityCk: {
67621 #if 0  /* local variables moved into u.bv */
67622   int nRoot;      /* Number of tables to check.  (Number of root pages.) */
67623   int *aRoot;     /* Array of rootpage numbers for tables to be checked */
67624   int j;          /* Loop counter */
67625   int nErr;       /* Number of errors reported */
67626   char *z;        /* Text of the error report */
67627   Mem *pnErr;     /* Register keeping track of errors remaining */
67628 #endif /* local variables moved into u.bv */
67629
67630   u.bv.nRoot = pOp->p2;
67631   assert( u.bv.nRoot>0 );
67632   u.bv.aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(u.bv.nRoot+1) );
67633   if( u.bv.aRoot==0 ) goto no_mem;
67634   assert( pOp->p3>0 && pOp->p3<=p->nMem );
67635   u.bv.pnErr = &aMem[pOp->p3];
67636   assert( (u.bv.pnErr->flags & MEM_Int)!=0 );
67637   assert( (u.bv.pnErr->flags & (MEM_Str|MEM_Blob))==0 );
67638   pIn1 = &aMem[pOp->p1];
67639   for(u.bv.j=0; u.bv.j<u.bv.nRoot; u.bv.j++){
67640     u.bv.aRoot[u.bv.j] = (int)sqlite3VdbeIntValue(&pIn1[u.bv.j]);
67641   }
67642   u.bv.aRoot[u.bv.j] = 0;
67643   assert( pOp->p5<db->nDb );
67644   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p5))!=0 );
67645   u.bv.z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, u.bv.aRoot, u.bv.nRoot,
67646                                  (int)u.bv.pnErr->u.i, &u.bv.nErr);
67647   sqlite3DbFree(db, u.bv.aRoot);
67648   u.bv.pnErr->u.i -= u.bv.nErr;
67649   sqlite3VdbeMemSetNull(pIn1);
67650   if( u.bv.nErr==0 ){
67651     assert( u.bv.z==0 );
67652   }else if( u.bv.z==0 ){
67653     goto no_mem;
67654   }else{
67655     sqlite3VdbeMemSetStr(pIn1, u.bv.z, -1, SQLITE_UTF8, sqlite3_free);
67656   }
67657   UPDATE_MAX_BLOBSIZE(pIn1);
67658   sqlite3VdbeChangeEncoding(pIn1, encoding);
67659   break;
67660 }
67661 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
67662
67663 /* Opcode: RowSetAdd P1 P2 * * *
67664 **
67665 ** Insert the integer value held by register P2 into a boolean index
67666 ** held in register P1.
67667 **
67668 ** An assertion fails if P2 is not an integer.
67669 */
67670 case OP_RowSetAdd: {       /* in1, in2 */
67671   pIn1 = &aMem[pOp->p1];
67672   pIn2 = &aMem[pOp->p2];
67673   assert( (pIn2->flags & MEM_Int)!=0 );
67674   if( (pIn1->flags & MEM_RowSet)==0 ){
67675     sqlite3VdbeMemSetRowSet(pIn1);
67676     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
67677   }
67678   sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
67679   break;
67680 }
67681
67682 /* Opcode: RowSetRead P1 P2 P3 * *
67683 **
67684 ** Extract the smallest value from boolean index P1 and put that value into
67685 ** register P3.  Or, if boolean index P1 is initially empty, leave P3
67686 ** unchanged and jump to instruction P2.
67687 */
67688 case OP_RowSetRead: {       /* jump, in1, out3 */
67689 #if 0  /* local variables moved into u.bw */
67690   i64 val;
67691 #endif /* local variables moved into u.bw */
67692   CHECK_FOR_INTERRUPT;
67693   pIn1 = &aMem[pOp->p1];
67694   if( (pIn1->flags & MEM_RowSet)==0
67695    || sqlite3RowSetNext(pIn1->u.pRowSet, &u.bw.val)==0
67696   ){
67697     /* The boolean index is empty */
67698     sqlite3VdbeMemSetNull(pIn1);
67699     pc = pOp->p2 - 1;
67700   }else{
67701     /* A value was pulled from the index */
67702     sqlite3VdbeMemSetInt64(&aMem[pOp->p3], u.bw.val);
67703   }
67704   break;
67705 }
67706
67707 /* Opcode: RowSetTest P1 P2 P3 P4
67708 **
67709 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
67710 ** contains a RowSet object and that RowSet object contains
67711 ** the value held in P3, jump to register P2. Otherwise, insert the
67712 ** integer in P3 into the RowSet and continue on to the
67713 ** next opcode.
67714 **
67715 ** The RowSet object is optimized for the case where successive sets
67716 ** of integers, where each set contains no duplicates. Each set
67717 ** of values is identified by a unique P4 value. The first set
67718 ** must have P4==0, the final set P4=-1.  P4 must be either -1 or
67719 ** non-negative.  For non-negative values of P4 only the lower 4
67720 ** bits are significant.
67721 **
67722 ** This allows optimizations: (a) when P4==0 there is no need to test
67723 ** the rowset object for P3, as it is guaranteed not to contain it,
67724 ** (b) when P4==-1 there is no need to insert the value, as it will
67725 ** never be tested for, and (c) when a value that is part of set X is
67726 ** inserted, there is no need to search to see if the same value was
67727 ** previously inserted as part of set X (only if it was previously
67728 ** inserted as part of some other set).
67729 */
67730 case OP_RowSetTest: {                     /* jump, in1, in3 */
67731 #if 0  /* local variables moved into u.bx */
67732   int iSet;
67733   int exists;
67734 #endif /* local variables moved into u.bx */
67735
67736   pIn1 = &aMem[pOp->p1];
67737   pIn3 = &aMem[pOp->p3];
67738   u.bx.iSet = pOp->p4.i;
67739   assert( pIn3->flags&MEM_Int );
67740
67741   /* If there is anything other than a rowset object in memory cell P1,
67742   ** delete it now and initialize P1 with an empty rowset
67743   */
67744   if( (pIn1->flags & MEM_RowSet)==0 ){
67745     sqlite3VdbeMemSetRowSet(pIn1);
67746     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
67747   }
67748
67749   assert( pOp->p4type==P4_INT32 );
67750   assert( u.bx.iSet==-1 || u.bx.iSet>=0 );
67751   if( u.bx.iSet ){
67752     u.bx.exists = sqlite3RowSetTest(pIn1->u.pRowSet,
67753                                (u8)(u.bx.iSet>=0 ? u.bx.iSet & 0xf : 0xff),
67754                                pIn3->u.i);
67755     if( u.bx.exists ){
67756       pc = pOp->p2 - 1;
67757       break;
67758     }
67759   }
67760   if( u.bx.iSet>=0 ){
67761     sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
67762   }
67763   break;
67764 }
67765
67766
67767 #ifndef SQLITE_OMIT_TRIGGER
67768
67769 /* Opcode: Program P1 P2 P3 P4 *
67770 **
67771 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM). 
67772 **
67773 ** P1 contains the address of the memory cell that contains the first memory 
67774 ** cell in an array of values used as arguments to the sub-program. P2 
67775 ** contains the address to jump to if the sub-program throws an IGNORE 
67776 ** exception using the RAISE() function. Register P3 contains the address 
67777 ** of a memory cell in this (the parent) VM that is used to allocate the 
67778 ** memory required by the sub-vdbe at runtime.
67779 **
67780 ** P4 is a pointer to the VM containing the trigger program.
67781 */
67782 case OP_Program: {        /* jump */
67783 #if 0  /* local variables moved into u.by */
67784   int nMem;               /* Number of memory registers for sub-program */
67785   int nByte;              /* Bytes of runtime space required for sub-program */
67786   Mem *pRt;               /* Register to allocate runtime space */
67787   Mem *pMem;              /* Used to iterate through memory cells */
67788   Mem *pEnd;              /* Last memory cell in new array */
67789   VdbeFrame *pFrame;      /* New vdbe frame to execute in */
67790   SubProgram *pProgram;   /* Sub-program to execute */
67791   void *t;                /* Token identifying trigger */
67792 #endif /* local variables moved into u.by */
67793
67794   u.by.pProgram = pOp->p4.pProgram;
67795   u.by.pRt = &aMem[pOp->p3];
67796   assert( memIsValid(u.by.pRt) );
67797   assert( u.by.pProgram->nOp>0 );
67798
67799   /* If the p5 flag is clear, then recursive invocation of triggers is
67800   ** disabled for backwards compatibility (p5 is set if this sub-program
67801   ** is really a trigger, not a foreign key action, and the flag set
67802   ** and cleared by the "PRAGMA recursive_triggers" command is clear).
67803   **
67804   ** It is recursive invocation of triggers, at the SQL level, that is
67805   ** disabled. In some cases a single trigger may generate more than one
67806   ** SubProgram (if the trigger may be executed with more than one different
67807   ** ON CONFLICT algorithm). SubProgram structures associated with a
67808   ** single trigger all have the same value for the SubProgram.token
67809   ** variable.  */
67810   if( pOp->p5 ){
67811     u.by.t = u.by.pProgram->token;
67812     for(u.by.pFrame=p->pFrame; u.by.pFrame && u.by.pFrame->token!=u.by.t; u.by.pFrame=u.by.pFrame->pParent);
67813     if( u.by.pFrame ) break;
67814   }
67815
67816   if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
67817     rc = SQLITE_ERROR;
67818     sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
67819     break;
67820   }
67821
67822   /* Register u.by.pRt is used to store the memory required to save the state
67823   ** of the current program, and the memory required at runtime to execute
67824   ** the trigger program. If this trigger has been fired before, then u.by.pRt
67825   ** is already allocated. Otherwise, it must be initialized.  */
67826   if( (u.by.pRt->flags&MEM_Frame)==0 ){
67827     /* SubProgram.nMem is set to the number of memory cells used by the
67828     ** program stored in SubProgram.aOp. As well as these, one memory
67829     ** cell is required for each cursor used by the program. Set local
67830     ** variable u.by.nMem (and later, VdbeFrame.nChildMem) to this value.
67831     */
67832     u.by.nMem = u.by.pProgram->nMem + u.by.pProgram->nCsr;
67833     u.by.nByte = ROUND8(sizeof(VdbeFrame))
67834               + u.by.nMem * sizeof(Mem)
67835               + u.by.pProgram->nCsr * sizeof(VdbeCursor *);
67836     u.by.pFrame = sqlite3DbMallocZero(db, u.by.nByte);
67837     if( !u.by.pFrame ){
67838       goto no_mem;
67839     }
67840     sqlite3VdbeMemRelease(u.by.pRt);
67841     u.by.pRt->flags = MEM_Frame;
67842     u.by.pRt->u.pFrame = u.by.pFrame;
67843
67844     u.by.pFrame->v = p;
67845     u.by.pFrame->nChildMem = u.by.nMem;
67846     u.by.pFrame->nChildCsr = u.by.pProgram->nCsr;
67847     u.by.pFrame->pc = pc;
67848     u.by.pFrame->aMem = p->aMem;
67849     u.by.pFrame->nMem = p->nMem;
67850     u.by.pFrame->apCsr = p->apCsr;
67851     u.by.pFrame->nCursor = p->nCursor;
67852     u.by.pFrame->aOp = p->aOp;
67853     u.by.pFrame->nOp = p->nOp;
67854     u.by.pFrame->token = u.by.pProgram->token;
67855
67856     u.by.pEnd = &VdbeFrameMem(u.by.pFrame)[u.by.pFrame->nChildMem];
67857     for(u.by.pMem=VdbeFrameMem(u.by.pFrame); u.by.pMem!=u.by.pEnd; u.by.pMem++){
67858       u.by.pMem->flags = MEM_Null;
67859       u.by.pMem->db = db;
67860     }
67861   }else{
67862     u.by.pFrame = u.by.pRt->u.pFrame;
67863     assert( u.by.pProgram->nMem+u.by.pProgram->nCsr==u.by.pFrame->nChildMem );
67864     assert( u.by.pProgram->nCsr==u.by.pFrame->nChildCsr );
67865     assert( pc==u.by.pFrame->pc );
67866   }
67867
67868   p->nFrame++;
67869   u.by.pFrame->pParent = p->pFrame;
67870   u.by.pFrame->lastRowid = lastRowid;
67871   u.by.pFrame->nChange = p->nChange;
67872   p->nChange = 0;
67873   p->pFrame = u.by.pFrame;
67874   p->aMem = aMem = &VdbeFrameMem(u.by.pFrame)[-1];
67875   p->nMem = u.by.pFrame->nChildMem;
67876   p->nCursor = (u16)u.by.pFrame->nChildCsr;
67877   p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
67878   p->aOp = aOp = u.by.pProgram->aOp;
67879   p->nOp = u.by.pProgram->nOp;
67880   pc = -1;
67881
67882   break;
67883 }
67884
67885 /* Opcode: Param P1 P2 * * *
67886 **
67887 ** This opcode is only ever present in sub-programs called via the 
67888 ** OP_Program instruction. Copy a value currently stored in a memory 
67889 ** cell of the calling (parent) frame to cell P2 in the current frames 
67890 ** address space. This is used by trigger programs to access the new.* 
67891 ** and old.* values.
67892 **
67893 ** The address of the cell in the parent frame is determined by adding
67894 ** the value of the P1 argument to the value of the P1 argument to the
67895 ** calling OP_Program instruction.
67896 */
67897 case OP_Param: {           /* out2-prerelease */
67898 #if 0  /* local variables moved into u.bz */
67899   VdbeFrame *pFrame;
67900   Mem *pIn;
67901 #endif /* local variables moved into u.bz */
67902   u.bz.pFrame = p->pFrame;
67903   u.bz.pIn = &u.bz.pFrame->aMem[pOp->p1 + u.bz.pFrame->aOp[u.bz.pFrame->pc].p1];
67904   sqlite3VdbeMemShallowCopy(pOut, u.bz.pIn, MEM_Ephem);
67905   break;
67906 }
67907
67908 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
67909
67910 #ifndef SQLITE_OMIT_FOREIGN_KEY
67911 /* Opcode: FkCounter P1 P2 * * *
67912 **
67913 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
67914 ** If P1 is non-zero, the database constraint counter is incremented 
67915 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the 
67916 ** statement counter is incremented (immediate foreign key constraints).
67917 */
67918 case OP_FkCounter: {
67919   if( pOp->p1 ){
67920     db->nDeferredCons += pOp->p2;
67921   }else{
67922     p->nFkConstraint += pOp->p2;
67923   }
67924   break;
67925 }
67926
67927 /* Opcode: FkIfZero P1 P2 * * *
67928 **
67929 ** This opcode tests if a foreign key constraint-counter is currently zero.
67930 ** If so, jump to instruction P2. Otherwise, fall through to the next 
67931 ** instruction.
67932 **
67933 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
67934 ** is zero (the one that counts deferred constraint violations). If P1 is
67935 ** zero, the jump is taken if the statement constraint-counter is zero
67936 ** (immediate foreign key constraint violations).
67937 */
67938 case OP_FkIfZero: {         /* jump */
67939   if( pOp->p1 ){
67940     if( db->nDeferredCons==0 ) pc = pOp->p2-1;
67941   }else{
67942     if( p->nFkConstraint==0 ) pc = pOp->p2-1;
67943   }
67944   break;
67945 }
67946 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
67947
67948 #ifndef SQLITE_OMIT_AUTOINCREMENT
67949 /* Opcode: MemMax P1 P2 * * *
67950 **
67951 ** P1 is a register in the root frame of this VM (the root frame is
67952 ** different from the current frame if this instruction is being executed
67953 ** within a sub-program). Set the value of register P1 to the maximum of 
67954 ** its current value and the value in register P2.
67955 **
67956 ** This instruction throws an error if the memory cell is not initially
67957 ** an integer.
67958 */
67959 case OP_MemMax: {        /* in2 */
67960 #if 0  /* local variables moved into u.ca */
67961   Mem *pIn1;
67962   VdbeFrame *pFrame;
67963 #endif /* local variables moved into u.ca */
67964   if( p->pFrame ){
67965     for(u.ca.pFrame=p->pFrame; u.ca.pFrame->pParent; u.ca.pFrame=u.ca.pFrame->pParent);
67966     u.ca.pIn1 = &u.ca.pFrame->aMem[pOp->p1];
67967   }else{
67968     u.ca.pIn1 = &aMem[pOp->p1];
67969   }
67970   assert( memIsValid(u.ca.pIn1) );
67971   sqlite3VdbeMemIntegerify(u.ca.pIn1);
67972   pIn2 = &aMem[pOp->p2];
67973   sqlite3VdbeMemIntegerify(pIn2);
67974   if( u.ca.pIn1->u.i<pIn2->u.i){
67975     u.ca.pIn1->u.i = pIn2->u.i;
67976   }
67977   break;
67978 }
67979 #endif /* SQLITE_OMIT_AUTOINCREMENT */
67980
67981 /* Opcode: IfPos P1 P2 * * *
67982 **
67983 ** If the value of register P1 is 1 or greater, jump to P2.
67984 **
67985 ** It is illegal to use this instruction on a register that does
67986 ** not contain an integer.  An assertion fault will result if you try.
67987 */
67988 case OP_IfPos: {        /* jump, in1 */
67989   pIn1 = &aMem[pOp->p1];
67990   assert( pIn1->flags&MEM_Int );
67991   if( pIn1->u.i>0 ){
67992      pc = pOp->p2 - 1;
67993   }
67994   break;
67995 }
67996
67997 /* Opcode: IfNeg P1 P2 * * *
67998 **
67999 ** If the value of register P1 is less than zero, jump to P2. 
68000 **
68001 ** It is illegal to use this instruction on a register that does
68002 ** not contain an integer.  An assertion fault will result if you try.
68003 */
68004 case OP_IfNeg: {        /* jump, in1 */
68005   pIn1 = &aMem[pOp->p1];
68006   assert( pIn1->flags&MEM_Int );
68007   if( pIn1->u.i<0 ){
68008      pc = pOp->p2 - 1;
68009   }
68010   break;
68011 }
68012
68013 /* Opcode: IfZero P1 P2 P3 * *
68014 **
68015 ** The register P1 must contain an integer.  Add literal P3 to the
68016 ** value in register P1.  If the result is exactly 0, jump to P2. 
68017 **
68018 ** It is illegal to use this instruction on a register that does
68019 ** not contain an integer.  An assertion fault will result if you try.
68020 */
68021 case OP_IfZero: {        /* jump, in1 */
68022   pIn1 = &aMem[pOp->p1];
68023   assert( pIn1->flags&MEM_Int );
68024   pIn1->u.i += pOp->p3;
68025   if( pIn1->u.i==0 ){
68026      pc = pOp->p2 - 1;
68027   }
68028   break;
68029 }
68030
68031 /* Opcode: AggStep * P2 P3 P4 P5
68032 **
68033 ** Execute the step function for an aggregate.  The
68034 ** function has P5 arguments.   P4 is a pointer to the FuncDef
68035 ** structure that specifies the function.  Use register
68036 ** P3 as the accumulator.
68037 **
68038 ** The P5 arguments are taken from register P2 and its
68039 ** successors.
68040 */
68041 case OP_AggStep: {
68042 #if 0  /* local variables moved into u.cb */
68043   int n;
68044   int i;
68045   Mem *pMem;
68046   Mem *pRec;
68047   sqlite3_context ctx;
68048   sqlite3_value **apVal;
68049 #endif /* local variables moved into u.cb */
68050
68051   u.cb.n = pOp->p5;
68052   assert( u.cb.n>=0 );
68053   u.cb.pRec = &aMem[pOp->p2];
68054   u.cb.apVal = p->apArg;
68055   assert( u.cb.apVal || u.cb.n==0 );
68056   for(u.cb.i=0; u.cb.i<u.cb.n; u.cb.i++, u.cb.pRec++){
68057     assert( memIsValid(u.cb.pRec) );
68058     u.cb.apVal[u.cb.i] = u.cb.pRec;
68059     memAboutToChange(p, u.cb.pRec);
68060     sqlite3VdbeMemStoreType(u.cb.pRec);
68061   }
68062   u.cb.ctx.pFunc = pOp->p4.pFunc;
68063   assert( pOp->p3>0 && pOp->p3<=p->nMem );
68064   u.cb.ctx.pMem = u.cb.pMem = &aMem[pOp->p3];
68065   u.cb.pMem->n++;
68066   u.cb.ctx.s.flags = MEM_Null;
68067   u.cb.ctx.s.z = 0;
68068   u.cb.ctx.s.zMalloc = 0;
68069   u.cb.ctx.s.xDel = 0;
68070   u.cb.ctx.s.db = db;
68071   u.cb.ctx.isError = 0;
68072   u.cb.ctx.pColl = 0;
68073   if( u.cb.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
68074     assert( pOp>p->aOp );
68075     assert( pOp[-1].p4type==P4_COLLSEQ );
68076     assert( pOp[-1].opcode==OP_CollSeq );
68077     u.cb.ctx.pColl = pOp[-1].p4.pColl;
68078   }
68079   (u.cb.ctx.pFunc->xStep)(&u.cb.ctx, u.cb.n, u.cb.apVal); /* IMP: R-24505-23230 */
68080   if( u.cb.ctx.isError ){
68081     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.cb.ctx.s));
68082     rc = u.cb.ctx.isError;
68083   }
68084
68085   sqlite3VdbeMemRelease(&u.cb.ctx.s);
68086
68087   break;
68088 }
68089
68090 /* Opcode: AggFinal P1 P2 * P4 *
68091 **
68092 ** Execute the finalizer function for an aggregate.  P1 is
68093 ** the memory location that is the accumulator for the aggregate.
68094 **
68095 ** P2 is the number of arguments that the step function takes and
68096 ** P4 is a pointer to the FuncDef for this function.  The P2
68097 ** argument is not used by this opcode.  It is only there to disambiguate
68098 ** functions that can take varying numbers of arguments.  The
68099 ** P4 argument is only needed for the degenerate case where
68100 ** the step function was not previously called.
68101 */
68102 case OP_AggFinal: {
68103 #if 0  /* local variables moved into u.cc */
68104   Mem *pMem;
68105 #endif /* local variables moved into u.cc */
68106   assert( pOp->p1>0 && pOp->p1<=p->nMem );
68107   u.cc.pMem = &aMem[pOp->p1];
68108   assert( (u.cc.pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
68109   rc = sqlite3VdbeMemFinalize(u.cc.pMem, pOp->p4.pFunc);
68110   if( rc ){
68111     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(u.cc.pMem));
68112   }
68113   sqlite3VdbeChangeEncoding(u.cc.pMem, encoding);
68114   UPDATE_MAX_BLOBSIZE(u.cc.pMem);
68115   if( sqlite3VdbeMemTooBig(u.cc.pMem) ){
68116     goto too_big;
68117   }
68118   break;
68119 }
68120
68121 #ifndef SQLITE_OMIT_WAL
68122 /* Opcode: Checkpoint P1 P2 P3 * *
68123 **
68124 ** Checkpoint database P1. This is a no-op if P1 is not currently in
68125 ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL
68126 ** or RESTART.  Write 1 or 0 into mem[P3] if the checkpoint returns
68127 ** SQLITE_BUSY or not, respectively.  Write the number of pages in the
68128 ** WAL after the checkpoint into mem[P3+1] and the number of pages
68129 ** in the WAL that have been checkpointed after the checkpoint
68130 ** completes into mem[P3+2].  However on an error, mem[P3+1] and
68131 ** mem[P3+2] are initialized to -1.
68132 */
68133 case OP_Checkpoint: {
68134 #if 0  /* local variables moved into u.cd */
68135   int i;                          /* Loop counter */
68136   int aRes[3];                    /* Results */
68137   Mem *pMem;                      /* Write results here */
68138 #endif /* local variables moved into u.cd */
68139
68140   u.cd.aRes[0] = 0;
68141   u.cd.aRes[1] = u.cd.aRes[2] = -1;
68142   assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
68143        || pOp->p2==SQLITE_CHECKPOINT_FULL
68144        || pOp->p2==SQLITE_CHECKPOINT_RESTART
68145   );
68146   rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &u.cd.aRes[1], &u.cd.aRes[2]);
68147   if( rc==SQLITE_BUSY ){
68148     rc = SQLITE_OK;
68149     u.cd.aRes[0] = 1;
68150   }
68151   for(u.cd.i=0, u.cd.pMem = &aMem[pOp->p3]; u.cd.i<3; u.cd.i++, u.cd.pMem++){
68152     sqlite3VdbeMemSetInt64(u.cd.pMem, (i64)u.cd.aRes[u.cd.i]);
68153   }
68154   break;
68155 };  
68156 #endif
68157
68158 #ifndef SQLITE_OMIT_PRAGMA
68159 /* Opcode: JournalMode P1 P2 P3 * P5
68160 **
68161 ** Change the journal mode of database P1 to P3. P3 must be one of the
68162 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
68163 ** modes (delete, truncate, persist, off and memory), this is a simple
68164 ** operation. No IO is required.
68165 **
68166 ** If changing into or out of WAL mode the procedure is more complicated.
68167 **
68168 ** Write a string containing the final journal-mode to register P2.
68169 */
68170 case OP_JournalMode: {    /* out2-prerelease */
68171 #if 0  /* local variables moved into u.ce */
68172   Btree *pBt;                     /* Btree to change journal mode of */
68173   Pager *pPager;                  /* Pager associated with pBt */
68174   int eNew;                       /* New journal mode */
68175   int eOld;                       /* The old journal mode */
68176   const char *zFilename;          /* Name of database file for pPager */
68177 #endif /* local variables moved into u.ce */
68178
68179   u.ce.eNew = pOp->p3;
68180   assert( u.ce.eNew==PAGER_JOURNALMODE_DELETE
68181        || u.ce.eNew==PAGER_JOURNALMODE_TRUNCATE
68182        || u.ce.eNew==PAGER_JOURNALMODE_PERSIST
68183        || u.ce.eNew==PAGER_JOURNALMODE_OFF
68184        || u.ce.eNew==PAGER_JOURNALMODE_MEMORY
68185        || u.ce.eNew==PAGER_JOURNALMODE_WAL
68186        || u.ce.eNew==PAGER_JOURNALMODE_QUERY
68187   );
68188   assert( pOp->p1>=0 && pOp->p1<db->nDb );
68189
68190   u.ce.pBt = db->aDb[pOp->p1].pBt;
68191   u.ce.pPager = sqlite3BtreePager(u.ce.pBt);
68192   u.ce.eOld = sqlite3PagerGetJournalMode(u.ce.pPager);
68193   if( u.ce.eNew==PAGER_JOURNALMODE_QUERY ) u.ce.eNew = u.ce.eOld;
68194   if( !sqlite3PagerOkToChangeJournalMode(u.ce.pPager) ) u.ce.eNew = u.ce.eOld;
68195
68196 #ifndef SQLITE_OMIT_WAL
68197   u.ce.zFilename = sqlite3PagerFilename(u.ce.pPager);
68198
68199   /* Do not allow a transition to journal_mode=WAL for a database
68200   ** in temporary storage or if the VFS does not support shared memory
68201   */
68202   if( u.ce.eNew==PAGER_JOURNALMODE_WAL
68203    && (u.ce.zFilename[0]==0                         /* Temp file */
68204        || !sqlite3PagerWalSupported(u.ce.pPager))   /* No shared-memory support */
68205   ){
68206     u.ce.eNew = u.ce.eOld;
68207   }
68208
68209   if( (u.ce.eNew!=u.ce.eOld)
68210    && (u.ce.eOld==PAGER_JOURNALMODE_WAL || u.ce.eNew==PAGER_JOURNALMODE_WAL)
68211   ){
68212     if( !db->autoCommit || db->activeVdbeCnt>1 ){
68213       rc = SQLITE_ERROR;
68214       sqlite3SetString(&p->zErrMsg, db,
68215           "cannot change %s wal mode from within a transaction",
68216           (u.ce.eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
68217       );
68218       break;
68219     }else{
68220
68221       if( u.ce.eOld==PAGER_JOURNALMODE_WAL ){
68222         /* If leaving WAL mode, close the log file. If successful, the call
68223         ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
68224         ** file. An EXCLUSIVE lock may still be held on the database file
68225         ** after a successful return.
68226         */
68227         rc = sqlite3PagerCloseWal(u.ce.pPager);
68228         if( rc==SQLITE_OK ){
68229           sqlite3PagerSetJournalMode(u.ce.pPager, u.ce.eNew);
68230         }
68231       }else if( u.ce.eOld==PAGER_JOURNALMODE_MEMORY ){
68232         /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
68233         ** as an intermediate */
68234         sqlite3PagerSetJournalMode(u.ce.pPager, PAGER_JOURNALMODE_OFF);
68235       }
68236
68237       /* Open a transaction on the database file. Regardless of the journal
68238       ** mode, this transaction always uses a rollback journal.
68239       */
68240       assert( sqlite3BtreeIsInTrans(u.ce.pBt)==0 );
68241       if( rc==SQLITE_OK ){
68242         rc = sqlite3BtreeSetVersion(u.ce.pBt, (u.ce.eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
68243       }
68244     }
68245   }
68246 #endif /* ifndef SQLITE_OMIT_WAL */
68247
68248   if( rc ){
68249     u.ce.eNew = u.ce.eOld;
68250   }
68251   u.ce.eNew = sqlite3PagerSetJournalMode(u.ce.pPager, u.ce.eNew);
68252
68253   pOut = &aMem[pOp->p2];
68254   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
68255   pOut->z = (char *)sqlite3JournalModename(u.ce.eNew);
68256   pOut->n = sqlite3Strlen30(pOut->z);
68257   pOut->enc = SQLITE_UTF8;
68258   sqlite3VdbeChangeEncoding(pOut, encoding);
68259   break;
68260 };
68261 #endif /* SQLITE_OMIT_PRAGMA */
68262
68263 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
68264 /* Opcode: Vacuum * * * * *
68265 **
68266 ** Vacuum the entire database.  This opcode will cause other virtual
68267 ** machines to be created and run.  It may not be called from within
68268 ** a transaction.
68269 */
68270 case OP_Vacuum: {
68271   rc = sqlite3RunVacuum(&p->zErrMsg, db);
68272   break;
68273 }
68274 #endif
68275
68276 #if !defined(SQLITE_OMIT_AUTOVACUUM)
68277 /* Opcode: IncrVacuum P1 P2 * * *
68278 **
68279 ** Perform a single step of the incremental vacuum procedure on
68280 ** the P1 database. If the vacuum has finished, jump to instruction
68281 ** P2. Otherwise, fall through to the next instruction.
68282 */
68283 case OP_IncrVacuum: {        /* jump */
68284 #if 0  /* local variables moved into u.cf */
68285   Btree *pBt;
68286 #endif /* local variables moved into u.cf */
68287
68288   assert( pOp->p1>=0 && pOp->p1<db->nDb );
68289   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
68290   u.cf.pBt = db->aDb[pOp->p1].pBt;
68291   rc = sqlite3BtreeIncrVacuum(u.cf.pBt);
68292   if( rc==SQLITE_DONE ){
68293     pc = pOp->p2 - 1;
68294     rc = SQLITE_OK;
68295   }
68296   break;
68297 }
68298 #endif
68299
68300 /* Opcode: Expire P1 * * * *
68301 **
68302 ** Cause precompiled statements to become expired. An expired statement
68303 ** fails with an error code of SQLITE_SCHEMA if it is ever executed 
68304 ** (via sqlite3_step()).
68305 ** 
68306 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
68307 ** then only the currently executing statement is affected. 
68308 */
68309 case OP_Expire: {
68310   if( !pOp->p1 ){
68311     sqlite3ExpirePreparedStatements(db);
68312   }else{
68313     p->expired = 1;
68314   }
68315   break;
68316 }
68317
68318 #ifndef SQLITE_OMIT_SHARED_CACHE
68319 /* Opcode: TableLock P1 P2 P3 P4 *
68320 **
68321 ** Obtain a lock on a particular table. This instruction is only used when
68322 ** the shared-cache feature is enabled. 
68323 **
68324 ** P1 is the index of the database in sqlite3.aDb[] of the database
68325 ** on which the lock is acquired.  A readlock is obtained if P3==0 or
68326 ** a write lock if P3==1.
68327 **
68328 ** P2 contains the root-page of the table to lock.
68329 **
68330 ** P4 contains a pointer to the name of the table being locked. This is only
68331 ** used to generate an error message if the lock cannot be obtained.
68332 */
68333 case OP_TableLock: {
68334   u8 isWriteLock = (u8)pOp->p3;
68335   if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
68336     int p1 = pOp->p1; 
68337     assert( p1>=0 && p1<db->nDb );
68338     assert( (p->btreeMask & (((yDbMask)1)<<p1))!=0 );
68339     assert( isWriteLock==0 || isWriteLock==1 );
68340     rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
68341     if( (rc&0xFF)==SQLITE_LOCKED ){
68342       const char *z = pOp->p4.z;
68343       sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
68344     }
68345   }
68346   break;
68347 }
68348 #endif /* SQLITE_OMIT_SHARED_CACHE */
68349
68350 #ifndef SQLITE_OMIT_VIRTUALTABLE
68351 /* Opcode: VBegin * * * P4 *
68352 **
68353 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the 
68354 ** xBegin method for that table.
68355 **
68356 ** Also, whether or not P4 is set, check that this is not being called from
68357 ** within a callback to a virtual table xSync() method. If it is, the error
68358 ** code will be set to SQLITE_LOCKED.
68359 */
68360 case OP_VBegin: {
68361 #if 0  /* local variables moved into u.cg */
68362   VTable *pVTab;
68363 #endif /* local variables moved into u.cg */
68364   u.cg.pVTab = pOp->p4.pVtab;
68365   rc = sqlite3VtabBegin(db, u.cg.pVTab);
68366   if( u.cg.pVTab ) importVtabErrMsg(p, u.cg.pVTab->pVtab);
68367   break;
68368 }
68369 #endif /* SQLITE_OMIT_VIRTUALTABLE */
68370
68371 #ifndef SQLITE_OMIT_VIRTUALTABLE
68372 /* Opcode: VCreate P1 * * P4 *
68373 **
68374 ** P4 is the name of a virtual table in database P1. Call the xCreate method
68375 ** for that table.
68376 */
68377 case OP_VCreate: {
68378   rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
68379   break;
68380 }
68381 #endif /* SQLITE_OMIT_VIRTUALTABLE */
68382
68383 #ifndef SQLITE_OMIT_VIRTUALTABLE
68384 /* Opcode: VDestroy P1 * * P4 *
68385 **
68386 ** P4 is the name of a virtual table in database P1.  Call the xDestroy method
68387 ** of that table.
68388 */
68389 case OP_VDestroy: {
68390   p->inVtabMethod = 2;
68391   rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
68392   p->inVtabMethod = 0;
68393   break;
68394 }
68395 #endif /* SQLITE_OMIT_VIRTUALTABLE */
68396
68397 #ifndef SQLITE_OMIT_VIRTUALTABLE
68398 /* Opcode: VOpen P1 * * P4 *
68399 **
68400 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
68401 ** P1 is a cursor number.  This opcode opens a cursor to the virtual
68402 ** table and stores that cursor in P1.
68403 */
68404 case OP_VOpen: {
68405 #if 0  /* local variables moved into u.ch */
68406   VdbeCursor *pCur;
68407   sqlite3_vtab_cursor *pVtabCursor;
68408   sqlite3_vtab *pVtab;
68409   sqlite3_module *pModule;
68410 #endif /* local variables moved into u.ch */
68411
68412   u.ch.pCur = 0;
68413   u.ch.pVtabCursor = 0;
68414   u.ch.pVtab = pOp->p4.pVtab->pVtab;
68415   u.ch.pModule = (sqlite3_module *)u.ch.pVtab->pModule;
68416   assert(u.ch.pVtab && u.ch.pModule);
68417   rc = u.ch.pModule->xOpen(u.ch.pVtab, &u.ch.pVtabCursor);
68418   importVtabErrMsg(p, u.ch.pVtab);
68419   if( SQLITE_OK==rc ){
68420     /* Initialize sqlite3_vtab_cursor base class */
68421     u.ch.pVtabCursor->pVtab = u.ch.pVtab;
68422
68423     /* Initialise vdbe cursor object */
68424     u.ch.pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
68425     if( u.ch.pCur ){
68426       u.ch.pCur->pVtabCursor = u.ch.pVtabCursor;
68427       u.ch.pCur->pModule = u.ch.pVtabCursor->pVtab->pModule;
68428     }else{
68429       db->mallocFailed = 1;
68430       u.ch.pModule->xClose(u.ch.pVtabCursor);
68431     }
68432   }
68433   break;
68434 }
68435 #endif /* SQLITE_OMIT_VIRTUALTABLE */
68436
68437 #ifndef SQLITE_OMIT_VIRTUALTABLE
68438 /* Opcode: VFilter P1 P2 P3 P4 *
68439 **
68440 ** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
68441 ** the filtered result set is empty.
68442 **
68443 ** P4 is either NULL or a string that was generated by the xBestIndex
68444 ** method of the module.  The interpretation of the P4 string is left
68445 ** to the module implementation.
68446 **
68447 ** This opcode invokes the xFilter method on the virtual table specified
68448 ** by P1.  The integer query plan parameter to xFilter is stored in register
68449 ** P3. Register P3+1 stores the argc parameter to be passed to the
68450 ** xFilter method. Registers P3+2..P3+1+argc are the argc
68451 ** additional parameters which are passed to
68452 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
68453 **
68454 ** A jump is made to P2 if the result set after filtering would be empty.
68455 */
68456 case OP_VFilter: {   /* jump */
68457 #if 0  /* local variables moved into u.ci */
68458   int nArg;
68459   int iQuery;
68460   const sqlite3_module *pModule;
68461   Mem *pQuery;
68462   Mem *pArgc;
68463   sqlite3_vtab_cursor *pVtabCursor;
68464   sqlite3_vtab *pVtab;
68465   VdbeCursor *pCur;
68466   int res;
68467   int i;
68468   Mem **apArg;
68469 #endif /* local variables moved into u.ci */
68470
68471   u.ci.pQuery = &aMem[pOp->p3];
68472   u.ci.pArgc = &u.ci.pQuery[1];
68473   u.ci.pCur = p->apCsr[pOp->p1];
68474   assert( memIsValid(u.ci.pQuery) );
68475   REGISTER_TRACE(pOp->p3, u.ci.pQuery);
68476   assert( u.ci.pCur->pVtabCursor );
68477   u.ci.pVtabCursor = u.ci.pCur->pVtabCursor;
68478   u.ci.pVtab = u.ci.pVtabCursor->pVtab;
68479   u.ci.pModule = u.ci.pVtab->pModule;
68480
68481   /* Grab the index number and argc parameters */
68482   assert( (u.ci.pQuery->flags&MEM_Int)!=0 && u.ci.pArgc->flags==MEM_Int );
68483   u.ci.nArg = (int)u.ci.pArgc->u.i;
68484   u.ci.iQuery = (int)u.ci.pQuery->u.i;
68485
68486   /* Invoke the xFilter method */
68487   {
68488     u.ci.res = 0;
68489     u.ci.apArg = p->apArg;
68490     for(u.ci.i = 0; u.ci.i<u.ci.nArg; u.ci.i++){
68491       u.ci.apArg[u.ci.i] = &u.ci.pArgc[u.ci.i+1];
68492       sqlite3VdbeMemStoreType(u.ci.apArg[u.ci.i]);
68493     }
68494
68495     p->inVtabMethod = 1;
68496     rc = u.ci.pModule->xFilter(u.ci.pVtabCursor, u.ci.iQuery, pOp->p4.z, u.ci.nArg, u.ci.apArg);
68497     p->inVtabMethod = 0;
68498     importVtabErrMsg(p, u.ci.pVtab);
68499     if( rc==SQLITE_OK ){
68500       u.ci.res = u.ci.pModule->xEof(u.ci.pVtabCursor);
68501     }
68502
68503     if( u.ci.res ){
68504       pc = pOp->p2 - 1;
68505     }
68506   }
68507   u.ci.pCur->nullRow = 0;
68508
68509   break;
68510 }
68511 #endif /* SQLITE_OMIT_VIRTUALTABLE */
68512
68513 #ifndef SQLITE_OMIT_VIRTUALTABLE
68514 /* Opcode: VColumn P1 P2 P3 * *
68515 **
68516 ** Store the value of the P2-th column of
68517 ** the row of the virtual-table that the 
68518 ** P1 cursor is pointing to into register P3.
68519 */
68520 case OP_VColumn: {
68521 #if 0  /* local variables moved into u.cj */
68522   sqlite3_vtab *pVtab;
68523   const sqlite3_module *pModule;
68524   Mem *pDest;
68525   sqlite3_context sContext;
68526 #endif /* local variables moved into u.cj */
68527
68528   VdbeCursor *pCur = p->apCsr[pOp->p1];
68529   assert( pCur->pVtabCursor );
68530   assert( pOp->p3>0 && pOp->p3<=p->nMem );
68531   u.cj.pDest = &aMem[pOp->p3];
68532   memAboutToChange(p, u.cj.pDest);
68533   if( pCur->nullRow ){
68534     sqlite3VdbeMemSetNull(u.cj.pDest);
68535     break;
68536   }
68537   u.cj.pVtab = pCur->pVtabCursor->pVtab;
68538   u.cj.pModule = u.cj.pVtab->pModule;
68539   assert( u.cj.pModule->xColumn );
68540   memset(&u.cj.sContext, 0, sizeof(u.cj.sContext));
68541
68542   /* The output cell may already have a buffer allocated. Move
68543   ** the current contents to u.cj.sContext.s so in case the user-function
68544   ** can use the already allocated buffer instead of allocating a
68545   ** new one.
68546   */
68547   sqlite3VdbeMemMove(&u.cj.sContext.s, u.cj.pDest);
68548   MemSetTypeFlag(&u.cj.sContext.s, MEM_Null);
68549
68550   rc = u.cj.pModule->xColumn(pCur->pVtabCursor, &u.cj.sContext, pOp->p2);
68551   importVtabErrMsg(p, u.cj.pVtab);
68552   if( u.cj.sContext.isError ){
68553     rc = u.cj.sContext.isError;
68554   }
68555
68556   /* Copy the result of the function to the P3 register. We
68557   ** do this regardless of whether or not an error occurred to ensure any
68558   ** dynamic allocation in u.cj.sContext.s (a Mem struct) is  released.
68559   */
68560   sqlite3VdbeChangeEncoding(&u.cj.sContext.s, encoding);
68561   sqlite3VdbeMemMove(u.cj.pDest, &u.cj.sContext.s);
68562   REGISTER_TRACE(pOp->p3, u.cj.pDest);
68563   UPDATE_MAX_BLOBSIZE(u.cj.pDest);
68564
68565   if( sqlite3VdbeMemTooBig(u.cj.pDest) ){
68566     goto too_big;
68567   }
68568   break;
68569 }
68570 #endif /* SQLITE_OMIT_VIRTUALTABLE */
68571
68572 #ifndef SQLITE_OMIT_VIRTUALTABLE
68573 /* Opcode: VNext P1 P2 * * *
68574 **
68575 ** Advance virtual table P1 to the next row in its result set and
68576 ** jump to instruction P2.  Or, if the virtual table has reached
68577 ** the end of its result set, then fall through to the next instruction.
68578 */
68579 case OP_VNext: {   /* jump */
68580 #if 0  /* local variables moved into u.ck */
68581   sqlite3_vtab *pVtab;
68582   const sqlite3_module *pModule;
68583   int res;
68584   VdbeCursor *pCur;
68585 #endif /* local variables moved into u.ck */
68586
68587   u.ck.res = 0;
68588   u.ck.pCur = p->apCsr[pOp->p1];
68589   assert( u.ck.pCur->pVtabCursor );
68590   if( u.ck.pCur->nullRow ){
68591     break;
68592   }
68593   u.ck.pVtab = u.ck.pCur->pVtabCursor->pVtab;
68594   u.ck.pModule = u.ck.pVtab->pModule;
68595   assert( u.ck.pModule->xNext );
68596
68597   /* Invoke the xNext() method of the module. There is no way for the
68598   ** underlying implementation to return an error if one occurs during
68599   ** xNext(). Instead, if an error occurs, true is returned (indicating that
68600   ** data is available) and the error code returned when xColumn or
68601   ** some other method is next invoked on the save virtual table cursor.
68602   */
68603   p->inVtabMethod = 1;
68604   rc = u.ck.pModule->xNext(u.ck.pCur->pVtabCursor);
68605   p->inVtabMethod = 0;
68606   importVtabErrMsg(p, u.ck.pVtab);
68607   if( rc==SQLITE_OK ){
68608     u.ck.res = u.ck.pModule->xEof(u.ck.pCur->pVtabCursor);
68609   }
68610
68611   if( !u.ck.res ){
68612     /* If there is data, jump to P2 */
68613     pc = pOp->p2 - 1;
68614   }
68615   break;
68616 }
68617 #endif /* SQLITE_OMIT_VIRTUALTABLE */
68618
68619 #ifndef SQLITE_OMIT_VIRTUALTABLE
68620 /* Opcode: VRename P1 * * P4 *
68621 **
68622 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
68623 ** This opcode invokes the corresponding xRename method. The value
68624 ** in register P1 is passed as the zName argument to the xRename method.
68625 */
68626 case OP_VRename: {
68627 #if 0  /* local variables moved into u.cl */
68628   sqlite3_vtab *pVtab;
68629   Mem *pName;
68630 #endif /* local variables moved into u.cl */
68631
68632   u.cl.pVtab = pOp->p4.pVtab->pVtab;
68633   u.cl.pName = &aMem[pOp->p1];
68634   assert( u.cl.pVtab->pModule->xRename );
68635   assert( memIsValid(u.cl.pName) );
68636   REGISTER_TRACE(pOp->p1, u.cl.pName);
68637   assert( u.cl.pName->flags & MEM_Str );
68638   rc = u.cl.pVtab->pModule->xRename(u.cl.pVtab, u.cl.pName->z);
68639   importVtabErrMsg(p, u.cl.pVtab);
68640   p->expired = 0;
68641
68642   break;
68643 }
68644 #endif
68645
68646 #ifndef SQLITE_OMIT_VIRTUALTABLE
68647 /* Opcode: VUpdate P1 P2 P3 P4 *
68648 **
68649 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
68650 ** This opcode invokes the corresponding xUpdate method. P2 values
68651 ** are contiguous memory cells starting at P3 to pass to the xUpdate 
68652 ** invocation. The value in register (P3+P2-1) corresponds to the 
68653 ** p2th element of the argv array passed to xUpdate.
68654 **
68655 ** The xUpdate method will do a DELETE or an INSERT or both.
68656 ** The argv[0] element (which corresponds to memory cell P3)
68657 ** is the rowid of a row to delete.  If argv[0] is NULL then no 
68658 ** deletion occurs.  The argv[1] element is the rowid of the new 
68659 ** row.  This can be NULL to have the virtual table select the new 
68660 ** rowid for itself.  The subsequent elements in the array are 
68661 ** the values of columns in the new row.
68662 **
68663 ** If P2==1 then no insert is performed.  argv[0] is the rowid of
68664 ** a row to delete.
68665 **
68666 ** P1 is a boolean flag. If it is set to true and the xUpdate call
68667 ** is successful, then the value returned by sqlite3_last_insert_rowid() 
68668 ** is set to the value of the rowid for the row just inserted.
68669 */
68670 case OP_VUpdate: {
68671 #if 0  /* local variables moved into u.cm */
68672   sqlite3_vtab *pVtab;
68673   sqlite3_module *pModule;
68674   int nArg;
68675   int i;
68676   sqlite_int64 rowid;
68677   Mem **apArg;
68678   Mem *pX;
68679 #endif /* local variables moved into u.cm */
68680
68681   assert( pOp->p2==1        || pOp->p5==OE_Fail   || pOp->p5==OE_Rollback
68682        || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
68683   );
68684   u.cm.pVtab = pOp->p4.pVtab->pVtab;
68685   u.cm.pModule = (sqlite3_module *)u.cm.pVtab->pModule;
68686   u.cm.nArg = pOp->p2;
68687   assert( pOp->p4type==P4_VTAB );
68688   if( ALWAYS(u.cm.pModule->xUpdate) ){
68689     u8 vtabOnConflict = db->vtabOnConflict;
68690     u.cm.apArg = p->apArg;
68691     u.cm.pX = &aMem[pOp->p3];
68692     for(u.cm.i=0; u.cm.i<u.cm.nArg; u.cm.i++){
68693       assert( memIsValid(u.cm.pX) );
68694       memAboutToChange(p, u.cm.pX);
68695       sqlite3VdbeMemStoreType(u.cm.pX);
68696       u.cm.apArg[u.cm.i] = u.cm.pX;
68697       u.cm.pX++;
68698     }
68699     db->vtabOnConflict = pOp->p5;
68700     rc = u.cm.pModule->xUpdate(u.cm.pVtab, u.cm.nArg, u.cm.apArg, &u.cm.rowid);
68701     db->vtabOnConflict = vtabOnConflict;
68702     importVtabErrMsg(p, u.cm.pVtab);
68703     if( rc==SQLITE_OK && pOp->p1 ){
68704       assert( u.cm.nArg>1 && u.cm.apArg[0] && (u.cm.apArg[0]->flags&MEM_Null) );
68705       db->lastRowid = lastRowid = u.cm.rowid;
68706     }
68707     if( rc==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
68708       if( pOp->p5==OE_Ignore ){
68709         rc = SQLITE_OK;
68710       }else{
68711         p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
68712       }
68713     }else{
68714       p->nChange++;
68715     }
68716   }
68717   break;
68718 }
68719 #endif /* SQLITE_OMIT_VIRTUALTABLE */
68720
68721 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
68722 /* Opcode: Pagecount P1 P2 * * *
68723 **
68724 ** Write the current number of pages in database P1 to memory cell P2.
68725 */
68726 case OP_Pagecount: {            /* out2-prerelease */
68727   pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
68728   break;
68729 }
68730 #endif
68731
68732
68733 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
68734 /* Opcode: MaxPgcnt P1 P2 P3 * *
68735 **
68736 ** Try to set the maximum page count for database P1 to the value in P3.
68737 ** Do not let the maximum page count fall below the current page count and
68738 ** do not change the maximum page count value if P3==0.
68739 **
68740 ** Store the maximum page count after the change in register P2.
68741 */
68742 case OP_MaxPgcnt: {            /* out2-prerelease */
68743   unsigned int newMax;
68744   Btree *pBt;
68745
68746   pBt = db->aDb[pOp->p1].pBt;
68747   newMax = 0;
68748   if( pOp->p3 ){
68749     newMax = sqlite3BtreeLastPage(pBt);
68750     if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
68751   }
68752   pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
68753   break;
68754 }
68755 #endif
68756
68757
68758 #ifndef SQLITE_OMIT_TRACE
68759 /* Opcode: Trace * * * P4 *
68760 **
68761 ** If tracing is enabled (by the sqlite3_trace()) interface, then
68762 ** the UTF-8 string contained in P4 is emitted on the trace callback.
68763 */
68764 case OP_Trace: {
68765 #if 0  /* local variables moved into u.cn */
68766   char *zTrace;
68767   char *z;
68768 #endif /* local variables moved into u.cn */
68769
68770   if( db->xTrace && (u.cn.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0 ){
68771     u.cn.z = sqlite3VdbeExpandSql(p, u.cn.zTrace);
68772     db->xTrace(db->pTraceArg, u.cn.z);
68773     sqlite3DbFree(db, u.cn.z);
68774   }
68775 #ifdef SQLITE_DEBUG
68776   if( (db->flags & SQLITE_SqlTrace)!=0
68777    && (u.cn.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
68778   ){
68779     sqlite3DebugPrintf("SQL-trace: %s\n", u.cn.zTrace);
68780   }
68781 #endif /* SQLITE_DEBUG */
68782   break;
68783 }
68784 #endif
68785
68786
68787 /* Opcode: Noop * * * * *
68788 **
68789 ** Do nothing.  This instruction is often useful as a jump
68790 ** destination.
68791 */
68792 /*
68793 ** The magic Explain opcode are only inserted when explain==2 (which
68794 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
68795 ** This opcode records information from the optimizer.  It is the
68796 ** the same as a no-op.  This opcodesnever appears in a real VM program.
68797 */
68798 default: {          /* This is really OP_Noop and OP_Explain */
68799   assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
68800   break;
68801 }
68802
68803 /*****************************************************************************
68804 ** The cases of the switch statement above this line should all be indented
68805 ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
68806 ** readability.  From this point on down, the normal indentation rules are
68807 ** restored.
68808 *****************************************************************************/
68809     }
68810
68811 #ifdef VDBE_PROFILE
68812     {
68813       u64 elapsed = sqlite3Hwtime() - start;
68814       pOp->cycles += elapsed;
68815       pOp->cnt++;
68816 #if 0
68817         fprintf(stdout, "%10llu ", elapsed);
68818         sqlite3VdbePrintOp(stdout, origPc, &aOp[origPc]);
68819 #endif
68820     }
68821 #endif
68822
68823     /* The following code adds nothing to the actual functionality
68824     ** of the program.  It is only here for testing and debugging.
68825     ** On the other hand, it does burn CPU cycles every time through
68826     ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
68827     */
68828 #ifndef NDEBUG
68829     assert( pc>=-1 && pc<p->nOp );
68830
68831 #ifdef SQLITE_DEBUG
68832     if( p->trace ){
68833       if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
68834       if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
68835         registerTrace(p->trace, pOp->p2, &aMem[pOp->p2]);
68836       }
68837       if( pOp->opflags & OPFLG_OUT3 ){
68838         registerTrace(p->trace, pOp->p3, &aMem[pOp->p3]);
68839       }
68840     }
68841 #endif  /* SQLITE_DEBUG */
68842 #endif  /* NDEBUG */
68843   }  /* The end of the for(;;) loop the loops through opcodes */
68844
68845   /* If we reach this point, it means that execution is finished with
68846   ** an error of some kind.
68847   */
68848 vdbe_error_halt:
68849   assert( rc );
68850   p->rc = rc;
68851   testcase( sqlite3GlobalConfig.xLog!=0 );
68852   sqlite3_log(rc, "statement aborts at %d: [%s] %s", 
68853                    pc, p->zSql, p->zErrMsg);
68854   sqlite3VdbeHalt(p);
68855   if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
68856   rc = SQLITE_ERROR;
68857   if( resetSchemaOnFault>0 ){
68858     sqlite3ResetInternalSchema(db, resetSchemaOnFault-1);
68859   }
68860
68861   /* This is the only way out of this procedure.  We have to
68862   ** release the mutexes on btrees that were acquired at the
68863   ** top. */
68864 vdbe_return:
68865   db->lastRowid = lastRowid;
68866   sqlite3VdbeLeave(p);
68867   return rc;
68868
68869   /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
68870   ** is encountered.
68871   */
68872 too_big:
68873   sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
68874   rc = SQLITE_TOOBIG;
68875   goto vdbe_error_halt;
68876
68877   /* Jump to here if a malloc() fails.
68878   */
68879 no_mem:
68880   db->mallocFailed = 1;
68881   sqlite3SetString(&p->zErrMsg, db, "out of memory");
68882   rc = SQLITE_NOMEM;
68883   goto vdbe_error_halt;
68884
68885   /* Jump to here for any other kind of fatal error.  The "rc" variable
68886   ** should hold the error number.
68887   */
68888 abort_due_to_error:
68889   assert( p->zErrMsg==0 );
68890   if( db->mallocFailed ) rc = SQLITE_NOMEM;
68891   if( rc!=SQLITE_IOERR_NOMEM ){
68892     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
68893   }
68894   goto vdbe_error_halt;
68895
68896   /* Jump to here if the sqlite3_interrupt() API sets the interrupt
68897   ** flag.
68898   */
68899 abort_due_to_interrupt:
68900   assert( db->u1.isInterrupted );
68901   rc = SQLITE_INTERRUPT;
68902   p->rc = rc;
68903   sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
68904   goto vdbe_error_halt;
68905 }
68906
68907 /************** End of vdbe.c ************************************************/
68908 /************** Begin file vdbeblob.c ****************************************/
68909 /*
68910 ** 2007 May 1
68911 **
68912 ** The author disclaims copyright to this source code.  In place of
68913 ** a legal notice, here is a blessing:
68914 **
68915 **    May you do good and not evil.
68916 **    May you find forgiveness for yourself and forgive others.
68917 **    May you share freely, never taking more than you give.
68918 **
68919 *************************************************************************
68920 **
68921 ** This file contains code used to implement incremental BLOB I/O.
68922 */
68923
68924
68925 #ifndef SQLITE_OMIT_INCRBLOB
68926
68927 /*
68928 ** Valid sqlite3_blob* handles point to Incrblob structures.
68929 */
68930 typedef struct Incrblob Incrblob;
68931 struct Incrblob {
68932   int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
68933   int nByte;              /* Size of open blob, in bytes */
68934   int iOffset;            /* Byte offset of blob in cursor data */
68935   int iCol;               /* Table column this handle is open on */
68936   BtCursor *pCsr;         /* Cursor pointing at blob row */
68937   sqlite3_stmt *pStmt;    /* Statement holding cursor open */
68938   sqlite3 *db;            /* The associated database */
68939 };
68940
68941
68942 /*
68943 ** This function is used by both blob_open() and blob_reopen(). It seeks
68944 ** the b-tree cursor associated with blob handle p to point to row iRow.
68945 ** If successful, SQLITE_OK is returned and subsequent calls to
68946 ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
68947 **
68948 ** If an error occurs, or if the specified row does not exist or does not
68949 ** contain a value of type TEXT or BLOB in the column nominated when the
68950 ** blob handle was opened, then an error code is returned and *pzErr may
68951 ** be set to point to a buffer containing an error message. It is the
68952 ** responsibility of the caller to free the error message buffer using
68953 ** sqlite3DbFree().
68954 **
68955 ** If an error does occur, then the b-tree cursor is closed. All subsequent
68956 ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will 
68957 ** immediately return SQLITE_ABORT.
68958 */
68959 static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
68960   int rc;                         /* Error code */
68961   char *zErr = 0;                 /* Error message */
68962   Vdbe *v = (Vdbe *)p->pStmt;
68963
68964   /* Set the value of the SQL statements only variable to integer iRow. 
68965   ** This is done directly instead of using sqlite3_bind_int64() to avoid 
68966   ** triggering asserts related to mutexes.
68967   */
68968   assert( v->aVar[0].flags&MEM_Int );
68969   v->aVar[0].u.i = iRow;
68970
68971   rc = sqlite3_step(p->pStmt);
68972   if( rc==SQLITE_ROW ){
68973     u32 type = v->apCsr[0]->aType[p->iCol];
68974     if( type<12 ){
68975       zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
68976           type==0?"null": type==7?"real": "integer"
68977       );
68978       rc = SQLITE_ERROR;
68979       sqlite3_finalize(p->pStmt);
68980       p->pStmt = 0;
68981     }else{
68982       p->iOffset = v->apCsr[0]->aOffset[p->iCol];
68983       p->nByte = sqlite3VdbeSerialTypeLen(type);
68984       p->pCsr =  v->apCsr[0]->pCursor;
68985       sqlite3BtreeEnterCursor(p->pCsr);
68986       sqlite3BtreeCacheOverflow(p->pCsr);
68987       sqlite3BtreeLeaveCursor(p->pCsr);
68988     }
68989   }
68990
68991   if( rc==SQLITE_ROW ){
68992     rc = SQLITE_OK;
68993   }else if( p->pStmt ){
68994     rc = sqlite3_finalize(p->pStmt);
68995     p->pStmt = 0;
68996     if( rc==SQLITE_OK ){
68997       zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
68998       rc = SQLITE_ERROR;
68999     }else{
69000       zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
69001     }
69002   }
69003
69004   assert( rc!=SQLITE_OK || zErr==0 );
69005   assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
69006
69007   *pzErr = zErr;
69008   return rc;
69009 }
69010
69011 /*
69012 ** Open a blob handle.
69013 */
69014 SQLITE_API int sqlite3_blob_open(
69015   sqlite3* db,            /* The database connection */
69016   const char *zDb,        /* The attached database containing the blob */
69017   const char *zTable,     /* The table containing the blob */
69018   const char *zColumn,    /* The column containing the blob */
69019   sqlite_int64 iRow,      /* The row containing the glob */
69020   int flags,              /* True -> read/write access, false -> read-only */
69021   sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
69022 ){
69023   int nAttempt = 0;
69024   int iCol;               /* Index of zColumn in row-record */
69025
69026   /* This VDBE program seeks a btree cursor to the identified 
69027   ** db/table/row entry. The reason for using a vdbe program instead
69028   ** of writing code to use the b-tree layer directly is that the
69029   ** vdbe program will take advantage of the various transaction,
69030   ** locking and error handling infrastructure built into the vdbe.
69031   **
69032   ** After seeking the cursor, the vdbe executes an OP_ResultRow.
69033   ** Code external to the Vdbe then "borrows" the b-tree cursor and
69034   ** uses it to implement the blob_read(), blob_write() and 
69035   ** blob_bytes() functions.
69036   **
69037   ** The sqlite3_blob_close() function finalizes the vdbe program,
69038   ** which closes the b-tree cursor and (possibly) commits the 
69039   ** transaction.
69040   */
69041   static const VdbeOpList openBlob[] = {
69042     {OP_Transaction, 0, 0, 0},     /* 0: Start a transaction */
69043     {OP_VerifyCookie, 0, 0, 0},    /* 1: Check the schema cookie */
69044     {OP_TableLock, 0, 0, 0},       /* 2: Acquire a read or write lock */
69045
69046     /* One of the following two instructions is replaced by an OP_Noop. */
69047     {OP_OpenRead, 0, 0, 0},        /* 3: Open cursor 0 for reading */
69048     {OP_OpenWrite, 0, 0, 0},       /* 4: Open cursor 0 for read/write */
69049
69050     {OP_Variable, 1, 1, 1},        /* 5: Push the rowid to the stack */
69051     {OP_NotExists, 0, 10, 1},      /* 6: Seek the cursor */
69052     {OP_Column, 0, 0, 1},          /* 7  */
69053     {OP_ResultRow, 1, 0, 0},       /* 8  */
69054     {OP_Goto, 0, 5, 0},            /* 9  */
69055     {OP_Close, 0, 0, 0},           /* 10 */
69056     {OP_Halt, 0, 0, 0},            /* 11 */
69057   };
69058
69059   int rc = SQLITE_OK;
69060   char *zErr = 0;
69061   Table *pTab;
69062   Parse *pParse = 0;
69063   Incrblob *pBlob = 0;
69064
69065   flags = !!flags;                /* flags = (flags ? 1 : 0); */
69066   *ppBlob = 0;
69067
69068   sqlite3_mutex_enter(db->mutex);
69069
69070   pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
69071   if( !pBlob ) goto blob_open_out;
69072   pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
69073   if( !pParse ) goto blob_open_out;
69074
69075   do {
69076     memset(pParse, 0, sizeof(Parse));
69077     pParse->db = db;
69078     sqlite3DbFree(db, zErr);
69079     zErr = 0;
69080
69081     sqlite3BtreeEnterAll(db);
69082     pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
69083     if( pTab && IsVirtual(pTab) ){
69084       pTab = 0;
69085       sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
69086     }
69087 #ifndef SQLITE_OMIT_VIEW
69088     if( pTab && pTab->pSelect ){
69089       pTab = 0;
69090       sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
69091     }
69092 #endif
69093     if( !pTab ){
69094       if( pParse->zErrMsg ){
69095         sqlite3DbFree(db, zErr);
69096         zErr = pParse->zErrMsg;
69097         pParse->zErrMsg = 0;
69098       }
69099       rc = SQLITE_ERROR;
69100       sqlite3BtreeLeaveAll(db);
69101       goto blob_open_out;
69102     }
69103
69104     /* Now search pTab for the exact column. */
69105     for(iCol=0; iCol<pTab->nCol; iCol++) {
69106       if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
69107         break;
69108       }
69109     }
69110     if( iCol==pTab->nCol ){
69111       sqlite3DbFree(db, zErr);
69112       zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
69113       rc = SQLITE_ERROR;
69114       sqlite3BtreeLeaveAll(db);
69115       goto blob_open_out;
69116     }
69117
69118     /* If the value is being opened for writing, check that the
69119     ** column is not indexed, and that it is not part of a foreign key. 
69120     ** It is against the rules to open a column to which either of these
69121     ** descriptions applies for writing.  */
69122     if( flags ){
69123       const char *zFault = 0;
69124       Index *pIdx;
69125 #ifndef SQLITE_OMIT_FOREIGN_KEY
69126       if( db->flags&SQLITE_ForeignKeys ){
69127         /* Check that the column is not part of an FK child key definition. It
69128         ** is not necessary to check if it is part of a parent key, as parent
69129         ** key columns must be indexed. The check below will pick up this 
69130         ** case.  */
69131         FKey *pFKey;
69132         for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
69133           int j;
69134           for(j=0; j<pFKey->nCol; j++){
69135             if( pFKey->aCol[j].iFrom==iCol ){
69136               zFault = "foreign key";
69137             }
69138           }
69139         }
69140       }
69141 #endif
69142       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
69143         int j;
69144         for(j=0; j<pIdx->nColumn; j++){
69145           if( pIdx->aiColumn[j]==iCol ){
69146             zFault = "indexed";
69147           }
69148         }
69149       }
69150       if( zFault ){
69151         sqlite3DbFree(db, zErr);
69152         zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
69153         rc = SQLITE_ERROR;
69154         sqlite3BtreeLeaveAll(db);
69155         goto blob_open_out;
69156       }
69157     }
69158
69159     pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(db);
69160     assert( pBlob->pStmt || db->mallocFailed );
69161     if( pBlob->pStmt ){
69162       Vdbe *v = (Vdbe *)pBlob->pStmt;
69163       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
69164
69165       sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
69166
69167
69168       /* Configure the OP_Transaction */
69169       sqlite3VdbeChangeP1(v, 0, iDb);
69170       sqlite3VdbeChangeP2(v, 0, flags);
69171
69172       /* Configure the OP_VerifyCookie */
69173       sqlite3VdbeChangeP1(v, 1, iDb);
69174       sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
69175       sqlite3VdbeChangeP3(v, 1, pTab->pSchema->iGeneration);
69176
69177       /* Make sure a mutex is held on the table to be accessed */
69178       sqlite3VdbeUsesBtree(v, iDb); 
69179
69180       /* Configure the OP_TableLock instruction */
69181 #ifdef SQLITE_OMIT_SHARED_CACHE
69182       sqlite3VdbeChangeToNoop(v, 2, 1);
69183 #else
69184       sqlite3VdbeChangeP1(v, 2, iDb);
69185       sqlite3VdbeChangeP2(v, 2, pTab->tnum);
69186       sqlite3VdbeChangeP3(v, 2, flags);
69187       sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
69188 #endif
69189
69190       /* Remove either the OP_OpenWrite or OpenRead. Set the P2 
69191       ** parameter of the other to pTab->tnum.  */
69192       sqlite3VdbeChangeToNoop(v, 4 - flags, 1);
69193       sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum);
69194       sqlite3VdbeChangeP3(v, 3 + flags, iDb);
69195
69196       /* Configure the number of columns. Configure the cursor to
69197       ** think that the table has one more column than it really
69198       ** does. An OP_Column to retrieve this imaginary column will
69199       ** always return an SQL NULL. This is useful because it means
69200       ** we can invoke OP_Column to fill in the vdbe cursors type 
69201       ** and offset cache without causing any IO.
69202       */
69203       sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
69204       sqlite3VdbeChangeP2(v, 7, pTab->nCol);
69205       if( !db->mallocFailed ){
69206         pParse->nVar = 1;
69207         pParse->nMem = 1;
69208         pParse->nTab = 1;
69209         sqlite3VdbeMakeReady(v, pParse);
69210       }
69211     }
69212    
69213     pBlob->flags = flags;
69214     pBlob->iCol = iCol;
69215     pBlob->db = db;
69216     sqlite3BtreeLeaveAll(db);
69217     if( db->mallocFailed ){
69218       goto blob_open_out;
69219     }
69220     sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
69221     rc = blobSeekToRow(pBlob, iRow, &zErr);
69222   } while( (++nAttempt)<5 && rc==SQLITE_SCHEMA );
69223
69224 blob_open_out:
69225   if( rc==SQLITE_OK && db->mallocFailed==0 ){
69226     *ppBlob = (sqlite3_blob *)pBlob;
69227   }else{
69228     if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
69229     sqlite3DbFree(db, pBlob);
69230   }
69231   sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
69232   sqlite3DbFree(db, zErr);
69233   sqlite3StackFree(db, pParse);
69234   rc = sqlite3ApiExit(db, rc);
69235   sqlite3_mutex_leave(db->mutex);
69236   return rc;
69237 }
69238
69239 /*
69240 ** Close a blob handle that was previously created using
69241 ** sqlite3_blob_open().
69242 */
69243 SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
69244   Incrblob *p = (Incrblob *)pBlob;
69245   int rc;
69246   sqlite3 *db;
69247
69248   if( p ){
69249     db = p->db;
69250     sqlite3_mutex_enter(db->mutex);
69251     rc = sqlite3_finalize(p->pStmt);
69252     sqlite3DbFree(db, p);
69253     sqlite3_mutex_leave(db->mutex);
69254   }else{
69255     rc = SQLITE_OK;
69256   }
69257   return rc;
69258 }
69259
69260 /*
69261 ** Perform a read or write operation on a blob
69262 */
69263 static int blobReadWrite(
69264   sqlite3_blob *pBlob, 
69265   void *z, 
69266   int n, 
69267   int iOffset, 
69268   int (*xCall)(BtCursor*, u32, u32, void*)
69269 ){
69270   int rc;
69271   Incrblob *p = (Incrblob *)pBlob;
69272   Vdbe *v;
69273   sqlite3 *db;
69274
69275   if( p==0 ) return SQLITE_MISUSE_BKPT;
69276   db = p->db;
69277   sqlite3_mutex_enter(db->mutex);
69278   v = (Vdbe*)p->pStmt;
69279
69280   if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
69281     /* Request is out of range. Return a transient error. */
69282     rc = SQLITE_ERROR;
69283     sqlite3Error(db, SQLITE_ERROR, 0);
69284   }else if( v==0 ){
69285     /* If there is no statement handle, then the blob-handle has
69286     ** already been invalidated. Return SQLITE_ABORT in this case.
69287     */
69288     rc = SQLITE_ABORT;
69289   }else{
69290     /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
69291     ** returned, clean-up the statement handle.
69292     */
69293     assert( db == v->db );
69294     sqlite3BtreeEnterCursor(p->pCsr);
69295     rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
69296     sqlite3BtreeLeaveCursor(p->pCsr);
69297     if( rc==SQLITE_ABORT ){
69298       sqlite3VdbeFinalize(v);
69299       p->pStmt = 0;
69300     }else{
69301       db->errCode = rc;
69302       v->rc = rc;
69303     }
69304   }
69305   rc = sqlite3ApiExit(db, rc);
69306   sqlite3_mutex_leave(db->mutex);
69307   return rc;
69308 }
69309
69310 /*
69311 ** Read data from a blob handle.
69312 */
69313 SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
69314   return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
69315 }
69316
69317 /*
69318 ** Write data to a blob handle.
69319 */
69320 SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
69321   return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
69322 }
69323
69324 /*
69325 ** Query a blob handle for the size of the data.
69326 **
69327 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
69328 ** so no mutex is required for access.
69329 */
69330 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
69331   Incrblob *p = (Incrblob *)pBlob;
69332   return (p && p->pStmt) ? p->nByte : 0;
69333 }
69334
69335 /*
69336 ** Move an existing blob handle to point to a different row of the same
69337 ** database table.
69338 **
69339 ** If an error occurs, or if the specified row does not exist or does not
69340 ** contain a blob or text value, then an error code is returned and the
69341 ** database handle error code and message set. If this happens, then all 
69342 ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close()) 
69343 ** immediately return SQLITE_ABORT.
69344 */
69345 SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
69346   int rc;
69347   Incrblob *p = (Incrblob *)pBlob;
69348   sqlite3 *db;
69349
69350   if( p==0 ) return SQLITE_MISUSE_BKPT;
69351   db = p->db;
69352   sqlite3_mutex_enter(db->mutex);
69353
69354   if( p->pStmt==0 ){
69355     /* If there is no statement handle, then the blob-handle has
69356     ** already been invalidated. Return SQLITE_ABORT in this case.
69357     */
69358     rc = SQLITE_ABORT;
69359   }else{
69360     char *zErr;
69361     rc = blobSeekToRow(p, iRow, &zErr);
69362     if( rc!=SQLITE_OK ){
69363       sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
69364       sqlite3DbFree(db, zErr);
69365     }
69366     assert( rc!=SQLITE_SCHEMA );
69367   }
69368
69369   rc = sqlite3ApiExit(db, rc);
69370   assert( rc==SQLITE_OK || p->pStmt==0 );
69371   sqlite3_mutex_leave(db->mutex);
69372   return rc;
69373 }
69374
69375 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
69376
69377 /************** End of vdbeblob.c ********************************************/
69378 /************** Begin file journal.c *****************************************/
69379 /*
69380 ** 2007 August 22
69381 **
69382 ** The author disclaims copyright to this source code.  In place of
69383 ** a legal notice, here is a blessing:
69384 **
69385 **    May you do good and not evil.
69386 **    May you find forgiveness for yourself and forgive others.
69387 **    May you share freely, never taking more than you give.
69388 **
69389 *************************************************************************
69390 **
69391 ** This file implements a special kind of sqlite3_file object used
69392 ** by SQLite to create journal files if the atomic-write optimization
69393 ** is enabled.
69394 **
69395 ** The distinctive characteristic of this sqlite3_file is that the
69396 ** actual on disk file is created lazily. When the file is created,
69397 ** the caller specifies a buffer size for an in-memory buffer to
69398 ** be used to service read() and write() requests. The actual file
69399 ** on disk is not created or populated until either:
69400 **
69401 **   1) The in-memory representation grows too large for the allocated 
69402 **      buffer, or
69403 **   2) The sqlite3JournalCreate() function is called.
69404 */
69405 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
69406
69407
69408 /*
69409 ** A JournalFile object is a subclass of sqlite3_file used by
69410 ** as an open file handle for journal files.
69411 */
69412 struct JournalFile {
69413   sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
69414   int nBuf;                       /* Size of zBuf[] in bytes */
69415   char *zBuf;                     /* Space to buffer journal writes */
69416   int iSize;                      /* Amount of zBuf[] currently used */
69417   int flags;                      /* xOpen flags */
69418   sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
69419   sqlite3_file *pReal;            /* The "real" underlying file descriptor */
69420   const char *zJournal;           /* Name of the journal file */
69421 };
69422 typedef struct JournalFile JournalFile;
69423
69424 /*
69425 ** If it does not already exists, create and populate the on-disk file 
69426 ** for JournalFile p.
69427 */
69428 static int createFile(JournalFile *p){
69429   int rc = SQLITE_OK;
69430   if( !p->pReal ){
69431     sqlite3_file *pReal = (sqlite3_file *)&p[1];
69432     rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
69433     if( rc==SQLITE_OK ){
69434       p->pReal = pReal;
69435       if( p->iSize>0 ){
69436         assert(p->iSize<=p->nBuf);
69437         rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
69438       }
69439     }
69440   }
69441   return rc;
69442 }
69443
69444 /*
69445 ** Close the file.
69446 */
69447 static int jrnlClose(sqlite3_file *pJfd){
69448   JournalFile *p = (JournalFile *)pJfd;
69449   if( p->pReal ){
69450     sqlite3OsClose(p->pReal);
69451   }
69452   sqlite3_free(p->zBuf);
69453   return SQLITE_OK;
69454 }
69455
69456 /*
69457 ** Read data from the file.
69458 */
69459 static int jrnlRead(
69460   sqlite3_file *pJfd,    /* The journal file from which to read */
69461   void *zBuf,            /* Put the results here */
69462   int iAmt,              /* Number of bytes to read */
69463   sqlite_int64 iOfst     /* Begin reading at this offset */
69464 ){
69465   int rc = SQLITE_OK;
69466   JournalFile *p = (JournalFile *)pJfd;
69467   if( p->pReal ){
69468     rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
69469   }else if( (iAmt+iOfst)>p->iSize ){
69470     rc = SQLITE_IOERR_SHORT_READ;
69471   }else{
69472     memcpy(zBuf, &p->zBuf[iOfst], iAmt);
69473   }
69474   return rc;
69475 }
69476
69477 /*
69478 ** Write data to the file.
69479 */
69480 static int jrnlWrite(
69481   sqlite3_file *pJfd,    /* The journal file into which to write */
69482   const void *zBuf,      /* Take data to be written from here */
69483   int iAmt,              /* Number of bytes to write */
69484   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
69485 ){
69486   int rc = SQLITE_OK;
69487   JournalFile *p = (JournalFile *)pJfd;
69488   if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
69489     rc = createFile(p);
69490   }
69491   if( rc==SQLITE_OK ){
69492     if( p->pReal ){
69493       rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
69494     }else{
69495       memcpy(&p->zBuf[iOfst], zBuf, iAmt);
69496       if( p->iSize<(iOfst+iAmt) ){
69497         p->iSize = (iOfst+iAmt);
69498       }
69499     }
69500   }
69501   return rc;
69502 }
69503
69504 /*
69505 ** Truncate the file.
69506 */
69507 static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
69508   int rc = SQLITE_OK;
69509   JournalFile *p = (JournalFile *)pJfd;
69510   if( p->pReal ){
69511     rc = sqlite3OsTruncate(p->pReal, size);
69512   }else if( size<p->iSize ){
69513     p->iSize = size;
69514   }
69515   return rc;
69516 }
69517
69518 /*
69519 ** Sync the file.
69520 */
69521 static int jrnlSync(sqlite3_file *pJfd, int flags){
69522   int rc;
69523   JournalFile *p = (JournalFile *)pJfd;
69524   if( p->pReal ){
69525     rc = sqlite3OsSync(p->pReal, flags);
69526   }else{
69527     rc = SQLITE_OK;
69528   }
69529   return rc;
69530 }
69531
69532 /*
69533 ** Query the size of the file in bytes.
69534 */
69535 static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
69536   int rc = SQLITE_OK;
69537   JournalFile *p = (JournalFile *)pJfd;
69538   if( p->pReal ){
69539     rc = sqlite3OsFileSize(p->pReal, pSize);
69540   }else{
69541     *pSize = (sqlite_int64) p->iSize;
69542   }
69543   return rc;
69544 }
69545
69546 /*
69547 ** Table of methods for JournalFile sqlite3_file object.
69548 */
69549 static struct sqlite3_io_methods JournalFileMethods = {
69550   1,             /* iVersion */
69551   jrnlClose,     /* xClose */
69552   jrnlRead,      /* xRead */
69553   jrnlWrite,     /* xWrite */
69554   jrnlTruncate,  /* xTruncate */
69555   jrnlSync,      /* xSync */
69556   jrnlFileSize,  /* xFileSize */
69557   0,             /* xLock */
69558   0,             /* xUnlock */
69559   0,             /* xCheckReservedLock */
69560   0,             /* xFileControl */
69561   0,             /* xSectorSize */
69562   0,             /* xDeviceCharacteristics */
69563   0,             /* xShmMap */
69564   0,             /* xShmLock */
69565   0,             /* xShmBarrier */
69566   0              /* xShmUnmap */
69567 };
69568
69569 /* 
69570 ** Open a journal file.
69571 */
69572 SQLITE_PRIVATE int sqlite3JournalOpen(
69573   sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
69574   const char *zName,         /* Name of the journal file */
69575   sqlite3_file *pJfd,        /* Preallocated, blank file handle */
69576   int flags,                 /* Opening flags */
69577   int nBuf                   /* Bytes buffered before opening the file */
69578 ){
69579   JournalFile *p = (JournalFile *)pJfd;
69580   memset(p, 0, sqlite3JournalSize(pVfs));
69581   if( nBuf>0 ){
69582     p->zBuf = sqlite3MallocZero(nBuf);
69583     if( !p->zBuf ){
69584       return SQLITE_NOMEM;
69585     }
69586   }else{
69587     return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
69588   }
69589   p->pMethod = &JournalFileMethods;
69590   p->nBuf = nBuf;
69591   p->flags = flags;
69592   p->zJournal = zName;
69593   p->pVfs = pVfs;
69594   return SQLITE_OK;
69595 }
69596
69597 /*
69598 ** If the argument p points to a JournalFile structure, and the underlying
69599 ** file has not yet been created, create it now.
69600 */
69601 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
69602   if( p->pMethods!=&JournalFileMethods ){
69603     return SQLITE_OK;
69604   }
69605   return createFile((JournalFile *)p);
69606 }
69607
69608 /* 
69609 ** Return the number of bytes required to store a JournalFile that uses vfs
69610 ** pVfs to create the underlying on-disk files.
69611 */
69612 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
69613   return (pVfs->szOsFile+sizeof(JournalFile));
69614 }
69615 #endif
69616
69617 /************** End of journal.c *********************************************/
69618 /************** Begin file memjournal.c **************************************/
69619 /*
69620 ** 2008 October 7
69621 **
69622 ** The author disclaims copyright to this source code.  In place of
69623 ** a legal notice, here is a blessing:
69624 **
69625 **    May you do good and not evil.
69626 **    May you find forgiveness for yourself and forgive others.
69627 **    May you share freely, never taking more than you give.
69628 **
69629 *************************************************************************
69630 **
69631 ** This file contains code use to implement an in-memory rollback journal.
69632 ** The in-memory rollback journal is used to journal transactions for
69633 ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
69634 */
69635
69636 /* Forward references to internal structures */
69637 typedef struct MemJournal MemJournal;
69638 typedef struct FilePoint FilePoint;
69639 typedef struct FileChunk FileChunk;
69640
69641 /* Space to hold the rollback journal is allocated in increments of
69642 ** this many bytes.
69643 **
69644 ** The size chosen is a little less than a power of two.  That way,
69645 ** the FileChunk object will have a size that almost exactly fills
69646 ** a power-of-two allocation.  This mimimizes wasted space in power-of-two
69647 ** memory allocators.
69648 */
69649 #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
69650
69651 /* Macro to find the minimum of two numeric values.
69652 */
69653 #ifndef MIN
69654 # define MIN(x,y) ((x)<(y)?(x):(y))
69655 #endif
69656
69657 /*
69658 ** The rollback journal is composed of a linked list of these structures.
69659 */
69660 struct FileChunk {
69661   FileChunk *pNext;               /* Next chunk in the journal */
69662   u8 zChunk[JOURNAL_CHUNKSIZE];   /* Content of this chunk */
69663 };
69664
69665 /*
69666 ** An instance of this object serves as a cursor into the rollback journal.
69667 ** The cursor can be either for reading or writing.
69668 */
69669 struct FilePoint {
69670   sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
69671   FileChunk *pChunk;              /* Specific chunk into which cursor points */
69672 };
69673
69674 /*
69675 ** This subclass is a subclass of sqlite3_file.  Each open memory-journal
69676 ** is an instance of this class.
69677 */
69678 struct MemJournal {
69679   sqlite3_io_methods *pMethod;    /* Parent class. MUST BE FIRST */
69680   FileChunk *pFirst;              /* Head of in-memory chunk-list */
69681   FilePoint endpoint;             /* Pointer to the end of the file */
69682   FilePoint readpoint;            /* Pointer to the end of the last xRead() */
69683 };
69684
69685 /*
69686 ** Read data from the in-memory journal file.  This is the implementation
69687 ** of the sqlite3_vfs.xRead method.
69688 */
69689 static int memjrnlRead(
69690   sqlite3_file *pJfd,    /* The journal file from which to read */
69691   void *zBuf,            /* Put the results here */
69692   int iAmt,              /* Number of bytes to read */
69693   sqlite_int64 iOfst     /* Begin reading at this offset */
69694 ){
69695   MemJournal *p = (MemJournal *)pJfd;
69696   u8 *zOut = zBuf;
69697   int nRead = iAmt;
69698   int iChunkOffset;
69699   FileChunk *pChunk;
69700
69701   /* SQLite never tries to read past the end of a rollback journal file */
69702   assert( iOfst+iAmt<=p->endpoint.iOffset );
69703
69704   if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
69705     sqlite3_int64 iOff = 0;
69706     for(pChunk=p->pFirst; 
69707         ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
69708         pChunk=pChunk->pNext
69709     ){
69710       iOff += JOURNAL_CHUNKSIZE;
69711     }
69712   }else{
69713     pChunk = p->readpoint.pChunk;
69714   }
69715
69716   iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
69717   do {
69718     int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
69719     int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
69720     memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
69721     zOut += nCopy;
69722     nRead -= iSpace;
69723     iChunkOffset = 0;
69724   } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
69725   p->readpoint.iOffset = iOfst+iAmt;
69726   p->readpoint.pChunk = pChunk;
69727
69728   return SQLITE_OK;
69729 }
69730
69731 /*
69732 ** Write data to the file.
69733 */
69734 static int memjrnlWrite(
69735   sqlite3_file *pJfd,    /* The journal file into which to write */
69736   const void *zBuf,      /* Take data to be written from here */
69737   int iAmt,              /* Number of bytes to write */
69738   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
69739 ){
69740   MemJournal *p = (MemJournal *)pJfd;
69741   int nWrite = iAmt;
69742   u8 *zWrite = (u8 *)zBuf;
69743
69744   /* An in-memory journal file should only ever be appended to. Random
69745   ** access writes are not required by sqlite.
69746   */
69747   assert( iOfst==p->endpoint.iOffset );
69748   UNUSED_PARAMETER(iOfst);
69749
69750   while( nWrite>0 ){
69751     FileChunk *pChunk = p->endpoint.pChunk;
69752     int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
69753     int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
69754
69755     if( iChunkOffset==0 ){
69756       /* New chunk is required to extend the file. */
69757       FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
69758       if( !pNew ){
69759         return SQLITE_IOERR_NOMEM;
69760       }
69761       pNew->pNext = 0;
69762       if( pChunk ){
69763         assert( p->pFirst );
69764         pChunk->pNext = pNew;
69765       }else{
69766         assert( !p->pFirst );
69767         p->pFirst = pNew;
69768       }
69769       p->endpoint.pChunk = pNew;
69770     }
69771
69772     memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
69773     zWrite += iSpace;
69774     nWrite -= iSpace;
69775     p->endpoint.iOffset += iSpace;
69776   }
69777
69778   return SQLITE_OK;
69779 }
69780
69781 /*
69782 ** Truncate the file.
69783 */
69784 static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
69785   MemJournal *p = (MemJournal *)pJfd;
69786   FileChunk *pChunk;
69787   assert(size==0);
69788   UNUSED_PARAMETER(size);
69789   pChunk = p->pFirst;
69790   while( pChunk ){
69791     FileChunk *pTmp = pChunk;
69792     pChunk = pChunk->pNext;
69793     sqlite3_free(pTmp);
69794   }
69795   sqlite3MemJournalOpen(pJfd);
69796   return SQLITE_OK;
69797 }
69798
69799 /*
69800 ** Close the file.
69801 */
69802 static int memjrnlClose(sqlite3_file *pJfd){
69803   memjrnlTruncate(pJfd, 0);
69804   return SQLITE_OK;
69805 }
69806
69807
69808 /*
69809 ** Sync the file.
69810 **
69811 ** Syncing an in-memory journal is a no-op.  And, in fact, this routine
69812 ** is never called in a working implementation.  This implementation
69813 ** exists purely as a contingency, in case some malfunction in some other
69814 ** part of SQLite causes Sync to be called by mistake.
69815 */
69816 static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
69817   UNUSED_PARAMETER2(NotUsed, NotUsed2);
69818   return SQLITE_OK;
69819 }
69820
69821 /*
69822 ** Query the size of the file in bytes.
69823 */
69824 static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
69825   MemJournal *p = (MemJournal *)pJfd;
69826   *pSize = (sqlite_int64) p->endpoint.iOffset;
69827   return SQLITE_OK;
69828 }
69829
69830 /*
69831 ** Table of methods for MemJournal sqlite3_file object.
69832 */
69833 static const struct sqlite3_io_methods MemJournalMethods = {
69834   1,                /* iVersion */
69835   memjrnlClose,     /* xClose */
69836   memjrnlRead,      /* xRead */
69837   memjrnlWrite,     /* xWrite */
69838   memjrnlTruncate,  /* xTruncate */
69839   memjrnlSync,      /* xSync */
69840   memjrnlFileSize,  /* xFileSize */
69841   0,                /* xLock */
69842   0,                /* xUnlock */
69843   0,                /* xCheckReservedLock */
69844   0,                /* xFileControl */
69845   0,                /* xSectorSize */
69846   0,                /* xDeviceCharacteristics */
69847   0,                /* xShmMap */
69848   0,                /* xShmLock */
69849   0,                /* xShmBarrier */
69850   0                 /* xShmUnlock */
69851 };
69852
69853 /* 
69854 ** Open a journal file.
69855 */
69856 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
69857   MemJournal *p = (MemJournal *)pJfd;
69858   assert( EIGHT_BYTE_ALIGNMENT(p) );
69859   memset(p, 0, sqlite3MemJournalSize());
69860   p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
69861 }
69862
69863 /*
69864 ** Return true if the file-handle passed as an argument is 
69865 ** an in-memory journal 
69866 */
69867 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
69868   return pJfd->pMethods==&MemJournalMethods;
69869 }
69870
69871 /* 
69872 ** Return the number of bytes required to store a MemJournal file descriptor.
69873 */
69874 SQLITE_PRIVATE int sqlite3MemJournalSize(void){
69875   return sizeof(MemJournal);
69876 }
69877
69878 /************** End of memjournal.c ******************************************/
69879 /************** Begin file walker.c ******************************************/
69880 /*
69881 ** 2008 August 16
69882 **
69883 ** The author disclaims copyright to this source code.  In place of
69884 ** a legal notice, here is a blessing:
69885 **
69886 **    May you do good and not evil.
69887 **    May you find forgiveness for yourself and forgive others.
69888 **    May you share freely, never taking more than you give.
69889 **
69890 *************************************************************************
69891 ** This file contains routines used for walking the parser tree for
69892 ** an SQL statement.
69893 */
69894
69895
69896 /*
69897 ** Walk an expression tree.  Invoke the callback once for each node
69898 ** of the expression, while decending.  (In other words, the callback
69899 ** is invoked before visiting children.)
69900 **
69901 ** The return value from the callback should be one of the WRC_*
69902 ** constants to specify how to proceed with the walk.
69903 **
69904 **    WRC_Continue      Continue descending down the tree.
69905 **
69906 **    WRC_Prune         Do not descend into child nodes.  But allow
69907 **                      the walk to continue with sibling nodes.
69908 **
69909 **    WRC_Abort         Do no more callbacks.  Unwind the stack and
69910 **                      return the top-level walk call.
69911 **
69912 ** The return value from this routine is WRC_Abort to abandon the tree walk
69913 ** and WRC_Continue to continue.
69914 */
69915 SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
69916   int rc;
69917   if( pExpr==0 ) return WRC_Continue;
69918   testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
69919   testcase( ExprHasProperty(pExpr, EP_Reduced) );
69920   rc = pWalker->xExprCallback(pWalker, pExpr);
69921   if( rc==WRC_Continue
69922               && !ExprHasAnyProperty(pExpr,EP_TokenOnly) ){
69923     if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
69924     if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
69925     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
69926       if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
69927     }else{
69928       if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
69929     }
69930   }
69931   return rc & WRC_Abort;
69932 }
69933
69934 /*
69935 ** Call sqlite3WalkExpr() for every expression in list p or until
69936 ** an abort request is seen.
69937 */
69938 SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
69939   int i;
69940   struct ExprList_item *pItem;
69941   if( p ){
69942     for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
69943       if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
69944     }
69945   }
69946   return WRC_Continue;
69947 }
69948
69949 /*
69950 ** Walk all expressions associated with SELECT statement p.  Do
69951 ** not invoke the SELECT callback on p, but do (of course) invoke
69952 ** any expr callbacks and SELECT callbacks that come from subqueries.
69953 ** Return WRC_Abort or WRC_Continue.
69954 */
69955 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
69956   if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
69957   if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
69958   if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
69959   if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
69960   if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
69961   if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
69962   if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
69963   return WRC_Continue;
69964 }
69965
69966 /*
69967 ** Walk the parse trees associated with all subqueries in the
69968 ** FROM clause of SELECT statement p.  Do not invoke the select
69969 ** callback on p, but do invoke it on each FROM clause subquery
69970 ** and on any subqueries further down in the tree.  Return 
69971 ** WRC_Abort or WRC_Continue;
69972 */
69973 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
69974   SrcList *pSrc;
69975   int i;
69976   struct SrcList_item *pItem;
69977
69978   pSrc = p->pSrc;
69979   if( ALWAYS(pSrc) ){
69980     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
69981       if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
69982         return WRC_Abort;
69983       }
69984     }
69985   }
69986   return WRC_Continue;
69987
69988
69989 /*
69990 ** Call sqlite3WalkExpr() for every expression in Select statement p.
69991 ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
69992 ** on the compound select chain, p->pPrior.
69993 **
69994 ** Return WRC_Continue under normal conditions.  Return WRC_Abort if
69995 ** there is an abort request.
69996 **
69997 ** If the Walker does not have an xSelectCallback() then this routine
69998 ** is a no-op returning WRC_Continue.
69999 */
70000 SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
70001   int rc;
70002   if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
70003   rc = WRC_Continue;
70004   while( p  ){
70005     rc = pWalker->xSelectCallback(pWalker, p);
70006     if( rc ) break;
70007     if( sqlite3WalkSelectExpr(pWalker, p) ) return WRC_Abort;
70008     if( sqlite3WalkSelectFrom(pWalker, p) ) return WRC_Abort;
70009     p = p->pPrior;
70010   }
70011   return rc & WRC_Abort;
70012 }
70013
70014 /************** End of walker.c **********************************************/
70015 /************** Begin file resolve.c *****************************************/
70016 /*
70017 ** 2008 August 18
70018 **
70019 ** The author disclaims copyright to this source code.  In place of
70020 ** a legal notice, here is a blessing:
70021 **
70022 **    May you do good and not evil.
70023 **    May you find forgiveness for yourself and forgive others.
70024 **    May you share freely, never taking more than you give.
70025 **
70026 *************************************************************************
70027 **
70028 ** This file contains routines used for walking the parser tree and
70029 ** resolve all identifiers by associating them with a particular
70030 ** table and column.
70031 */
70032
70033 /*
70034 ** Turn the pExpr expression into an alias for the iCol-th column of the
70035 ** result set in pEList.
70036 **
70037 ** If the result set column is a simple column reference, then this routine
70038 ** makes an exact copy.  But for any other kind of expression, this
70039 ** routine make a copy of the result set column as the argument to the
70040 ** TK_AS operator.  The TK_AS operator causes the expression to be
70041 ** evaluated just once and then reused for each alias.
70042 **
70043 ** The reason for suppressing the TK_AS term when the expression is a simple
70044 ** column reference is so that the column reference will be recognized as
70045 ** usable by indices within the WHERE clause processing logic. 
70046 **
70047 ** Hack:  The TK_AS operator is inhibited if zType[0]=='G'.  This means
70048 ** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
70049 **
70050 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
70051 **
70052 ** Is equivalent to:
70053 **
70054 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
70055 **
70056 ** The result of random()%5 in the GROUP BY clause is probably different
70057 ** from the result in the result-set.  We might fix this someday.  Or
70058 ** then again, we might not...
70059 */
70060 static void resolveAlias(
70061   Parse *pParse,         /* Parsing context */
70062   ExprList *pEList,      /* A result set */
70063   int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
70064   Expr *pExpr,           /* Transform this into an alias to the result set */
70065   const char *zType      /* "GROUP" or "ORDER" or "" */
70066 ){
70067   Expr *pOrig;           /* The iCol-th column of the result set */
70068   Expr *pDup;            /* Copy of pOrig */
70069   sqlite3 *db;           /* The database connection */
70070
70071   assert( iCol>=0 && iCol<pEList->nExpr );
70072   pOrig = pEList->a[iCol].pExpr;
70073   assert( pOrig!=0 );
70074   assert( pOrig->flags & EP_Resolved );
70075   db = pParse->db;
70076   if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
70077     pDup = sqlite3ExprDup(db, pOrig, 0);
70078     pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
70079     if( pDup==0 ) return;
70080     if( pEList->a[iCol].iAlias==0 ){
70081       pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
70082     }
70083     pDup->iTable = pEList->a[iCol].iAlias;
70084   }else if( ExprHasProperty(pOrig, EP_IntValue) || pOrig->u.zToken==0 ){
70085     pDup = sqlite3ExprDup(db, pOrig, 0);
70086     if( pDup==0 ) return;
70087   }else{
70088     char *zToken = pOrig->u.zToken;
70089     assert( zToken!=0 );
70090     pOrig->u.zToken = 0;
70091     pDup = sqlite3ExprDup(db, pOrig, 0);
70092     pOrig->u.zToken = zToken;
70093     if( pDup==0 ) return;
70094     assert( (pDup->flags & (EP_Reduced|EP_TokenOnly))==0 );
70095     pDup->flags2 |= EP2_MallocedToken;
70096     pDup->u.zToken = sqlite3DbStrDup(db, zToken);
70097   }
70098   if( pExpr->flags & EP_ExpCollate ){
70099     pDup->pColl = pExpr->pColl;
70100     pDup->flags |= EP_ExpCollate;
70101   }
70102
70103   /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This 
70104   ** prevents ExprDelete() from deleting the Expr structure itself,
70105   ** allowing it to be repopulated by the memcpy() on the following line.
70106   */
70107   ExprSetProperty(pExpr, EP_Static);
70108   sqlite3ExprDelete(db, pExpr);
70109   memcpy(pExpr, pDup, sizeof(*pExpr));
70110   sqlite3DbFree(db, pDup);
70111 }
70112
70113 /*
70114 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
70115 ** that name in the set of source tables in pSrcList and make the pExpr 
70116 ** expression node refer back to that source column.  The following changes
70117 ** are made to pExpr:
70118 **
70119 **    pExpr->iDb           Set the index in db->aDb[] of the database X
70120 **                         (even if X is implied).
70121 **    pExpr->iTable        Set to the cursor number for the table obtained
70122 **                         from pSrcList.
70123 **    pExpr->pTab          Points to the Table structure of X.Y (even if
70124 **                         X and/or Y are implied.)
70125 **    pExpr->iColumn       Set to the column number within the table.
70126 **    pExpr->op            Set to TK_COLUMN.
70127 **    pExpr->pLeft         Any expression this points to is deleted
70128 **    pExpr->pRight        Any expression this points to is deleted.
70129 **
70130 ** The zDb variable is the name of the database (the "X").  This value may be
70131 ** NULL meaning that name is of the form Y.Z or Z.  Any available database
70132 ** can be used.  The zTable variable is the name of the table (the "Y").  This
70133 ** value can be NULL if zDb is also NULL.  If zTable is NULL it
70134 ** means that the form of the name is Z and that columns from any table
70135 ** can be used.
70136 **
70137 ** If the name cannot be resolved unambiguously, leave an error message
70138 ** in pParse and return WRC_Abort.  Return WRC_Prune on success.
70139 */
70140 static int lookupName(
70141   Parse *pParse,       /* The parsing context */
70142   const char *zDb,     /* Name of the database containing table, or NULL */
70143   const char *zTab,    /* Name of table containing column, or NULL */
70144   const char *zCol,    /* Name of the column. */
70145   NameContext *pNC,    /* The name context used to resolve the name */
70146   Expr *pExpr          /* Make this EXPR node point to the selected column */
70147 ){
70148   int i, j;            /* Loop counters */
70149   int cnt = 0;                      /* Number of matching column names */
70150   int cntTab = 0;                   /* Number of matching table names */
70151   sqlite3 *db = pParse->db;         /* The database connection */
70152   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
70153   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
70154   NameContext *pTopNC = pNC;        /* First namecontext in the list */
70155   Schema *pSchema = 0;              /* Schema of the expression */
70156   int isTrigger = 0;
70157
70158   assert( pNC );     /* the name context cannot be NULL. */
70159   assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
70160   assert( ~ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
70161
70162   /* Initialize the node to no-match */
70163   pExpr->iTable = -1;
70164   pExpr->pTab = 0;
70165   ExprSetIrreducible(pExpr);
70166
70167   /* Start at the inner-most context and move outward until a match is found */
70168   while( pNC && cnt==0 ){
70169     ExprList *pEList;
70170     SrcList *pSrcList = pNC->pSrcList;
70171
70172     if( pSrcList ){
70173       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
70174         Table *pTab;
70175         int iDb;
70176         Column *pCol;
70177   
70178         pTab = pItem->pTab;
70179         assert( pTab!=0 && pTab->zName!=0 );
70180         iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
70181         assert( pTab->nCol>0 );
70182         if( zTab ){
70183           if( pItem->zAlias ){
70184             char *zTabName = pItem->zAlias;
70185             if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
70186           }else{
70187             char *zTabName = pTab->zName;
70188             if( NEVER(zTabName==0) || sqlite3StrICmp(zTabName, zTab)!=0 ){
70189               continue;
70190             }
70191             if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
70192               continue;
70193             }
70194           }
70195         }
70196         if( 0==(cntTab++) ){
70197           pExpr->iTable = pItem->iCursor;
70198           pExpr->pTab = pTab;
70199           pSchema = pTab->pSchema;
70200           pMatch = pItem;
70201         }
70202         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
70203           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
70204             IdList *pUsing;
70205             cnt++;
70206             pExpr->iTable = pItem->iCursor;
70207             pExpr->pTab = pTab;
70208             pMatch = pItem;
70209             pSchema = pTab->pSchema;
70210             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
70211             pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
70212             if( i<pSrcList->nSrc-1 ){
70213               if( pItem[1].jointype & JT_NATURAL ){
70214                 /* If this match occurred in the left table of a natural join,
70215                 ** then skip the right table to avoid a duplicate match */
70216                 pItem++;
70217                 i++;
70218               }else if( (pUsing = pItem[1].pUsing)!=0 ){
70219                 /* If this match occurs on a column that is in the USING clause
70220                 ** of a join, skip the search of the right table of the join
70221                 ** to avoid a duplicate match there. */
70222                 int k;
70223                 for(k=0; k<pUsing->nId; k++){
70224                   if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
70225                     pItem++;
70226                     i++;
70227                     break;
70228                   }
70229                 }
70230               }
70231             }
70232             break;
70233           }
70234         }
70235       }
70236     }
70237
70238 #ifndef SQLITE_OMIT_TRIGGER
70239     /* If we have not already resolved the name, then maybe 
70240     ** it is a new.* or old.* trigger argument reference
70241     */
70242     if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
70243       int op = pParse->eTriggerOp;
70244       Table *pTab = 0;
70245       assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
70246       if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
70247         pExpr->iTable = 1;
70248         pTab = pParse->pTriggerTab;
70249       }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
70250         pExpr->iTable = 0;
70251         pTab = pParse->pTriggerTab;
70252       }
70253
70254       if( pTab ){ 
70255         int iCol;
70256         pSchema = pTab->pSchema;
70257         cntTab++;
70258         for(iCol=0; iCol<pTab->nCol; iCol++){
70259           Column *pCol = &pTab->aCol[iCol];
70260           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
70261             if( iCol==pTab->iPKey ){
70262               iCol = -1;
70263             }
70264             break;
70265           }
70266         }
70267         if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
70268           iCol = -1;        /* IMP: R-44911-55124 */
70269         }
70270         if( iCol<pTab->nCol ){
70271           cnt++;
70272           if( iCol<0 ){
70273             pExpr->affinity = SQLITE_AFF_INTEGER;
70274           }else if( pExpr->iTable==0 ){
70275             testcase( iCol==31 );
70276             testcase( iCol==32 );
70277             pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
70278           }else{
70279             testcase( iCol==31 );
70280             testcase( iCol==32 );
70281             pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
70282           }
70283           pExpr->iColumn = (i16)iCol;
70284           pExpr->pTab = pTab;
70285           isTrigger = 1;
70286         }
70287       }
70288     }
70289 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
70290
70291     /*
70292     ** Perhaps the name is a reference to the ROWID
70293     */
70294     if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
70295       cnt = 1;
70296       pExpr->iColumn = -1;     /* IMP: R-44911-55124 */
70297       pExpr->affinity = SQLITE_AFF_INTEGER;
70298     }
70299
70300     /*
70301     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
70302     ** might refer to an result-set alias.  This happens, for example, when
70303     ** we are resolving names in the WHERE clause of the following command:
70304     **
70305     **     SELECT a+b AS x FROM table WHERE x<10;
70306     **
70307     ** In cases like this, replace pExpr with a copy of the expression that
70308     ** forms the result set entry ("a+b" in the example) and return immediately.
70309     ** Note that the expression in the result set should have already been
70310     ** resolved by the time the WHERE clause is resolved.
70311     */
70312     if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
70313       for(j=0; j<pEList->nExpr; j++){
70314         char *zAs = pEList->a[j].zName;
70315         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
70316           Expr *pOrig;
70317           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
70318           assert( pExpr->x.pList==0 );
70319           assert( pExpr->x.pSelect==0 );
70320           pOrig = pEList->a[j].pExpr;
70321           if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
70322             sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
70323             return WRC_Abort;
70324           }
70325           resolveAlias(pParse, pEList, j, pExpr, "");
70326           cnt = 1;
70327           pMatch = 0;
70328           assert( zTab==0 && zDb==0 );
70329           goto lookupname_end;
70330         }
70331       } 
70332     }
70333
70334     /* Advance to the next name context.  The loop will exit when either
70335     ** we have a match (cnt>0) or when we run out of name contexts.
70336     */
70337     if( cnt==0 ){
70338       pNC = pNC->pNext;
70339     }
70340   }
70341
70342   /*
70343   ** If X and Y are NULL (in other words if only the column name Z is
70344   ** supplied) and the value of Z is enclosed in double-quotes, then
70345   ** Z is a string literal if it doesn't match any column names.  In that
70346   ** case, we need to return right away and not make any changes to
70347   ** pExpr.
70348   **
70349   ** Because no reference was made to outer contexts, the pNC->nRef
70350   ** fields are not changed in any context.
70351   */
70352   if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
70353     pExpr->op = TK_STRING;
70354     pExpr->pTab = 0;
70355     return WRC_Prune;
70356   }
70357
70358   /*
70359   ** cnt==0 means there was not match.  cnt>1 means there were two or
70360   ** more matches.  Either way, we have an error.
70361   */
70362   if( cnt!=1 ){
70363     const char *zErr;
70364     zErr = cnt==0 ? "no such column" : "ambiguous column name";
70365     if( zDb ){
70366       sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
70367     }else if( zTab ){
70368       sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
70369     }else{
70370       sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
70371     }
70372     pParse->checkSchema = 1;
70373     pTopNC->nErr++;
70374   }
70375
70376   /* If a column from a table in pSrcList is referenced, then record
70377   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
70378   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
70379   ** column number is greater than the number of bits in the bitmask
70380   ** then set the high-order bit of the bitmask.
70381   */
70382   if( pExpr->iColumn>=0 && pMatch!=0 ){
70383     int n = pExpr->iColumn;
70384     testcase( n==BMS-1 );
70385     if( n>=BMS ){
70386       n = BMS-1;
70387     }
70388     assert( pMatch->iCursor==pExpr->iTable );
70389     pMatch->colUsed |= ((Bitmask)1)<<n;
70390   }
70391
70392   /* Clean up and return
70393   */
70394   sqlite3ExprDelete(db, pExpr->pLeft);
70395   pExpr->pLeft = 0;
70396   sqlite3ExprDelete(db, pExpr->pRight);
70397   pExpr->pRight = 0;
70398   pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
70399 lookupname_end:
70400   if( cnt==1 ){
70401     assert( pNC!=0 );
70402     sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
70403     /* Increment the nRef value on all name contexts from TopNC up to
70404     ** the point where the name matched. */
70405     for(;;){
70406       assert( pTopNC!=0 );
70407       pTopNC->nRef++;
70408       if( pTopNC==pNC ) break;
70409       pTopNC = pTopNC->pNext;
70410     }
70411     return WRC_Prune;
70412   } else {
70413     return WRC_Abort;
70414   }
70415 }
70416
70417 /*
70418 ** Allocate and return a pointer to an expression to load the column iCol
70419 ** from datasource iSrc in SrcList pSrc.
70420 */
70421 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
70422   Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
70423   if( p ){
70424     struct SrcList_item *pItem = &pSrc->a[iSrc];
70425     p->pTab = pItem->pTab;
70426     p->iTable = pItem->iCursor;
70427     if( p->pTab->iPKey==iCol ){
70428       p->iColumn = -1;
70429     }else{
70430       p->iColumn = (ynVar)iCol;
70431       testcase( iCol==BMS );
70432       testcase( iCol==BMS-1 );
70433       pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
70434     }
70435     ExprSetProperty(p, EP_Resolved);
70436   }
70437   return p;
70438 }
70439
70440 /*
70441 ** This routine is callback for sqlite3WalkExpr().
70442 **
70443 ** Resolve symbolic names into TK_COLUMN operators for the current
70444 ** node in the expression tree.  Return 0 to continue the search down
70445 ** the tree or 2 to abort the tree walk.
70446 **
70447 ** This routine also does error checking and name resolution for
70448 ** function names.  The operator for aggregate functions is changed
70449 ** to TK_AGG_FUNCTION.
70450 */
70451 static int resolveExprStep(Walker *pWalker, Expr *pExpr){
70452   NameContext *pNC;
70453   Parse *pParse;
70454
70455   pNC = pWalker->u.pNC;
70456   assert( pNC!=0 );
70457   pParse = pNC->pParse;
70458   assert( pParse==pWalker->pParse );
70459
70460   if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
70461   ExprSetProperty(pExpr, EP_Resolved);
70462 #ifndef NDEBUG
70463   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
70464     SrcList *pSrcList = pNC->pSrcList;
70465     int i;
70466     for(i=0; i<pNC->pSrcList->nSrc; i++){
70467       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
70468     }
70469   }
70470 #endif
70471   switch( pExpr->op ){
70472
70473 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
70474     /* The special operator TK_ROW means use the rowid for the first
70475     ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
70476     ** clause processing on UPDATE and DELETE statements.
70477     */
70478     case TK_ROW: {
70479       SrcList *pSrcList = pNC->pSrcList;
70480       struct SrcList_item *pItem;
70481       assert( pSrcList && pSrcList->nSrc==1 );
70482       pItem = pSrcList->a; 
70483       pExpr->op = TK_COLUMN;
70484       pExpr->pTab = pItem->pTab;
70485       pExpr->iTable = pItem->iCursor;
70486       pExpr->iColumn = -1;
70487       pExpr->affinity = SQLITE_AFF_INTEGER;
70488       break;
70489     }
70490 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
70491
70492     /* A lone identifier is the name of a column.
70493     */
70494     case TK_ID: {
70495       return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
70496     }
70497   
70498     /* A table name and column name:     ID.ID
70499     ** Or a database, table and column:  ID.ID.ID
70500     */
70501     case TK_DOT: {
70502       const char *zColumn;
70503       const char *zTable;
70504       const char *zDb;
70505       Expr *pRight;
70506
70507       /* if( pSrcList==0 ) break; */
70508       pRight = pExpr->pRight;
70509       if( pRight->op==TK_ID ){
70510         zDb = 0;
70511         zTable = pExpr->pLeft->u.zToken;
70512         zColumn = pRight->u.zToken;
70513       }else{
70514         assert( pRight->op==TK_DOT );
70515         zDb = pExpr->pLeft->u.zToken;
70516         zTable = pRight->pLeft->u.zToken;
70517         zColumn = pRight->pRight->u.zToken;
70518       }
70519       return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
70520     }
70521
70522     /* Resolve function names
70523     */
70524     case TK_CONST_FUNC:
70525     case TK_FUNCTION: {
70526       ExprList *pList = pExpr->x.pList;    /* The argument list */
70527       int n = pList ? pList->nExpr : 0;    /* Number of arguments */
70528       int no_such_func = 0;       /* True if no such function exists */
70529       int wrong_num_args = 0;     /* True if wrong number of arguments */
70530       int is_agg = 0;             /* True if is an aggregate function */
70531       int auth;                   /* Authorization to use the function */
70532       int nId;                    /* Number of characters in function name */
70533       const char *zId;            /* The function name. */
70534       FuncDef *pDef;              /* Information about the function */
70535       u8 enc = ENC(pParse->db);   /* The database encoding */
70536
70537       testcase( pExpr->op==TK_CONST_FUNC );
70538       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
70539       zId = pExpr->u.zToken;
70540       nId = sqlite3Strlen30(zId);
70541       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
70542       if( pDef==0 ){
70543         pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
70544         if( pDef==0 ){
70545           no_such_func = 1;
70546         }else{
70547           wrong_num_args = 1;
70548         }
70549       }else{
70550         is_agg = pDef->xFunc==0;
70551       }
70552 #ifndef SQLITE_OMIT_AUTHORIZATION
70553       if( pDef ){
70554         auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
70555         if( auth!=SQLITE_OK ){
70556           if( auth==SQLITE_DENY ){
70557             sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
70558                                     pDef->zName);
70559             pNC->nErr++;
70560           }
70561           pExpr->op = TK_NULL;
70562           return WRC_Prune;
70563         }
70564       }
70565 #endif
70566       if( is_agg && !pNC->allowAgg ){
70567         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
70568         pNC->nErr++;
70569         is_agg = 0;
70570       }else if( no_such_func ){
70571         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
70572         pNC->nErr++;
70573       }else if( wrong_num_args ){
70574         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
70575              nId, zId);
70576         pNC->nErr++;
70577       }
70578       if( is_agg ){
70579         pExpr->op = TK_AGG_FUNCTION;
70580         pNC->hasAgg = 1;
70581       }
70582       if( is_agg ) pNC->allowAgg = 0;
70583       sqlite3WalkExprList(pWalker, pList);
70584       if( is_agg ) pNC->allowAgg = 1;
70585       /* FIX ME:  Compute pExpr->affinity based on the expected return
70586       ** type of the function 
70587       */
70588       return WRC_Prune;
70589     }
70590 #ifndef SQLITE_OMIT_SUBQUERY
70591     case TK_SELECT:
70592     case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
70593 #endif
70594     case TK_IN: {
70595       testcase( pExpr->op==TK_IN );
70596       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
70597         int nRef = pNC->nRef;
70598 #ifndef SQLITE_OMIT_CHECK
70599         if( pNC->isCheck ){
70600           sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
70601         }
70602 #endif
70603         sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
70604         assert( pNC->nRef>=nRef );
70605         if( nRef!=pNC->nRef ){
70606           ExprSetProperty(pExpr, EP_VarSelect);
70607         }
70608       }
70609       break;
70610     }
70611 #ifndef SQLITE_OMIT_CHECK
70612     case TK_VARIABLE: {
70613       if( pNC->isCheck ){
70614         sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
70615       }
70616       break;
70617     }
70618 #endif
70619   }
70620   return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
70621 }
70622
70623 /*
70624 ** pEList is a list of expressions which are really the result set of the
70625 ** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
70626 ** This routine checks to see if pE is a simple identifier which corresponds
70627 ** to the AS-name of one of the terms of the expression list.  If it is,
70628 ** this routine return an integer between 1 and N where N is the number of
70629 ** elements in pEList, corresponding to the matching entry.  If there is
70630 ** no match, or if pE is not a simple identifier, then this routine
70631 ** return 0.
70632 **
70633 ** pEList has been resolved.  pE has not.
70634 */
70635 static int resolveAsName(
70636   Parse *pParse,     /* Parsing context for error messages */
70637   ExprList *pEList,  /* List of expressions to scan */
70638   Expr *pE           /* Expression we are trying to match */
70639 ){
70640   int i;             /* Loop counter */
70641
70642   UNUSED_PARAMETER(pParse);
70643
70644   if( pE->op==TK_ID ){
70645     char *zCol = pE->u.zToken;
70646     for(i=0; i<pEList->nExpr; i++){
70647       char *zAs = pEList->a[i].zName;
70648       if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
70649         return i+1;
70650       }
70651     }
70652   }
70653   return 0;
70654 }
70655
70656 /*
70657 ** pE is a pointer to an expression which is a single term in the
70658 ** ORDER BY of a compound SELECT.  The expression has not been
70659 ** name resolved.
70660 **
70661 ** At the point this routine is called, we already know that the
70662 ** ORDER BY term is not an integer index into the result set.  That
70663 ** case is handled by the calling routine.
70664 **
70665 ** Attempt to match pE against result set columns in the left-most
70666 ** SELECT statement.  Return the index i of the matching column,
70667 ** as an indication to the caller that it should sort by the i-th column.
70668 ** The left-most column is 1.  In other words, the value returned is the
70669 ** same integer value that would be used in the SQL statement to indicate
70670 ** the column.
70671 **
70672 ** If there is no match, return 0.  Return -1 if an error occurs.
70673 */
70674 static int resolveOrderByTermToExprList(
70675   Parse *pParse,     /* Parsing context for error messages */
70676   Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
70677   Expr *pE           /* The specific ORDER BY term */
70678 ){
70679   int i;             /* Loop counter */
70680   ExprList *pEList;  /* The columns of the result set */
70681   NameContext nc;    /* Name context for resolving pE */
70682   sqlite3 *db;       /* Database connection */
70683   int rc;            /* Return code from subprocedures */
70684   u8 savedSuppErr;   /* Saved value of db->suppressErr */
70685
70686   assert( sqlite3ExprIsInteger(pE, &i)==0 );
70687   pEList = pSelect->pEList;
70688
70689   /* Resolve all names in the ORDER BY term expression
70690   */
70691   memset(&nc, 0, sizeof(nc));
70692   nc.pParse = pParse;
70693   nc.pSrcList = pSelect->pSrc;
70694   nc.pEList = pEList;
70695   nc.allowAgg = 1;
70696   nc.nErr = 0;
70697   db = pParse->db;
70698   savedSuppErr = db->suppressErr;
70699   db->suppressErr = 1;
70700   rc = sqlite3ResolveExprNames(&nc, pE);
70701   db->suppressErr = savedSuppErr;
70702   if( rc ) return 0;
70703
70704   /* Try to match the ORDER BY expression against an expression
70705   ** in the result set.  Return an 1-based index of the matching
70706   ** result-set entry.
70707   */
70708   for(i=0; i<pEList->nExpr; i++){
70709     if( sqlite3ExprCompare(pEList->a[i].pExpr, pE)<2 ){
70710       return i+1;
70711     }
70712   }
70713
70714   /* If no match, return 0. */
70715   return 0;
70716 }
70717
70718 /*
70719 ** Generate an ORDER BY or GROUP BY term out-of-range error.
70720 */
70721 static void resolveOutOfRangeError(
70722   Parse *pParse,         /* The error context into which to write the error */
70723   const char *zType,     /* "ORDER" or "GROUP" */
70724   int i,                 /* The index (1-based) of the term out of range */
70725   int mx                 /* Largest permissible value of i */
70726 ){
70727   sqlite3ErrorMsg(pParse, 
70728     "%r %s BY term out of range - should be "
70729     "between 1 and %d", i, zType, mx);
70730 }
70731
70732 /*
70733 ** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
70734 ** each term of the ORDER BY clause is a constant integer between 1
70735 ** and N where N is the number of columns in the compound SELECT.
70736 **
70737 ** ORDER BY terms that are already an integer between 1 and N are
70738 ** unmodified.  ORDER BY terms that are integers outside the range of
70739 ** 1 through N generate an error.  ORDER BY terms that are expressions
70740 ** are matched against result set expressions of compound SELECT
70741 ** beginning with the left-most SELECT and working toward the right.
70742 ** At the first match, the ORDER BY expression is transformed into
70743 ** the integer column number.
70744 **
70745 ** Return the number of errors seen.
70746 */
70747 static int resolveCompoundOrderBy(
70748   Parse *pParse,        /* Parsing context.  Leave error messages here */
70749   Select *pSelect       /* The SELECT statement containing the ORDER BY */
70750 ){
70751   int i;
70752   ExprList *pOrderBy;
70753   ExprList *pEList;
70754   sqlite3 *db;
70755   int moreToDo = 1;
70756
70757   pOrderBy = pSelect->pOrderBy;
70758   if( pOrderBy==0 ) return 0;
70759   db = pParse->db;
70760 #if SQLITE_MAX_COLUMN
70761   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
70762     sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
70763     return 1;
70764   }
70765 #endif
70766   for(i=0; i<pOrderBy->nExpr; i++){
70767     pOrderBy->a[i].done = 0;
70768   }
70769   pSelect->pNext = 0;
70770   while( pSelect->pPrior ){
70771     pSelect->pPrior->pNext = pSelect;
70772     pSelect = pSelect->pPrior;
70773   }
70774   while( pSelect && moreToDo ){
70775     struct ExprList_item *pItem;
70776     moreToDo = 0;
70777     pEList = pSelect->pEList;
70778     assert( pEList!=0 );
70779     for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
70780       int iCol = -1;
70781       Expr *pE, *pDup;
70782       if( pItem->done ) continue;
70783       pE = pItem->pExpr;
70784       if( sqlite3ExprIsInteger(pE, &iCol) ){
70785         if( iCol<=0 || iCol>pEList->nExpr ){
70786           resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
70787           return 1;
70788         }
70789       }else{
70790         iCol = resolveAsName(pParse, pEList, pE);
70791         if( iCol==0 ){
70792           pDup = sqlite3ExprDup(db, pE, 0);
70793           if( !db->mallocFailed ){
70794             assert(pDup);
70795             iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
70796           }
70797           sqlite3ExprDelete(db, pDup);
70798         }
70799       }
70800       if( iCol>0 ){
70801         CollSeq *pColl = pE->pColl;
70802         int flags = pE->flags & EP_ExpCollate;
70803         sqlite3ExprDelete(db, pE);
70804         pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0);
70805         if( pE==0 ) return 1;
70806         pE->pColl = pColl;
70807         pE->flags |= EP_IntValue | flags;
70808         pE->u.iValue = iCol;
70809         pItem->iCol = (u16)iCol;
70810         pItem->done = 1;
70811       }else{
70812         moreToDo = 1;
70813       }
70814     }
70815     pSelect = pSelect->pNext;
70816   }
70817   for(i=0; i<pOrderBy->nExpr; i++){
70818     if( pOrderBy->a[i].done==0 ){
70819       sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
70820             "column in the result set", i+1);
70821       return 1;
70822     }
70823   }
70824   return 0;
70825 }
70826
70827 /*
70828 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
70829 ** the SELECT statement pSelect.  If any term is reference to a
70830 ** result set expression (as determined by the ExprList.a.iCol field)
70831 ** then convert that term into a copy of the corresponding result set
70832 ** column.
70833 **
70834 ** If any errors are detected, add an error message to pParse and
70835 ** return non-zero.  Return zero if no errors are seen.
70836 */
70837 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
70838   Parse *pParse,        /* Parsing context.  Leave error messages here */
70839   Select *pSelect,      /* The SELECT statement containing the clause */
70840   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
70841   const char *zType     /* "ORDER" or "GROUP" */
70842 ){
70843   int i;
70844   sqlite3 *db = pParse->db;
70845   ExprList *pEList;
70846   struct ExprList_item *pItem;
70847
70848   if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
70849 #if SQLITE_MAX_COLUMN
70850   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
70851     sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
70852     return 1;
70853   }
70854 #endif
70855   pEList = pSelect->pEList;
70856   assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
70857   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
70858     if( pItem->iCol ){
70859       if( pItem->iCol>pEList->nExpr ){
70860         resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
70861         return 1;
70862       }
70863       resolveAlias(pParse, pEList, pItem->iCol-1, pItem->pExpr, zType);
70864     }
70865   }
70866   return 0;
70867 }
70868
70869 /*
70870 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
70871 ** The Name context of the SELECT statement is pNC.  zType is either
70872 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
70873 **
70874 ** This routine resolves each term of the clause into an expression.
70875 ** If the order-by term is an integer I between 1 and N (where N is the
70876 ** number of columns in the result set of the SELECT) then the expression
70877 ** in the resolution is a copy of the I-th result-set expression.  If
70878 ** the order-by term is an identify that corresponds to the AS-name of
70879 ** a result-set expression, then the term resolves to a copy of the
70880 ** result-set expression.  Otherwise, the expression is resolved in
70881 ** the usual way - using sqlite3ResolveExprNames().
70882 **
70883 ** This routine returns the number of errors.  If errors occur, then
70884 ** an appropriate error message might be left in pParse.  (OOM errors
70885 ** excepted.)
70886 */
70887 static int resolveOrderGroupBy(
70888   NameContext *pNC,     /* The name context of the SELECT statement */
70889   Select *pSelect,      /* The SELECT statement holding pOrderBy */
70890   ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
70891   const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
70892 ){
70893   int i;                         /* Loop counter */
70894   int iCol;                      /* Column number */
70895   struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
70896   Parse *pParse;                 /* Parsing context */
70897   int nResult;                   /* Number of terms in the result set */
70898
70899   if( pOrderBy==0 ) return 0;
70900   nResult = pSelect->pEList->nExpr;
70901   pParse = pNC->pParse;
70902   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
70903     Expr *pE = pItem->pExpr;
70904     iCol = resolveAsName(pParse, pSelect->pEList, pE);
70905     if( iCol>0 ){
70906       /* If an AS-name match is found, mark this ORDER BY column as being
70907       ** a copy of the iCol-th result-set column.  The subsequent call to
70908       ** sqlite3ResolveOrderGroupBy() will convert the expression to a
70909       ** copy of the iCol-th result-set expression. */
70910       pItem->iCol = (u16)iCol;
70911       continue;
70912     }
70913     if( sqlite3ExprIsInteger(pE, &iCol) ){
70914       /* The ORDER BY term is an integer constant.  Again, set the column
70915       ** number so that sqlite3ResolveOrderGroupBy() will convert the
70916       ** order-by term to a copy of the result-set expression */
70917       if( iCol<1 ){
70918         resolveOutOfRangeError(pParse, zType, i+1, nResult);
70919         return 1;
70920       }
70921       pItem->iCol = (u16)iCol;
70922       continue;
70923     }
70924
70925     /* Otherwise, treat the ORDER BY term as an ordinary expression */
70926     pItem->iCol = 0;
70927     if( sqlite3ResolveExprNames(pNC, pE) ){
70928       return 1;
70929     }
70930   }
70931   return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
70932 }
70933
70934 /*
70935 ** Resolve names in the SELECT statement p and all of its descendents.
70936 */
70937 static int resolveSelectStep(Walker *pWalker, Select *p){
70938   NameContext *pOuterNC;  /* Context that contains this SELECT */
70939   NameContext sNC;        /* Name context of this SELECT */
70940   int isCompound;         /* True if p is a compound select */
70941   int nCompound;          /* Number of compound terms processed so far */
70942   Parse *pParse;          /* Parsing context */
70943   ExprList *pEList;       /* Result set expression list */
70944   int i;                  /* Loop counter */
70945   ExprList *pGroupBy;     /* The GROUP BY clause */
70946   Select *pLeftmost;      /* Left-most of SELECT of a compound */
70947   sqlite3 *db;            /* Database connection */
70948   
70949
70950   assert( p!=0 );
70951   if( p->selFlags & SF_Resolved ){
70952     return WRC_Prune;
70953   }
70954   pOuterNC = pWalker->u.pNC;
70955   pParse = pWalker->pParse;
70956   db = pParse->db;
70957
70958   /* Normally sqlite3SelectExpand() will be called first and will have
70959   ** already expanded this SELECT.  However, if this is a subquery within
70960   ** an expression, sqlite3ResolveExprNames() will be called without a
70961   ** prior call to sqlite3SelectExpand().  When that happens, let
70962   ** sqlite3SelectPrep() do all of the processing for this SELECT.
70963   ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
70964   ** this routine in the correct order.
70965   */
70966   if( (p->selFlags & SF_Expanded)==0 ){
70967     sqlite3SelectPrep(pParse, p, pOuterNC);
70968     return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
70969   }
70970
70971   isCompound = p->pPrior!=0;
70972   nCompound = 0;
70973   pLeftmost = p;
70974   while( p ){
70975     assert( (p->selFlags & SF_Expanded)!=0 );
70976     assert( (p->selFlags & SF_Resolved)==0 );
70977     p->selFlags |= SF_Resolved;
70978
70979     /* Resolve the expressions in the LIMIT and OFFSET clauses. These
70980     ** are not allowed to refer to any names, so pass an empty NameContext.
70981     */
70982     memset(&sNC, 0, sizeof(sNC));
70983     sNC.pParse = pParse;
70984     if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
70985         sqlite3ResolveExprNames(&sNC, p->pOffset) ){
70986       return WRC_Abort;
70987     }
70988   
70989     /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
70990     ** resolve the result-set expression list.
70991     */
70992     sNC.allowAgg = 1;
70993     sNC.pSrcList = p->pSrc;
70994     sNC.pNext = pOuterNC;
70995   
70996     /* Resolve names in the result set. */
70997     pEList = p->pEList;
70998     assert( pEList!=0 );
70999     for(i=0; i<pEList->nExpr; i++){
71000       Expr *pX = pEList->a[i].pExpr;
71001       if( sqlite3ResolveExprNames(&sNC, pX) ){
71002         return WRC_Abort;
71003       }
71004     }
71005   
71006     /* Recursively resolve names in all subqueries
71007     */
71008     for(i=0; i<p->pSrc->nSrc; i++){
71009       struct SrcList_item *pItem = &p->pSrc->a[i];
71010       if( pItem->pSelect ){
71011         const char *zSavedContext = pParse->zAuthContext;
71012         if( pItem->zName ) pParse->zAuthContext = pItem->zName;
71013         sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
71014         pParse->zAuthContext = zSavedContext;
71015         if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
71016       }
71017     }
71018   
71019     /* If there are no aggregate functions in the result-set, and no GROUP BY 
71020     ** expression, do not allow aggregates in any of the other expressions.
71021     */
71022     assert( (p->selFlags & SF_Aggregate)==0 );
71023     pGroupBy = p->pGroupBy;
71024     if( pGroupBy || sNC.hasAgg ){
71025       p->selFlags |= SF_Aggregate;
71026     }else{
71027       sNC.allowAgg = 0;
71028     }
71029   
71030     /* If a HAVING clause is present, then there must be a GROUP BY clause.
71031     */
71032     if( p->pHaving && !pGroupBy ){
71033       sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
71034       return WRC_Abort;
71035     }
71036   
71037     /* Add the expression list to the name-context before parsing the
71038     ** other expressions in the SELECT statement. This is so that
71039     ** expressions in the WHERE clause (etc.) can refer to expressions by
71040     ** aliases in the result set.
71041     **
71042     ** Minor point: If this is the case, then the expression will be
71043     ** re-evaluated for each reference to it.
71044     */
71045     sNC.pEList = p->pEList;
71046     if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
71047        sqlite3ResolveExprNames(&sNC, p->pHaving)
71048     ){
71049       return WRC_Abort;
71050     }
71051
71052     /* The ORDER BY and GROUP BY clauses may not refer to terms in
71053     ** outer queries 
71054     */
71055     sNC.pNext = 0;
71056     sNC.allowAgg = 1;
71057
71058     /* Process the ORDER BY clause for singleton SELECT statements.
71059     ** The ORDER BY clause for compounds SELECT statements is handled
71060     ** below, after all of the result-sets for all of the elements of
71061     ** the compound have been resolved.
71062     */
71063     if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
71064       return WRC_Abort;
71065     }
71066     if( db->mallocFailed ){
71067       return WRC_Abort;
71068     }
71069   
71070     /* Resolve the GROUP BY clause.  At the same time, make sure 
71071     ** the GROUP BY clause does not contain aggregate functions.
71072     */
71073     if( pGroupBy ){
71074       struct ExprList_item *pItem;
71075     
71076       if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
71077         return WRC_Abort;
71078       }
71079       for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
71080         if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
71081           sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
71082               "the GROUP BY clause");
71083           return WRC_Abort;
71084         }
71085       }
71086     }
71087
71088     /* Advance to the next term of the compound
71089     */
71090     p = p->pPrior;
71091     nCompound++;
71092   }
71093
71094   /* Resolve the ORDER BY on a compound SELECT after all terms of
71095   ** the compound have been resolved.
71096   */
71097   if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
71098     return WRC_Abort;
71099   }
71100
71101   return WRC_Prune;
71102 }
71103
71104 /*
71105 ** This routine walks an expression tree and resolves references to
71106 ** table columns and result-set columns.  At the same time, do error
71107 ** checking on function usage and set a flag if any aggregate functions
71108 ** are seen.
71109 **
71110 ** To resolve table columns references we look for nodes (or subtrees) of the 
71111 ** form X.Y.Z or Y.Z or just Z where
71112 **
71113 **      X:   The name of a database.  Ex:  "main" or "temp" or
71114 **           the symbolic name assigned to an ATTACH-ed database.
71115 **
71116 **      Y:   The name of a table in a FROM clause.  Or in a trigger
71117 **           one of the special names "old" or "new".
71118 **
71119 **      Z:   The name of a column in table Y.
71120 **
71121 ** The node at the root of the subtree is modified as follows:
71122 **
71123 **    Expr.op        Changed to TK_COLUMN
71124 **    Expr.pTab      Points to the Table object for X.Y
71125 **    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
71126 **    Expr.iTable    The VDBE cursor number for X.Y
71127 **
71128 **
71129 ** To resolve result-set references, look for expression nodes of the
71130 ** form Z (with no X and Y prefix) where the Z matches the right-hand
71131 ** size of an AS clause in the result-set of a SELECT.  The Z expression
71132 ** is replaced by a copy of the left-hand side of the result-set expression.
71133 ** Table-name and function resolution occurs on the substituted expression
71134 ** tree.  For example, in:
71135 **
71136 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
71137 **
71138 ** The "x" term of the order by is replaced by "a+b" to render:
71139 **
71140 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
71141 **
71142 ** Function calls are checked to make sure that the function is 
71143 ** defined and that the correct number of arguments are specified.
71144 ** If the function is an aggregate function, then the pNC->hasAgg is
71145 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
71146 ** If an expression contains aggregate functions then the EP_Agg
71147 ** property on the expression is set.
71148 **
71149 ** An error message is left in pParse if anything is amiss.  The number
71150 ** if errors is returned.
71151 */
71152 SQLITE_PRIVATE int sqlite3ResolveExprNames( 
71153   NameContext *pNC,       /* Namespace to resolve expressions in. */
71154   Expr *pExpr             /* The expression to be analyzed. */
71155 ){
71156   int savedHasAgg;
71157   Walker w;
71158
71159   if( pExpr==0 ) return 0;
71160 #if SQLITE_MAX_EXPR_DEPTH>0
71161   {
71162     Parse *pParse = pNC->pParse;
71163     if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
71164       return 1;
71165     }
71166     pParse->nHeight += pExpr->nHeight;
71167   }
71168 #endif
71169   savedHasAgg = pNC->hasAgg;
71170   pNC->hasAgg = 0;
71171   w.xExprCallback = resolveExprStep;
71172   w.xSelectCallback = resolveSelectStep;
71173   w.pParse = pNC->pParse;
71174   w.u.pNC = pNC;
71175   sqlite3WalkExpr(&w, pExpr);
71176 #if SQLITE_MAX_EXPR_DEPTH>0
71177   pNC->pParse->nHeight -= pExpr->nHeight;
71178 #endif
71179   if( pNC->nErr>0 || w.pParse->nErr>0 ){
71180     ExprSetProperty(pExpr, EP_Error);
71181   }
71182   if( pNC->hasAgg ){
71183     ExprSetProperty(pExpr, EP_Agg);
71184   }else if( savedHasAgg ){
71185     pNC->hasAgg = 1;
71186   }
71187   return ExprHasProperty(pExpr, EP_Error);
71188 }
71189
71190
71191 /*
71192 ** Resolve all names in all expressions of a SELECT and in all
71193 ** decendents of the SELECT, including compounds off of p->pPrior,
71194 ** subqueries in expressions, and subqueries used as FROM clause
71195 ** terms.
71196 **
71197 ** See sqlite3ResolveExprNames() for a description of the kinds of
71198 ** transformations that occur.
71199 **
71200 ** All SELECT statements should have been expanded using
71201 ** sqlite3SelectExpand() prior to invoking this routine.
71202 */
71203 SQLITE_PRIVATE void sqlite3ResolveSelectNames(
71204   Parse *pParse,         /* The parser context */
71205   Select *p,             /* The SELECT statement being coded. */
71206   NameContext *pOuterNC  /* Name context for parent SELECT statement */
71207 ){
71208   Walker w;
71209
71210   assert( p!=0 );
71211   w.xExprCallback = resolveExprStep;
71212   w.xSelectCallback = resolveSelectStep;
71213   w.pParse = pParse;
71214   w.u.pNC = pOuterNC;
71215   sqlite3WalkSelect(&w, p);
71216 }
71217
71218 /************** End of resolve.c *********************************************/
71219 /************** Begin file expr.c ********************************************/
71220 /*
71221 ** 2001 September 15
71222 **
71223 ** The author disclaims copyright to this source code.  In place of
71224 ** a legal notice, here is a blessing:
71225 **
71226 **    May you do good and not evil.
71227 **    May you find forgiveness for yourself and forgive others.
71228 **    May you share freely, never taking more than you give.
71229 **
71230 *************************************************************************
71231 ** This file contains routines used for analyzing expressions and
71232 ** for generating VDBE code that evaluates expressions in SQLite.
71233 */
71234
71235 /*
71236 ** Return the 'affinity' of the expression pExpr if any.
71237 **
71238 ** If pExpr is a column, a reference to a column via an 'AS' alias,
71239 ** or a sub-select with a column as the return value, then the 
71240 ** affinity of that column is returned. Otherwise, 0x00 is returned,
71241 ** indicating no affinity for the expression.
71242 **
71243 ** i.e. the WHERE clause expresssions in the following statements all
71244 ** have an affinity:
71245 **
71246 ** CREATE TABLE t1(a);
71247 ** SELECT * FROM t1 WHERE a;
71248 ** SELECT a AS b FROM t1 WHERE b;
71249 ** SELECT * FROM t1 WHERE (select a from t1);
71250 */
71251 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
71252   int op = pExpr->op;
71253   if( op==TK_SELECT ){
71254     assert( pExpr->flags&EP_xIsSelect );
71255     return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
71256   }
71257 #ifndef SQLITE_OMIT_CAST
71258   if( op==TK_CAST ){
71259     assert( !ExprHasProperty(pExpr, EP_IntValue) );
71260     return sqlite3AffinityType(pExpr->u.zToken);
71261   }
71262 #endif
71263   if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER) 
71264    && pExpr->pTab!=0
71265   ){
71266     /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
71267     ** a TK_COLUMN but was previously evaluated and cached in a register */
71268     int j = pExpr->iColumn;
71269     if( j<0 ) return SQLITE_AFF_INTEGER;
71270     assert( pExpr->pTab && j<pExpr->pTab->nCol );
71271     return pExpr->pTab->aCol[j].affinity;
71272   }
71273   return pExpr->affinity;
71274 }
71275
71276 /*
71277 ** Set the explicit collating sequence for an expression to the
71278 ** collating sequence supplied in the second argument.
71279 */
71280 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Expr *pExpr, CollSeq *pColl){
71281   if( pExpr && pColl ){
71282     pExpr->pColl = pColl;
71283     pExpr->flags |= EP_ExpCollate;
71284   }
71285   return pExpr;
71286 }
71287
71288 /*
71289 ** Set the collating sequence for expression pExpr to be the collating
71290 ** sequence named by pToken.   Return a pointer to the revised expression.
71291 ** The collating sequence is marked as "explicit" using the EP_ExpCollate
71292 ** flag.  An explicit collating sequence will override implicit
71293 ** collating sequences.
71294 */
71295 SQLITE_PRIVATE Expr *sqlite3ExprSetCollByToken(Parse *pParse, Expr *pExpr, Token *pCollName){
71296   char *zColl = 0;            /* Dequoted name of collation sequence */
71297   CollSeq *pColl;
71298   sqlite3 *db = pParse->db;
71299   zColl = sqlite3NameFromToken(db, pCollName);
71300   pColl = sqlite3LocateCollSeq(pParse, zColl);
71301   sqlite3ExprSetColl(pExpr, pColl);
71302   sqlite3DbFree(db, zColl);
71303   return pExpr;
71304 }
71305
71306 /*
71307 ** Return the default collation sequence for the expression pExpr. If
71308 ** there is no default collation type, return 0.
71309 */
71310 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
71311   CollSeq *pColl = 0;
71312   Expr *p = pExpr;
71313   while( p ){
71314     int op;
71315     pColl = p->pColl;
71316     if( pColl ) break;
71317     op = p->op;
71318     if( p->pTab!=0 && (
71319         op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER || op==TK_TRIGGER
71320     )){
71321       /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
71322       ** a TK_COLUMN but was previously evaluated and cached in a register */
71323       const char *zColl;
71324       int j = p->iColumn;
71325       if( j>=0 ){
71326         sqlite3 *db = pParse->db;
71327         zColl = p->pTab->aCol[j].zColl;
71328         pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
71329         pExpr->pColl = pColl;
71330       }
71331       break;
71332     }
71333     if( op!=TK_CAST && op!=TK_UPLUS ){
71334       break;
71335     }
71336     p = p->pLeft;
71337   }
71338   if( sqlite3CheckCollSeq(pParse, pColl) ){ 
71339     pColl = 0;
71340   }
71341   return pColl;
71342 }
71343
71344 /*
71345 ** pExpr is an operand of a comparison operator.  aff2 is the
71346 ** type affinity of the other operand.  This routine returns the
71347 ** type affinity that should be used for the comparison operator.
71348 */
71349 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
71350   char aff1 = sqlite3ExprAffinity(pExpr);
71351   if( aff1 && aff2 ){
71352     /* Both sides of the comparison are columns. If one has numeric
71353     ** affinity, use that. Otherwise use no affinity.
71354     */
71355     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
71356       return SQLITE_AFF_NUMERIC;
71357     }else{
71358       return SQLITE_AFF_NONE;
71359     }
71360   }else if( !aff1 && !aff2 ){
71361     /* Neither side of the comparison is a column.  Compare the
71362     ** results directly.
71363     */
71364     return SQLITE_AFF_NONE;
71365   }else{
71366     /* One side is a column, the other is not. Use the columns affinity. */
71367     assert( aff1==0 || aff2==0 );
71368     return (aff1 + aff2);
71369   }
71370 }
71371
71372 /*
71373 ** pExpr is a comparison operator.  Return the type affinity that should
71374 ** be applied to both operands prior to doing the comparison.
71375 */
71376 static char comparisonAffinity(Expr *pExpr){
71377   char aff;
71378   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
71379           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
71380           pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
71381   assert( pExpr->pLeft );
71382   aff = sqlite3ExprAffinity(pExpr->pLeft);
71383   if( pExpr->pRight ){
71384     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
71385   }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
71386     aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
71387   }else if( !aff ){
71388     aff = SQLITE_AFF_NONE;
71389   }
71390   return aff;
71391 }
71392
71393 /*
71394 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
71395 ** idx_affinity is the affinity of an indexed column. Return true
71396 ** if the index with affinity idx_affinity may be used to implement
71397 ** the comparison in pExpr.
71398 */
71399 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
71400   char aff = comparisonAffinity(pExpr);
71401   switch( aff ){
71402     case SQLITE_AFF_NONE:
71403       return 1;
71404     case SQLITE_AFF_TEXT:
71405       return idx_affinity==SQLITE_AFF_TEXT;
71406     default:
71407       return sqlite3IsNumericAffinity(idx_affinity);
71408   }
71409 }
71410
71411 /*
71412 ** Return the P5 value that should be used for a binary comparison
71413 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
71414 */
71415 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
71416   u8 aff = (char)sqlite3ExprAffinity(pExpr2);
71417   aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
71418   return aff;
71419 }
71420
71421 /*
71422 ** Return a pointer to the collation sequence that should be used by
71423 ** a binary comparison operator comparing pLeft and pRight.
71424 **
71425 ** If the left hand expression has a collating sequence type, then it is
71426 ** used. Otherwise the collation sequence for the right hand expression
71427 ** is used, or the default (BINARY) if neither expression has a collating
71428 ** type.
71429 **
71430 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
71431 ** it is not considered.
71432 */
71433 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
71434   Parse *pParse, 
71435   Expr *pLeft, 
71436   Expr *pRight
71437 ){
71438   CollSeq *pColl;
71439   assert( pLeft );
71440   if( pLeft->flags & EP_ExpCollate ){
71441     assert( pLeft->pColl );
71442     pColl = pLeft->pColl;
71443   }else if( pRight && pRight->flags & EP_ExpCollate ){
71444     assert( pRight->pColl );
71445     pColl = pRight->pColl;
71446   }else{
71447     pColl = sqlite3ExprCollSeq(pParse, pLeft);
71448     if( !pColl ){
71449       pColl = sqlite3ExprCollSeq(pParse, pRight);
71450     }
71451   }
71452   return pColl;
71453 }
71454
71455 /*
71456 ** Generate code for a comparison operator.
71457 */
71458 static int codeCompare(
71459   Parse *pParse,    /* The parsing (and code generating) context */
71460   Expr *pLeft,      /* The left operand */
71461   Expr *pRight,     /* The right operand */
71462   int opcode,       /* The comparison opcode */
71463   int in1, int in2, /* Register holding operands */
71464   int dest,         /* Jump here if true.  */
71465   int jumpIfNull    /* If true, jump if either operand is NULL */
71466 ){
71467   int p5;
71468   int addr;
71469   CollSeq *p4;
71470
71471   p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
71472   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
71473   addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
71474                            (void*)p4, P4_COLLSEQ);
71475   sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
71476   return addr;
71477 }
71478
71479 #if SQLITE_MAX_EXPR_DEPTH>0
71480 /*
71481 ** Check that argument nHeight is less than or equal to the maximum
71482 ** expression depth allowed. If it is not, leave an error message in
71483 ** pParse.
71484 */
71485 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
71486   int rc = SQLITE_OK;
71487   int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
71488   if( nHeight>mxHeight ){
71489     sqlite3ErrorMsg(pParse, 
71490        "Expression tree is too large (maximum depth %d)", mxHeight
71491     );
71492     rc = SQLITE_ERROR;
71493   }
71494   return rc;
71495 }
71496
71497 /* The following three functions, heightOfExpr(), heightOfExprList()
71498 ** and heightOfSelect(), are used to determine the maximum height
71499 ** of any expression tree referenced by the structure passed as the
71500 ** first argument.
71501 **
71502 ** If this maximum height is greater than the current value pointed
71503 ** to by pnHeight, the second parameter, then set *pnHeight to that
71504 ** value.
71505 */
71506 static void heightOfExpr(Expr *p, int *pnHeight){
71507   if( p ){
71508     if( p->nHeight>*pnHeight ){
71509       *pnHeight = p->nHeight;
71510     }
71511   }
71512 }
71513 static void heightOfExprList(ExprList *p, int *pnHeight){
71514   if( p ){
71515     int i;
71516     for(i=0; i<p->nExpr; i++){
71517       heightOfExpr(p->a[i].pExpr, pnHeight);
71518     }
71519   }
71520 }
71521 static void heightOfSelect(Select *p, int *pnHeight){
71522   if( p ){
71523     heightOfExpr(p->pWhere, pnHeight);
71524     heightOfExpr(p->pHaving, pnHeight);
71525     heightOfExpr(p->pLimit, pnHeight);
71526     heightOfExpr(p->pOffset, pnHeight);
71527     heightOfExprList(p->pEList, pnHeight);
71528     heightOfExprList(p->pGroupBy, pnHeight);
71529     heightOfExprList(p->pOrderBy, pnHeight);
71530     heightOfSelect(p->pPrior, pnHeight);
71531   }
71532 }
71533
71534 /*
71535 ** Set the Expr.nHeight variable in the structure passed as an 
71536 ** argument. An expression with no children, Expr.pList or 
71537 ** Expr.pSelect member has a height of 1. Any other expression
71538 ** has a height equal to the maximum height of any other 
71539 ** referenced Expr plus one.
71540 */
71541 static void exprSetHeight(Expr *p){
71542   int nHeight = 0;
71543   heightOfExpr(p->pLeft, &nHeight);
71544   heightOfExpr(p->pRight, &nHeight);
71545   if( ExprHasProperty(p, EP_xIsSelect) ){
71546     heightOfSelect(p->x.pSelect, &nHeight);
71547   }else{
71548     heightOfExprList(p->x.pList, &nHeight);
71549   }
71550   p->nHeight = nHeight + 1;
71551 }
71552
71553 /*
71554 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
71555 ** the height is greater than the maximum allowed expression depth,
71556 ** leave an error in pParse.
71557 */
71558 SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
71559   exprSetHeight(p);
71560   sqlite3ExprCheckHeight(pParse, p->nHeight);
71561 }
71562
71563 /*
71564 ** Return the maximum height of any expression tree referenced
71565 ** by the select statement passed as an argument.
71566 */
71567 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
71568   int nHeight = 0;
71569   heightOfSelect(p, &nHeight);
71570   return nHeight;
71571 }
71572 #else
71573   #define exprSetHeight(y)
71574 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
71575
71576 /*
71577 ** This routine is the core allocator for Expr nodes.
71578 **
71579 ** Construct a new expression node and return a pointer to it.  Memory
71580 ** for this node and for the pToken argument is a single allocation
71581 ** obtained from sqlite3DbMalloc().  The calling function
71582 ** is responsible for making sure the node eventually gets freed.
71583 **
71584 ** If dequote is true, then the token (if it exists) is dequoted.
71585 ** If dequote is false, no dequoting is performance.  The deQuote
71586 ** parameter is ignored if pToken is NULL or if the token does not
71587 ** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
71588 ** then the EP_DblQuoted flag is set on the expression node.
71589 **
71590 ** Special case:  If op==TK_INTEGER and pToken points to a string that
71591 ** can be translated into a 32-bit integer, then the token is not
71592 ** stored in u.zToken.  Instead, the integer values is written
71593 ** into u.iValue and the EP_IntValue flag is set.  No extra storage
71594 ** is allocated to hold the integer text and the dequote flag is ignored.
71595 */
71596 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
71597   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
71598   int op,                 /* Expression opcode */
71599   const Token *pToken,    /* Token argument.  Might be NULL */
71600   int dequote             /* True to dequote */
71601 ){
71602   Expr *pNew;
71603   int nExtra = 0;
71604   int iValue = 0;
71605
71606   if( pToken ){
71607     if( op!=TK_INTEGER || pToken->z==0
71608           || sqlite3GetInt32(pToken->z, &iValue)==0 ){
71609       nExtra = pToken->n+1;
71610       assert( iValue>=0 );
71611     }
71612   }
71613   pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
71614   if( pNew ){
71615     pNew->op = (u8)op;
71616     pNew->iAgg = -1;
71617     if( pToken ){
71618       if( nExtra==0 ){
71619         pNew->flags |= EP_IntValue;
71620         pNew->u.iValue = iValue;
71621       }else{
71622         int c;
71623         pNew->u.zToken = (char*)&pNew[1];
71624         memcpy(pNew->u.zToken, pToken->z, pToken->n);
71625         pNew->u.zToken[pToken->n] = 0;
71626         if( dequote && nExtra>=3 
71627              && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
71628           sqlite3Dequote(pNew->u.zToken);
71629           if( c=='"' ) pNew->flags |= EP_DblQuoted;
71630         }
71631       }
71632     }
71633 #if SQLITE_MAX_EXPR_DEPTH>0
71634     pNew->nHeight = 1;
71635 #endif  
71636   }
71637   return pNew;
71638 }
71639
71640 /*
71641 ** Allocate a new expression node from a zero-terminated token that has
71642 ** already been dequoted.
71643 */
71644 SQLITE_PRIVATE Expr *sqlite3Expr(
71645   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
71646   int op,                 /* Expression opcode */
71647   const char *zToken      /* Token argument.  Might be NULL */
71648 ){
71649   Token x;
71650   x.z = zToken;
71651   x.n = zToken ? sqlite3Strlen30(zToken) : 0;
71652   return sqlite3ExprAlloc(db, op, &x, 0);
71653 }
71654
71655 /*
71656 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
71657 **
71658 ** If pRoot==NULL that means that a memory allocation error has occurred.
71659 ** In that case, delete the subtrees pLeft and pRight.
71660 */
71661 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
71662   sqlite3 *db,
71663   Expr *pRoot,
71664   Expr *pLeft,
71665   Expr *pRight
71666 ){
71667   if( pRoot==0 ){
71668     assert( db->mallocFailed );
71669     sqlite3ExprDelete(db, pLeft);
71670     sqlite3ExprDelete(db, pRight);
71671   }else{
71672     if( pRight ){
71673       pRoot->pRight = pRight;
71674       if( pRight->flags & EP_ExpCollate ){
71675         pRoot->flags |= EP_ExpCollate;
71676         pRoot->pColl = pRight->pColl;
71677       }
71678     }
71679     if( pLeft ){
71680       pRoot->pLeft = pLeft;
71681       if( pLeft->flags & EP_ExpCollate ){
71682         pRoot->flags |= EP_ExpCollate;
71683         pRoot->pColl = pLeft->pColl;
71684       }
71685     }
71686     exprSetHeight(pRoot);
71687   }
71688 }
71689
71690 /*
71691 ** Allocate a Expr node which joins as many as two subtrees.
71692 **
71693 ** One or both of the subtrees can be NULL.  Return a pointer to the new
71694 ** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
71695 ** free the subtrees and return NULL.
71696 */
71697 SQLITE_PRIVATE Expr *sqlite3PExpr(
71698   Parse *pParse,          /* Parsing context */
71699   int op,                 /* Expression opcode */
71700   Expr *pLeft,            /* Left operand */
71701   Expr *pRight,           /* Right operand */
71702   const Token *pToken     /* Argument token */
71703 ){
71704   Expr *p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
71705   sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
71706   if( p ) {
71707     sqlite3ExprCheckHeight(pParse, p->nHeight);
71708   }
71709   return p;
71710 }
71711
71712 /*
71713 ** Join two expressions using an AND operator.  If either expression is
71714 ** NULL, then just return the other expression.
71715 */
71716 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
71717   if( pLeft==0 ){
71718     return pRight;
71719   }else if( pRight==0 ){
71720     return pLeft;
71721   }else{
71722     Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
71723     sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
71724     return pNew;
71725   }
71726 }
71727
71728 /*
71729 ** Construct a new expression node for a function with multiple
71730 ** arguments.
71731 */
71732 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
71733   Expr *pNew;
71734   sqlite3 *db = pParse->db;
71735   assert( pToken );
71736   pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
71737   if( pNew==0 ){
71738     sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
71739     return 0;
71740   }
71741   pNew->x.pList = pList;
71742   assert( !ExprHasProperty(pNew, EP_xIsSelect) );
71743   sqlite3ExprSetHeight(pParse, pNew);
71744   return pNew;
71745 }
71746
71747 /*
71748 ** Assign a variable number to an expression that encodes a wildcard
71749 ** in the original SQL statement.  
71750 **
71751 ** Wildcards consisting of a single "?" are assigned the next sequential
71752 ** variable number.
71753 **
71754 ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
71755 ** sure "nnn" is not too be to avoid a denial of service attack when
71756 ** the SQL statement comes from an external source.
71757 **
71758 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
71759 ** as the previous instance of the same wildcard.  Or if this is the first
71760 ** instance of the wildcard, the next sequenial variable number is
71761 ** assigned.
71762 */
71763 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
71764   sqlite3 *db = pParse->db;
71765   const char *z;
71766
71767   if( pExpr==0 ) return;
71768   assert( !ExprHasAnyProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
71769   z = pExpr->u.zToken;
71770   assert( z!=0 );
71771   assert( z[0]!=0 );
71772   if( z[1]==0 ){
71773     /* Wildcard of the form "?".  Assign the next variable number */
71774     assert( z[0]=='?' );
71775     pExpr->iColumn = (ynVar)(++pParse->nVar);
71776   }else{
71777     ynVar x = 0;
71778     u32 n = sqlite3Strlen30(z);
71779     if( z[0]=='?' ){
71780       /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
71781       ** use it as the variable number */
71782       i64 i;
71783       int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
71784       pExpr->iColumn = x = (ynVar)i;
71785       testcase( i==0 );
71786       testcase( i==1 );
71787       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
71788       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
71789       if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
71790         sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
71791             db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
71792         x = 0;
71793       }
71794       if( i>pParse->nVar ){
71795         pParse->nVar = (int)i;
71796       }
71797     }else{
71798       /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
71799       ** number as the prior appearance of the same name, or if the name
71800       ** has never appeared before, reuse the same variable number
71801       */
71802       ynVar i;
71803       for(i=0; i<pParse->nzVar; i++){
71804         if( pParse->azVar[i] && memcmp(pParse->azVar[i],z,n+1)==0 ){
71805           pExpr->iColumn = x = (ynVar)i+1;
71806           break;
71807         }
71808       }
71809       if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
71810     }
71811     if( x>0 ){
71812       if( x>pParse->nzVar ){
71813         char **a;
71814         a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
71815         if( a==0 ) return;  /* Error reported through db->mallocFailed */
71816         pParse->azVar = a;
71817         memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
71818         pParse->nzVar = x;
71819       }
71820       if( z[0]!='?' || pParse->azVar[x-1]==0 ){
71821         sqlite3DbFree(db, pParse->azVar[x-1]);
71822         pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
71823       }
71824     }
71825   } 
71826   if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
71827     sqlite3ErrorMsg(pParse, "too many SQL variables");
71828   }
71829 }
71830
71831 /*
71832 ** Recursively delete an expression tree.
71833 */
71834 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
71835   if( p==0 ) return;
71836   /* Sanity check: Assert that the IntValue is non-negative if it exists */
71837   assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
71838   if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
71839     sqlite3ExprDelete(db, p->pLeft);
71840     sqlite3ExprDelete(db, p->pRight);
71841     if( !ExprHasProperty(p, EP_Reduced) && (p->flags2 & EP2_MallocedToken)!=0 ){
71842       sqlite3DbFree(db, p->u.zToken);
71843     }
71844     if( ExprHasProperty(p, EP_xIsSelect) ){
71845       sqlite3SelectDelete(db, p->x.pSelect);
71846     }else{
71847       sqlite3ExprListDelete(db, p->x.pList);
71848     }
71849   }
71850   if( !ExprHasProperty(p, EP_Static) ){
71851     sqlite3DbFree(db, p);
71852   }
71853 }
71854
71855 /*
71856 ** Return the number of bytes allocated for the expression structure 
71857 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
71858 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
71859 */
71860 static int exprStructSize(Expr *p){
71861   if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
71862   if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
71863   return EXPR_FULLSIZE;
71864 }
71865
71866 /*
71867 ** The dupedExpr*Size() routines each return the number of bytes required
71868 ** to store a copy of an expression or expression tree.  They differ in
71869 ** how much of the tree is measured.
71870 **
71871 **     dupedExprStructSize()     Size of only the Expr structure 
71872 **     dupedExprNodeSize()       Size of Expr + space for token
71873 **     dupedExprSize()           Expr + token + subtree components
71874 **
71875 ***************************************************************************
71876 **
71877 ** The dupedExprStructSize() function returns two values OR-ed together:  
71878 ** (1) the space required for a copy of the Expr structure only and 
71879 ** (2) the EP_xxx flags that indicate what the structure size should be.
71880 ** The return values is always one of:
71881 **
71882 **      EXPR_FULLSIZE
71883 **      EXPR_REDUCEDSIZE   | EP_Reduced
71884 **      EXPR_TOKENONLYSIZE | EP_TokenOnly
71885 **
71886 ** The size of the structure can be found by masking the return value
71887 ** of this routine with 0xfff.  The flags can be found by masking the
71888 ** return value with EP_Reduced|EP_TokenOnly.
71889 **
71890 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
71891 ** (unreduced) Expr objects as they or originally constructed by the parser.
71892 ** During expression analysis, extra information is computed and moved into
71893 ** later parts of teh Expr object and that extra information might get chopped
71894 ** off if the expression is reduced.  Note also that it does not work to
71895 ** make a EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
71896 ** to reduce a pristine expression tree from the parser.  The implementation
71897 ** of dupedExprStructSize() contain multiple assert() statements that attempt
71898 ** to enforce this constraint.
71899 */
71900 static int dupedExprStructSize(Expr *p, int flags){
71901   int nSize;
71902   assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
71903   if( 0==(flags&EXPRDUP_REDUCE) ){
71904     nSize = EXPR_FULLSIZE;
71905   }else{
71906     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
71907     assert( !ExprHasProperty(p, EP_FromJoin) ); 
71908     assert( (p->flags2 & EP2_MallocedToken)==0 );
71909     assert( (p->flags2 & EP2_Irreducible)==0 );
71910     if( p->pLeft || p->pRight || p->pColl || p->x.pList ){
71911       nSize = EXPR_REDUCEDSIZE | EP_Reduced;
71912     }else{
71913       nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
71914     }
71915   }
71916   return nSize;
71917 }
71918
71919 /*
71920 ** This function returns the space in bytes required to store the copy 
71921 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
71922 ** string is defined.)
71923 */
71924 static int dupedExprNodeSize(Expr *p, int flags){
71925   int nByte = dupedExprStructSize(p, flags) & 0xfff;
71926   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
71927     nByte += sqlite3Strlen30(p->u.zToken)+1;
71928   }
71929   return ROUND8(nByte);
71930 }
71931
71932 /*
71933 ** Return the number of bytes required to create a duplicate of the 
71934 ** expression passed as the first argument. The second argument is a
71935 ** mask containing EXPRDUP_XXX flags.
71936 **
71937 ** The value returned includes space to create a copy of the Expr struct
71938 ** itself and the buffer referred to by Expr.u.zToken, if any.
71939 **
71940 ** If the EXPRDUP_REDUCE flag is set, then the return value includes 
71941 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft 
71942 ** and Expr.pRight variables (but not for any structures pointed to or 
71943 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
71944 */
71945 static int dupedExprSize(Expr *p, int flags){
71946   int nByte = 0;
71947   if( p ){
71948     nByte = dupedExprNodeSize(p, flags);
71949     if( flags&EXPRDUP_REDUCE ){
71950       nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
71951     }
71952   }
71953   return nByte;
71954 }
71955
71956 /*
71957 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer 
71958 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough 
71959 ** to store the copy of expression p, the copies of p->u.zToken
71960 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
71961 ** if any. Before returning, *pzBuffer is set to the first byte passed the
71962 ** portion of the buffer copied into by this function.
71963 */
71964 static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
71965   Expr *pNew = 0;                      /* Value to return */
71966   if( p ){
71967     const int isReduced = (flags&EXPRDUP_REDUCE);
71968     u8 *zAlloc;
71969     u32 staticFlag = 0;
71970
71971     assert( pzBuffer==0 || isReduced );
71972
71973     /* Figure out where to write the new Expr structure. */
71974     if( pzBuffer ){
71975       zAlloc = *pzBuffer;
71976       staticFlag = EP_Static;
71977     }else{
71978       zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
71979     }
71980     pNew = (Expr *)zAlloc;
71981
71982     if( pNew ){
71983       /* Set nNewSize to the size allocated for the structure pointed to
71984       ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
71985       ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
71986       ** by the copy of the p->u.zToken string (if any).
71987       */
71988       const unsigned nStructSize = dupedExprStructSize(p, flags);
71989       const int nNewSize = nStructSize & 0xfff;
71990       int nToken;
71991       if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
71992         nToken = sqlite3Strlen30(p->u.zToken) + 1;
71993       }else{
71994         nToken = 0;
71995       }
71996       if( isReduced ){
71997         assert( ExprHasProperty(p, EP_Reduced)==0 );
71998         memcpy(zAlloc, p, nNewSize);
71999       }else{
72000         int nSize = exprStructSize(p);
72001         memcpy(zAlloc, p, nSize);
72002         memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
72003       }
72004
72005       /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
72006       pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
72007       pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
72008       pNew->flags |= staticFlag;
72009
72010       /* Copy the p->u.zToken string, if any. */
72011       if( nToken ){
72012         char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
72013         memcpy(zToken, p->u.zToken, nToken);
72014       }
72015
72016       if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
72017         /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
72018         if( ExprHasProperty(p, EP_xIsSelect) ){
72019           pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
72020         }else{
72021           pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
72022         }
72023       }
72024
72025       /* Fill in pNew->pLeft and pNew->pRight. */
72026       if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly) ){
72027         zAlloc += dupedExprNodeSize(p, flags);
72028         if( ExprHasProperty(pNew, EP_Reduced) ){
72029           pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
72030           pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
72031         }
72032         if( pzBuffer ){
72033           *pzBuffer = zAlloc;
72034         }
72035       }else{
72036         pNew->flags2 = 0;
72037         if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
72038           pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
72039           pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
72040         }
72041       }
72042
72043     }
72044   }
72045   return pNew;
72046 }
72047
72048 /*
72049 ** The following group of routines make deep copies of expressions,
72050 ** expression lists, ID lists, and select statements.  The copies can
72051 ** be deleted (by being passed to their respective ...Delete() routines)
72052 ** without effecting the originals.
72053 **
72054 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
72055 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded 
72056 ** by subsequent calls to sqlite*ListAppend() routines.
72057 **
72058 ** Any tables that the SrcList might point to are not duplicated.
72059 **
72060 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
72061 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
72062 ** truncated version of the usual Expr structure that will be stored as
72063 ** part of the in-memory representation of the database schema.
72064 */
72065 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
72066   return exprDup(db, p, flags, 0);
72067 }
72068 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
72069   ExprList *pNew;
72070   struct ExprList_item *pItem, *pOldItem;
72071   int i;
72072   if( p==0 ) return 0;
72073   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
72074   if( pNew==0 ) return 0;
72075   pNew->iECursor = 0;
72076   pNew->nExpr = pNew->nAlloc = p->nExpr;
72077   pNew->a = pItem = sqlite3DbMallocRaw(db,  p->nExpr*sizeof(p->a[0]) );
72078   if( pItem==0 ){
72079     sqlite3DbFree(db, pNew);
72080     return 0;
72081   } 
72082   pOldItem = p->a;
72083   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
72084     Expr *pOldExpr = pOldItem->pExpr;
72085     pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
72086     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
72087     pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
72088     pItem->sortOrder = pOldItem->sortOrder;
72089     pItem->done = 0;
72090     pItem->iCol = pOldItem->iCol;
72091     pItem->iAlias = pOldItem->iAlias;
72092   }
72093   return pNew;
72094 }
72095
72096 /*
72097 ** If cursors, triggers, views and subqueries are all omitted from
72098 ** the build, then none of the following routines, except for 
72099 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
72100 ** called with a NULL argument.
72101 */
72102 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
72103  || !defined(SQLITE_OMIT_SUBQUERY)
72104 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
72105   SrcList *pNew;
72106   int i;
72107   int nByte;
72108   if( p==0 ) return 0;
72109   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
72110   pNew = sqlite3DbMallocRaw(db, nByte );
72111   if( pNew==0 ) return 0;
72112   pNew->nSrc = pNew->nAlloc = p->nSrc;
72113   for(i=0; i<p->nSrc; i++){
72114     struct SrcList_item *pNewItem = &pNew->a[i];
72115     struct SrcList_item *pOldItem = &p->a[i];
72116     Table *pTab;
72117     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
72118     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
72119     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
72120     pNewItem->jointype = pOldItem->jointype;
72121     pNewItem->iCursor = pOldItem->iCursor;
72122     pNewItem->isPopulated = pOldItem->isPopulated;
72123     pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
72124     pNewItem->notIndexed = pOldItem->notIndexed;
72125     pNewItem->pIndex = pOldItem->pIndex;
72126     pTab = pNewItem->pTab = pOldItem->pTab;
72127     if( pTab ){
72128       pTab->nRef++;
72129     }
72130     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
72131     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
72132     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
72133     pNewItem->colUsed = pOldItem->colUsed;
72134   }
72135   return pNew;
72136 }
72137 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
72138   IdList *pNew;
72139   int i;
72140   if( p==0 ) return 0;
72141   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
72142   if( pNew==0 ) return 0;
72143   pNew->nId = pNew->nAlloc = p->nId;
72144   pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
72145   if( pNew->a==0 ){
72146     sqlite3DbFree(db, pNew);
72147     return 0;
72148   }
72149   for(i=0; i<p->nId; i++){
72150     struct IdList_item *pNewItem = &pNew->a[i];
72151     struct IdList_item *pOldItem = &p->a[i];
72152     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
72153     pNewItem->idx = pOldItem->idx;
72154   }
72155   return pNew;
72156 }
72157 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
72158   Select *pNew;
72159   if( p==0 ) return 0;
72160   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
72161   if( pNew==0 ) return 0;
72162   pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
72163   pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
72164   pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
72165   pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
72166   pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
72167   pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
72168   pNew->op = p->op;
72169   pNew->pPrior = sqlite3SelectDup(db, p->pPrior, flags);
72170   pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
72171   pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
72172   pNew->iLimit = 0;
72173   pNew->iOffset = 0;
72174   pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
72175   pNew->pRightmost = 0;
72176   pNew->addrOpenEphm[0] = -1;
72177   pNew->addrOpenEphm[1] = -1;
72178   pNew->addrOpenEphm[2] = -1;
72179   return pNew;
72180 }
72181 #else
72182 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
72183   assert( p==0 );
72184   return 0;
72185 }
72186 #endif
72187
72188
72189 /*
72190 ** Add a new element to the end of an expression list.  If pList is
72191 ** initially NULL, then create a new expression list.
72192 **
72193 ** If a memory allocation error occurs, the entire list is freed and
72194 ** NULL is returned.  If non-NULL is returned, then it is guaranteed
72195 ** that the new entry was successfully appended.
72196 */
72197 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
72198   Parse *pParse,          /* Parsing context */
72199   ExprList *pList,        /* List to which to append. Might be NULL */
72200   Expr *pExpr             /* Expression to be appended. Might be NULL */
72201 ){
72202   sqlite3 *db = pParse->db;
72203   if( pList==0 ){
72204     pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
72205     if( pList==0 ){
72206       goto no_mem;
72207     }
72208     assert( pList->nAlloc==0 );
72209   }
72210   if( pList->nAlloc<=pList->nExpr ){
72211     struct ExprList_item *a;
72212     int n = pList->nAlloc*2 + 4;
72213     a = sqlite3DbRealloc(db, pList->a, n*sizeof(pList->a[0]));
72214     if( a==0 ){
72215       goto no_mem;
72216     }
72217     pList->a = a;
72218     pList->nAlloc = sqlite3DbMallocSize(db, a)/sizeof(a[0]);
72219   }
72220   assert( pList->a!=0 );
72221   if( 1 ){
72222     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
72223     memset(pItem, 0, sizeof(*pItem));
72224     pItem->pExpr = pExpr;
72225   }
72226   return pList;
72227
72228 no_mem:     
72229   /* Avoid leaking memory if malloc has failed. */
72230   sqlite3ExprDelete(db, pExpr);
72231   sqlite3ExprListDelete(db, pList);
72232   return 0;
72233 }
72234
72235 /*
72236 ** Set the ExprList.a[].zName element of the most recently added item
72237 ** on the expression list.
72238 **
72239 ** pList might be NULL following an OOM error.  But pName should never be
72240 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
72241 ** is set.
72242 */
72243 SQLITE_PRIVATE void sqlite3ExprListSetName(
72244   Parse *pParse,          /* Parsing context */
72245   ExprList *pList,        /* List to which to add the span. */
72246   Token *pName,           /* Name to be added */
72247   int dequote             /* True to cause the name to be dequoted */
72248 ){
72249   assert( pList!=0 || pParse->db->mallocFailed!=0 );
72250   if( pList ){
72251     struct ExprList_item *pItem;
72252     assert( pList->nExpr>0 );
72253     pItem = &pList->a[pList->nExpr-1];
72254     assert( pItem->zName==0 );
72255     pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
72256     if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
72257   }
72258 }
72259
72260 /*
72261 ** Set the ExprList.a[].zSpan element of the most recently added item
72262 ** on the expression list.
72263 **
72264 ** pList might be NULL following an OOM error.  But pSpan should never be
72265 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
72266 ** is set.
72267 */
72268 SQLITE_PRIVATE void sqlite3ExprListSetSpan(
72269   Parse *pParse,          /* Parsing context */
72270   ExprList *pList,        /* List to which to add the span. */
72271   ExprSpan *pSpan         /* The span to be added */
72272 ){
72273   sqlite3 *db = pParse->db;
72274   assert( pList!=0 || db->mallocFailed!=0 );
72275   if( pList ){
72276     struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
72277     assert( pList->nExpr>0 );
72278     assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
72279     sqlite3DbFree(db, pItem->zSpan);
72280     pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
72281                                     (int)(pSpan->zEnd - pSpan->zStart));
72282   }
72283 }
72284
72285 /*
72286 ** If the expression list pEList contains more than iLimit elements,
72287 ** leave an error message in pParse.
72288 */
72289 SQLITE_PRIVATE void sqlite3ExprListCheckLength(
72290   Parse *pParse,
72291   ExprList *pEList,
72292   const char *zObject
72293 ){
72294   int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
72295   testcase( pEList && pEList->nExpr==mx );
72296   testcase( pEList && pEList->nExpr==mx+1 );
72297   if( pEList && pEList->nExpr>mx ){
72298     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
72299   }
72300 }
72301
72302 /*
72303 ** Delete an entire expression list.
72304 */
72305 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
72306   int i;
72307   struct ExprList_item *pItem;
72308   if( pList==0 ) return;
72309   assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
72310   assert( pList->nExpr<=pList->nAlloc );
72311   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
72312     sqlite3ExprDelete(db, pItem->pExpr);
72313     sqlite3DbFree(db, pItem->zName);
72314     sqlite3DbFree(db, pItem->zSpan);
72315   }
72316   sqlite3DbFree(db, pList->a);
72317   sqlite3DbFree(db, pList);
72318 }
72319
72320 /*
72321 ** These routines are Walker callbacks.  Walker.u.pi is a pointer
72322 ** to an integer.  These routines are checking an expression to see
72323 ** if it is a constant.  Set *Walker.u.pi to 0 if the expression is
72324 ** not constant.
72325 **
72326 ** These callback routines are used to implement the following:
72327 **
72328 **     sqlite3ExprIsConstant()
72329 **     sqlite3ExprIsConstantNotJoin()
72330 **     sqlite3ExprIsConstantOrFunction()
72331 **
72332 */
72333 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
72334
72335   /* If pWalker->u.i is 3 then any term of the expression that comes from
72336   ** the ON or USING clauses of a join disqualifies the expression
72337   ** from being considered constant. */
72338   if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
72339     pWalker->u.i = 0;
72340     return WRC_Abort;
72341   }
72342
72343   switch( pExpr->op ){
72344     /* Consider functions to be constant if all their arguments are constant
72345     ** and pWalker->u.i==2 */
72346     case TK_FUNCTION:
72347       if( pWalker->u.i==2 ) return 0;
72348       /* Fall through */
72349     case TK_ID:
72350     case TK_COLUMN:
72351     case TK_AGG_FUNCTION:
72352     case TK_AGG_COLUMN:
72353       testcase( pExpr->op==TK_ID );
72354       testcase( pExpr->op==TK_COLUMN );
72355       testcase( pExpr->op==TK_AGG_FUNCTION );
72356       testcase( pExpr->op==TK_AGG_COLUMN );
72357       pWalker->u.i = 0;
72358       return WRC_Abort;
72359     default:
72360       testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
72361       testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
72362       return WRC_Continue;
72363   }
72364 }
72365 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
72366   UNUSED_PARAMETER(NotUsed);
72367   pWalker->u.i = 0;
72368   return WRC_Abort;
72369 }
72370 static int exprIsConst(Expr *p, int initFlag){
72371   Walker w;
72372   w.u.i = initFlag;
72373   w.xExprCallback = exprNodeIsConstant;
72374   w.xSelectCallback = selectNodeIsConstant;
72375   sqlite3WalkExpr(&w, p);
72376   return w.u.i;
72377 }
72378
72379 /*
72380 ** Walk an expression tree.  Return 1 if the expression is constant
72381 ** and 0 if it involves variables or function calls.
72382 **
72383 ** For the purposes of this function, a double-quoted string (ex: "abc")
72384 ** is considered a variable but a single-quoted string (ex: 'abc') is
72385 ** a constant.
72386 */
72387 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
72388   return exprIsConst(p, 1);
72389 }
72390
72391 /*
72392 ** Walk an expression tree.  Return 1 if the expression is constant
72393 ** that does no originate from the ON or USING clauses of a join.
72394 ** Return 0 if it involves variables or function calls or terms from
72395 ** an ON or USING clause.
72396 */
72397 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
72398   return exprIsConst(p, 3);
72399 }
72400
72401 /*
72402 ** Walk an expression tree.  Return 1 if the expression is constant
72403 ** or a function call with constant arguments.  Return and 0 if there
72404 ** are any variables.
72405 **
72406 ** For the purposes of this function, a double-quoted string (ex: "abc")
72407 ** is considered a variable but a single-quoted string (ex: 'abc') is
72408 ** a constant.
72409 */
72410 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
72411   return exprIsConst(p, 2);
72412 }
72413
72414 /*
72415 ** If the expression p codes a constant integer that is small enough
72416 ** to fit in a 32-bit integer, return 1 and put the value of the integer
72417 ** in *pValue.  If the expression is not an integer or if it is too big
72418 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
72419 */
72420 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
72421   int rc = 0;
72422
72423   /* If an expression is an integer literal that fits in a signed 32-bit
72424   ** integer, then the EP_IntValue flag will have already been set */
72425   assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
72426            || sqlite3GetInt32(p->u.zToken, &rc)==0 );
72427
72428   if( p->flags & EP_IntValue ){
72429     *pValue = p->u.iValue;
72430     return 1;
72431   }
72432   switch( p->op ){
72433     case TK_UPLUS: {
72434       rc = sqlite3ExprIsInteger(p->pLeft, pValue);
72435       break;
72436     }
72437     case TK_UMINUS: {
72438       int v;
72439       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
72440         *pValue = -v;
72441         rc = 1;
72442       }
72443       break;
72444     }
72445     default: break;
72446   }
72447   return rc;
72448 }
72449
72450 /*
72451 ** Return FALSE if there is no chance that the expression can be NULL.
72452 **
72453 ** If the expression might be NULL or if the expression is too complex
72454 ** to tell return TRUE.  
72455 **
72456 ** This routine is used as an optimization, to skip OP_IsNull opcodes
72457 ** when we know that a value cannot be NULL.  Hence, a false positive
72458 ** (returning TRUE when in fact the expression can never be NULL) might
72459 ** be a small performance hit but is otherwise harmless.  On the other
72460 ** hand, a false negative (returning FALSE when the result could be NULL)
72461 ** will likely result in an incorrect answer.  So when in doubt, return
72462 ** TRUE.
72463 */
72464 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
72465   u8 op;
72466   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
72467   op = p->op;
72468   if( op==TK_REGISTER ) op = p->op2;
72469   switch( op ){
72470     case TK_INTEGER:
72471     case TK_STRING:
72472     case TK_FLOAT:
72473     case TK_BLOB:
72474       return 0;
72475     default:
72476       return 1;
72477   }
72478 }
72479
72480 /*
72481 ** Generate an OP_IsNull instruction that tests register iReg and jumps
72482 ** to location iDest if the value in iReg is NULL.  The value in iReg 
72483 ** was computed by pExpr.  If we can look at pExpr at compile-time and
72484 ** determine that it can never generate a NULL, then the OP_IsNull operation
72485 ** can be omitted.
72486 */
72487 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(
72488   Vdbe *v,            /* The VDBE under construction */
72489   const Expr *pExpr,  /* Only generate OP_IsNull if this expr can be NULL */
72490   int iReg,           /* Test the value in this register for NULL */
72491   int iDest           /* Jump here if the value is null */
72492 ){
72493   if( sqlite3ExprCanBeNull(pExpr) ){
72494     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
72495   }
72496 }
72497
72498 /*
72499 ** Return TRUE if the given expression is a constant which would be
72500 ** unchanged by OP_Affinity with the affinity given in the second
72501 ** argument.
72502 **
72503 ** This routine is used to determine if the OP_Affinity operation
72504 ** can be omitted.  When in doubt return FALSE.  A false negative
72505 ** is harmless.  A false positive, however, can result in the wrong
72506 ** answer.
72507 */
72508 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
72509   u8 op;
72510   if( aff==SQLITE_AFF_NONE ) return 1;
72511   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
72512   op = p->op;
72513   if( op==TK_REGISTER ) op = p->op2;
72514   switch( op ){
72515     case TK_INTEGER: {
72516       return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
72517     }
72518     case TK_FLOAT: {
72519       return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
72520     }
72521     case TK_STRING: {
72522       return aff==SQLITE_AFF_TEXT;
72523     }
72524     case TK_BLOB: {
72525       return 1;
72526     }
72527     case TK_COLUMN: {
72528       assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
72529       return p->iColumn<0
72530           && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
72531     }
72532     default: {
72533       return 0;
72534     }
72535   }
72536 }
72537
72538 /*
72539 ** Return TRUE if the given string is a row-id column name.
72540 */
72541 SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
72542   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
72543   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
72544   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
72545   return 0;
72546 }
72547
72548 /*
72549 ** Return true if we are able to the IN operator optimization on a
72550 ** query of the form
72551 **
72552 **       x IN (SELECT ...)
72553 **
72554 ** Where the SELECT... clause is as specified by the parameter to this
72555 ** routine.
72556 **
72557 ** The Select object passed in has already been preprocessed and no
72558 ** errors have been found.
72559 */
72560 #ifndef SQLITE_OMIT_SUBQUERY
72561 static int isCandidateForInOpt(Select *p){
72562   SrcList *pSrc;
72563   ExprList *pEList;
72564   Table *pTab;
72565   if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
72566   if( p->pPrior ) return 0;              /* Not a compound SELECT */
72567   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
72568     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
72569     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
72570     return 0; /* No DISTINCT keyword and no aggregate functions */
72571   }
72572   assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
72573   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
72574   assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
72575   if( p->pWhere ) return 0;              /* Has no WHERE clause */
72576   pSrc = p->pSrc;
72577   assert( pSrc!=0 );
72578   if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
72579   if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
72580   pTab = pSrc->a[0].pTab;
72581   if( NEVER(pTab==0) ) return 0;
72582   assert( pTab->pSelect==0 );            /* FROM clause is not a view */
72583   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
72584   pEList = p->pEList;
72585   if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
72586   if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
72587   return 1;
72588 }
72589 #endif /* SQLITE_OMIT_SUBQUERY */
72590
72591 /*
72592 ** This function is used by the implementation of the IN (...) operator.
72593 ** It's job is to find or create a b-tree structure that may be used
72594 ** either to test for membership of the (...) set or to iterate through
72595 ** its members, skipping duplicates.
72596 **
72597 ** The index of the cursor opened on the b-tree (database table, database index 
72598 ** or ephermal table) is stored in pX->iTable before this function returns.
72599 ** The returned value of this function indicates the b-tree type, as follows:
72600 **
72601 **   IN_INDEX_ROWID - The cursor was opened on a database table.
72602 **   IN_INDEX_INDEX - The cursor was opened on a database index.
72603 **   IN_INDEX_EPH -   The cursor was opened on a specially created and
72604 **                    populated epheremal table.
72605 **
72606 ** An existing b-tree may only be used if the SELECT is of the simple
72607 ** form:
72608 **
72609 **     SELECT <column> FROM <table>
72610 **
72611 ** If the prNotFound parameter is 0, then the b-tree will be used to iterate
72612 ** through the set members, skipping any duplicates. In this case an
72613 ** epheremal table must be used unless the selected <column> is guaranteed
72614 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
72615 ** has a UNIQUE constraint or UNIQUE index.
72616 **
72617 ** If the prNotFound parameter is not 0, then the b-tree will be used 
72618 ** for fast set membership tests. In this case an epheremal table must 
72619 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can 
72620 ** be found with <column> as its left-most column.
72621 **
72622 ** When the b-tree is being used for membership tests, the calling function
72623 ** needs to know whether or not the structure contains an SQL NULL 
72624 ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
72625 ** If there is any chance that the (...) might contain a NULL value at
72626 ** runtime, then a register is allocated and the register number written
72627 ** to *prNotFound. If there is no chance that the (...) contains a
72628 ** NULL value, then *prNotFound is left unchanged.
72629 **
72630 ** If a register is allocated and its location stored in *prNotFound, then
72631 ** its initial value is NULL.  If the (...) does not remain constant
72632 ** for the duration of the query (i.e. the SELECT within the (...)
72633 ** is a correlated subquery) then the value of the allocated register is
72634 ** reset to NULL each time the subquery is rerun. This allows the
72635 ** caller to use vdbe code equivalent to the following:
72636 **
72637 **   if( register==NULL ){
72638 **     has_null = <test if data structure contains null>
72639 **     register = 1
72640 **   }
72641 **
72642 ** in order to avoid running the <test if data structure contains null>
72643 ** test more often than is necessary.
72644 */
72645 #ifndef SQLITE_OMIT_SUBQUERY
72646 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
72647   Select *p;                            /* SELECT to the right of IN operator */
72648   int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
72649   int iTab = pParse->nTab++;            /* Cursor of the RHS table */
72650   int mustBeUnique = (prNotFound==0);   /* True if RHS must be unique */
72651
72652   assert( pX->op==TK_IN );
72653
72654   /* Check to see if an existing table or index can be used to
72655   ** satisfy the query.  This is preferable to generating a new 
72656   ** ephemeral table.
72657   */
72658   p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
72659   if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
72660     sqlite3 *db = pParse->db;              /* Database connection */
72661     Expr *pExpr = p->pEList->a[0].pExpr;   /* Expression <column> */
72662     int iCol = pExpr->iColumn;             /* Index of column <column> */
72663     Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
72664     Table *pTab = p->pSrc->a[0].pTab;      /* Table <table>. */
72665     int iDb;                               /* Database idx for pTab */
72666    
72667     /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
72668     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
72669     sqlite3CodeVerifySchema(pParse, iDb);
72670     sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
72671
72672     /* This function is only called from two places. In both cases the vdbe
72673     ** has already been allocated. So assume sqlite3GetVdbe() is always
72674     ** successful here.
72675     */
72676     assert(v);
72677     if( iCol<0 ){
72678       int iMem = ++pParse->nMem;
72679       int iAddr;
72680
72681       iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
72682       sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
72683
72684       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
72685       eType = IN_INDEX_ROWID;
72686
72687       sqlite3VdbeJumpHere(v, iAddr);
72688     }else{
72689       Index *pIdx;                         /* Iterator variable */
72690
72691       /* The collation sequence used by the comparison. If an index is to
72692       ** be used in place of a temp-table, it must be ordered according
72693       ** to this collation sequence.  */
72694       CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
72695
72696       /* Check that the affinity that will be used to perform the 
72697       ** comparison is the same as the affinity of the column. If
72698       ** it is not, it is not possible to use any index.
72699       */
72700       char aff = comparisonAffinity(pX);
72701       int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);
72702
72703       for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
72704         if( (pIdx->aiColumn[0]==iCol)
72705          && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
72706          && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
72707         ){
72708           int iMem = ++pParse->nMem;
72709           int iAddr;
72710           char *pKey;
72711   
72712           pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
72713           iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
72714           sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
72715   
72716           sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
72717                                pKey,P4_KEYINFO_HANDOFF);
72718           VdbeComment((v, "%s", pIdx->zName));
72719           eType = IN_INDEX_INDEX;
72720
72721           sqlite3VdbeJumpHere(v, iAddr);
72722           if( prNotFound && !pTab->aCol[iCol].notNull ){
72723             *prNotFound = ++pParse->nMem;
72724           }
72725         }
72726       }
72727     }
72728   }
72729
72730   if( eType==0 ){
72731     /* Could not found an existing table or index to use as the RHS b-tree.
72732     ** We will have to generate an ephemeral table to do the job.
72733     */
72734     double savedNQueryLoop = pParse->nQueryLoop;
72735     int rMayHaveNull = 0;
72736     eType = IN_INDEX_EPH;
72737     if( prNotFound ){
72738       *prNotFound = rMayHaveNull = ++pParse->nMem;
72739     }else{
72740       testcase( pParse->nQueryLoop>(double)1 );
72741       pParse->nQueryLoop = (double)1;
72742       if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
72743         eType = IN_INDEX_ROWID;
72744       }
72745     }
72746     sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
72747     pParse->nQueryLoop = savedNQueryLoop;
72748   }else{
72749     pX->iTable = iTab;
72750   }
72751   return eType;
72752 }
72753 #endif
72754
72755 /*
72756 ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
72757 ** or IN operators.  Examples:
72758 **
72759 **     (SELECT a FROM b)          -- subquery
72760 **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
72761 **     x IN (4,5,11)              -- IN operator with list on right-hand side
72762 **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
72763 **
72764 ** The pExpr parameter describes the expression that contains the IN
72765 ** operator or subquery.
72766 **
72767 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
72768 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
72769 ** to some integer key column of a table B-Tree. In this case, use an
72770 ** intkey B-Tree to store the set of IN(...) values instead of the usual
72771 ** (slower) variable length keys B-Tree.
72772 **
72773 ** If rMayHaveNull is non-zero, that means that the operation is an IN
72774 ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
72775 ** Furthermore, the IN is in a WHERE clause and that we really want
72776 ** to iterate over the RHS of the IN operator in order to quickly locate
72777 ** all corresponding LHS elements.  All this routine does is initialize
72778 ** the register given by rMayHaveNull to NULL.  Calling routines will take
72779 ** care of changing this register value to non-NULL if the RHS is NULL-free.
72780 **
72781 ** If rMayHaveNull is zero, that means that the subquery is being used
72782 ** for membership testing only.  There is no need to initialize any
72783 ** registers to indicate the presense or absence of NULLs on the RHS.
72784 **
72785 ** For a SELECT or EXISTS operator, return the register that holds the
72786 ** result.  For IN operators or if an error occurs, the return value is 0.
72787 */
72788 #ifndef SQLITE_OMIT_SUBQUERY
72789 SQLITE_PRIVATE int sqlite3CodeSubselect(
72790   Parse *pParse,          /* Parsing context */
72791   Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
72792   int rMayHaveNull,       /* Register that records whether NULLs exist in RHS */
72793   int isRowid             /* If true, LHS of IN operator is a rowid */
72794 ){
72795   int testAddr = 0;                       /* One-time test address */
72796   int rReg = 0;                           /* Register storing resulting */
72797   Vdbe *v = sqlite3GetVdbe(pParse);
72798   if( NEVER(v==0) ) return 0;
72799   sqlite3ExprCachePush(pParse);
72800
72801   /* This code must be run in its entirety every time it is encountered
72802   ** if any of the following is true:
72803   **
72804   **    *  The right-hand side is a correlated subquery
72805   **    *  The right-hand side is an expression list containing variables
72806   **    *  We are inside a trigger
72807   **
72808   ** If all of the above are false, then we can run this code just once
72809   ** save the results, and reuse the same result on subsequent invocations.
72810   */
72811   if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->pTriggerTab ){
72812     int mem = ++pParse->nMem;
72813     sqlite3VdbeAddOp1(v, OP_If, mem);
72814     testAddr = sqlite3VdbeAddOp2(v, OP_Integer, 1, mem);
72815     assert( testAddr>0 || pParse->db->mallocFailed );
72816   }
72817
72818 #ifndef SQLITE_OMIT_EXPLAIN
72819   if( pParse->explain==2 ){
72820     char *zMsg = sqlite3MPrintf(
72821         pParse->db, "EXECUTE %s%s SUBQUERY %d", testAddr?"":"CORRELATED ",
72822         pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
72823     );
72824     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
72825   }
72826 #endif
72827
72828   switch( pExpr->op ){
72829     case TK_IN: {
72830       char affinity;              /* Affinity of the LHS of the IN */
72831       KeyInfo keyInfo;            /* Keyinfo for the generated table */
72832       int addr;                   /* Address of OP_OpenEphemeral instruction */
72833       Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
72834
72835       if( rMayHaveNull ){
72836         sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
72837       }
72838
72839       affinity = sqlite3ExprAffinity(pLeft);
72840
72841       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
72842       ** expression it is handled the same way.  An ephemeral table is 
72843       ** filled with single-field index keys representing the results
72844       ** from the SELECT or the <exprlist>.
72845       **
72846       ** If the 'x' expression is a column value, or the SELECT...
72847       ** statement returns a column value, then the affinity of that
72848       ** column is used to build the index keys. If both 'x' and the
72849       ** SELECT... statement are columns, then numeric affinity is used
72850       ** if either column has NUMERIC or INTEGER affinity. If neither
72851       ** 'x' nor the SELECT... statement are columns, then numeric affinity
72852       ** is used.
72853       */
72854       pExpr->iTable = pParse->nTab++;
72855       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
72856       if( rMayHaveNull==0 ) sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
72857       memset(&keyInfo, 0, sizeof(keyInfo));
72858       keyInfo.nField = 1;
72859
72860       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
72861         /* Case 1:     expr IN (SELECT ...)
72862         **
72863         ** Generate code to write the results of the select into the temporary
72864         ** table allocated and opened above.
72865         */
72866         SelectDest dest;
72867         ExprList *pEList;
72868
72869         assert( !isRowid );
72870         sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
72871         dest.affinity = (u8)affinity;
72872         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
72873         pExpr->x.pSelect->iLimit = 0;
72874         if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
72875           return 0;
72876         }
72877         pEList = pExpr->x.pSelect->pEList;
72878         if( ALWAYS(pEList!=0 && pEList->nExpr>0) ){ 
72879           keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
72880               pEList->a[0].pExpr);
72881         }
72882       }else if( ALWAYS(pExpr->x.pList!=0) ){
72883         /* Case 2:     expr IN (exprlist)
72884         **
72885         ** For each expression, build an index key from the evaluation and
72886         ** store it in the temporary table. If <expr> is a column, then use
72887         ** that columns affinity when building index keys. If <expr> is not
72888         ** a column, use numeric affinity.
72889         */
72890         int i;
72891         ExprList *pList = pExpr->x.pList;
72892         struct ExprList_item *pItem;
72893         int r1, r2, r3;
72894
72895         if( !affinity ){
72896           affinity = SQLITE_AFF_NONE;
72897         }
72898         keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
72899
72900         /* Loop through each expression in <exprlist>. */
72901         r1 = sqlite3GetTempReg(pParse);
72902         r2 = sqlite3GetTempReg(pParse);
72903         sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
72904         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
72905           Expr *pE2 = pItem->pExpr;
72906           int iValToIns;
72907
72908           /* If the expression is not constant then we will need to
72909           ** disable the test that was generated above that makes sure
72910           ** this code only executes once.  Because for a non-constant
72911           ** expression we need to rerun this code each time.
72912           */
72913           if( testAddr && !sqlite3ExprIsConstant(pE2) ){
72914             sqlite3VdbeChangeToNoop(v, testAddr-1, 2);
72915             testAddr = 0;
72916           }
72917
72918           /* Evaluate the expression and insert it into the temp table */
72919           if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
72920             sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
72921           }else{
72922             r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
72923             if( isRowid ){
72924               sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
72925                                 sqlite3VdbeCurrentAddr(v)+2);
72926               sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
72927             }else{
72928               sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
72929               sqlite3ExprCacheAffinityChange(pParse, r3, 1);
72930               sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
72931             }
72932           }
72933         }
72934         sqlite3ReleaseTempReg(pParse, r1);
72935         sqlite3ReleaseTempReg(pParse, r2);
72936       }
72937       if( !isRowid ){
72938         sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
72939       }
72940       break;
72941     }
72942
72943     case TK_EXISTS:
72944     case TK_SELECT:
72945     default: {
72946       /* If this has to be a scalar SELECT.  Generate code to put the
72947       ** value of this select in a memory cell and record the number
72948       ** of the memory cell in iColumn.  If this is an EXISTS, write
72949       ** an integer 0 (not exists) or 1 (exists) into a memory cell
72950       ** and record that memory cell in iColumn.
72951       */
72952       Select *pSel;                         /* SELECT statement to encode */
72953       SelectDest dest;                      /* How to deal with SELECt result */
72954
72955       testcase( pExpr->op==TK_EXISTS );
72956       testcase( pExpr->op==TK_SELECT );
72957       assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
72958
72959       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
72960       pSel = pExpr->x.pSelect;
72961       sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
72962       if( pExpr->op==TK_SELECT ){
72963         dest.eDest = SRT_Mem;
72964         sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm);
72965         VdbeComment((v, "Init subquery result"));
72966       }else{
72967         dest.eDest = SRT_Exists;
72968         sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm);
72969         VdbeComment((v, "Init EXISTS result"));
72970       }
72971       sqlite3ExprDelete(pParse->db, pSel->pLimit);
72972       pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
72973                                   &sqlite3IntTokens[1]);
72974       pSel->iLimit = 0;
72975       if( sqlite3Select(pParse, pSel, &dest) ){
72976         return 0;
72977       }
72978       rReg = dest.iParm;
72979       ExprSetIrreducible(pExpr);
72980       break;
72981     }
72982   }
72983
72984   if( testAddr ){
72985     sqlite3VdbeJumpHere(v, testAddr-1);
72986   }
72987   sqlite3ExprCachePop(pParse, 1);
72988
72989   return rReg;
72990 }
72991 #endif /* SQLITE_OMIT_SUBQUERY */
72992
72993 #ifndef SQLITE_OMIT_SUBQUERY
72994 /*
72995 ** Generate code for an IN expression.
72996 **
72997 **      x IN (SELECT ...)
72998 **      x IN (value, value, ...)
72999 **
73000 ** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
73001 ** is an array of zero or more values.  The expression is true if the LHS is
73002 ** contained within the RHS.  The value of the expression is unknown (NULL)
73003 ** if the LHS is NULL or if the LHS is not contained within the RHS and the
73004 ** RHS contains one or more NULL values.
73005 **
73006 ** This routine generates code will jump to destIfFalse if the LHS is not 
73007 ** contained within the RHS.  If due to NULLs we cannot determine if the LHS
73008 ** is contained in the RHS then jump to destIfNull.  If the LHS is contained
73009 ** within the RHS then fall through.
73010 */
73011 static void sqlite3ExprCodeIN(
73012   Parse *pParse,        /* Parsing and code generating context */
73013   Expr *pExpr,          /* The IN expression */
73014   int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
73015   int destIfNull        /* Jump here if the results are unknown due to NULLs */
73016 ){
73017   int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
73018   char affinity;        /* Comparison affinity to use */
73019   int eType;            /* Type of the RHS */
73020   int r1;               /* Temporary use register */
73021   Vdbe *v;              /* Statement under construction */
73022
73023   /* Compute the RHS.   After this step, the table with cursor
73024   ** pExpr->iTable will contains the values that make up the RHS.
73025   */
73026   v = pParse->pVdbe;
73027   assert( v!=0 );       /* OOM detected prior to this routine */
73028   VdbeNoopComment((v, "begin IN expr"));
73029   eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
73030
73031   /* Figure out the affinity to use to create a key from the results
73032   ** of the expression. affinityStr stores a static string suitable for
73033   ** P4 of OP_MakeRecord.
73034   */
73035   affinity = comparisonAffinity(pExpr);
73036
73037   /* Code the LHS, the <expr> from "<expr> IN (...)".
73038   */
73039   sqlite3ExprCachePush(pParse);
73040   r1 = sqlite3GetTempReg(pParse);
73041   sqlite3ExprCode(pParse, pExpr->pLeft, r1);
73042
73043   /* If the LHS is NULL, then the result is either false or NULL depending
73044   ** on whether the RHS is empty or not, respectively.
73045   */
73046   if( destIfNull==destIfFalse ){
73047     /* Shortcut for the common case where the false and NULL outcomes are
73048     ** the same. */
73049     sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
73050   }else{
73051     int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1);
73052     sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
73053     sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
73054     sqlite3VdbeJumpHere(v, addr1);
73055   }
73056
73057   if( eType==IN_INDEX_ROWID ){
73058     /* In this case, the RHS is the ROWID of table b-tree
73059     */
73060     sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
73061     sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
73062   }else{
73063     /* In this case, the RHS is an index b-tree.
73064     */
73065     sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
73066
73067     /* If the set membership test fails, then the result of the 
73068     ** "x IN (...)" expression must be either 0 or NULL. If the set
73069     ** contains no NULL values, then the result is 0. If the set 
73070     ** contains one or more NULL values, then the result of the
73071     ** expression is also NULL.
73072     */
73073     if( rRhsHasNull==0 || destIfFalse==destIfNull ){
73074       /* This branch runs if it is known at compile time that the RHS
73075       ** cannot contain NULL values. This happens as the result
73076       ** of a "NOT NULL" constraint in the database schema.
73077       **
73078       ** Also run this branch if NULL is equivalent to FALSE
73079       ** for this particular IN operator.
73080       */
73081       sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
73082
73083     }else{
73084       /* In this branch, the RHS of the IN might contain a NULL and
73085       ** the presence of a NULL on the RHS makes a difference in the
73086       ** outcome.
73087       */
73088       int j1, j2, j3;
73089
73090       /* First check to see if the LHS is contained in the RHS.  If so,
73091       ** then the presence of NULLs in the RHS does not matter, so jump
73092       ** over all of the code that follows.
73093       */
73094       j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
73095
73096       /* Here we begin generating code that runs if the LHS is not
73097       ** contained within the RHS.  Generate additional code that
73098       ** tests the RHS for NULLs.  If the RHS contains a NULL then
73099       ** jump to destIfNull.  If there are no NULLs in the RHS then
73100       ** jump to destIfFalse.
73101       */
73102       j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
73103       j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
73104       sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
73105       sqlite3VdbeJumpHere(v, j3);
73106       sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
73107       sqlite3VdbeJumpHere(v, j2);
73108
73109       /* Jump to the appropriate target depending on whether or not
73110       ** the RHS contains a NULL
73111       */
73112       sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
73113       sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
73114
73115       /* The OP_Found at the top of this branch jumps here when true, 
73116       ** causing the overall IN expression evaluation to fall through.
73117       */
73118       sqlite3VdbeJumpHere(v, j1);
73119     }
73120   }
73121   sqlite3ReleaseTempReg(pParse, r1);
73122   sqlite3ExprCachePop(pParse, 1);
73123   VdbeComment((v, "end IN expr"));
73124 }
73125 #endif /* SQLITE_OMIT_SUBQUERY */
73126
73127 /*
73128 ** Duplicate an 8-byte value
73129 */
73130 static char *dup8bytes(Vdbe *v, const char *in){
73131   char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
73132   if( out ){
73133     memcpy(out, in, 8);
73134   }
73135   return out;
73136 }
73137
73138 #ifndef SQLITE_OMIT_FLOATING_POINT
73139 /*
73140 ** Generate an instruction that will put the floating point
73141 ** value described by z[0..n-1] into register iMem.
73142 **
73143 ** The z[] string will probably not be zero-terminated.  But the 
73144 ** z[n] character is guaranteed to be something that does not look
73145 ** like the continuation of the number.
73146 */
73147 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
73148   if( ALWAYS(z!=0) ){
73149     double value;
73150     char *zV;
73151     sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
73152     assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
73153     if( negateFlag ) value = -value;
73154     zV = dup8bytes(v, (char*)&value);
73155     sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
73156   }
73157 }
73158 #endif
73159
73160
73161 /*
73162 ** Generate an instruction that will put the integer describe by
73163 ** text z[0..n-1] into register iMem.
73164 **
73165 ** Expr.u.zToken is always UTF8 and zero-terminated.
73166 */
73167 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
73168   Vdbe *v = pParse->pVdbe;
73169   if( pExpr->flags & EP_IntValue ){
73170     int i = pExpr->u.iValue;
73171     assert( i>=0 );
73172     if( negFlag ) i = -i;
73173     sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
73174   }else{
73175     int c;
73176     i64 value;
73177     const char *z = pExpr->u.zToken;
73178     assert( z!=0 );
73179     c = sqlite3Atoi64(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
73180     if( c==0 || (c==2 && negFlag) ){
73181       char *zV;
73182       if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
73183       zV = dup8bytes(v, (char*)&value);
73184       sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
73185     }else{
73186 #ifdef SQLITE_OMIT_FLOATING_POINT
73187       sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
73188 #else
73189       codeReal(v, z, negFlag, iMem);
73190 #endif
73191     }
73192   }
73193 }
73194
73195 /*
73196 ** Clear a cache entry.
73197 */
73198 static void cacheEntryClear(Parse *pParse, struct yColCache *p){
73199   if( p->tempReg ){
73200     if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
73201       pParse->aTempReg[pParse->nTempReg++] = p->iReg;
73202     }
73203     p->tempReg = 0;
73204   }
73205 }
73206
73207
73208 /*
73209 ** Record in the column cache that a particular column from a
73210 ** particular table is stored in a particular register.
73211 */
73212 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
73213   int i;
73214   int minLru;
73215   int idxLru;
73216   struct yColCache *p;
73217
73218   assert( iReg>0 );  /* Register numbers are always positive */
73219   assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
73220
73221   /* The SQLITE_ColumnCache flag disables the column cache.  This is used
73222   ** for testing only - to verify that SQLite always gets the same answer
73223   ** with and without the column cache.
73224   */
73225   if( pParse->db->flags & SQLITE_ColumnCache ) return;
73226
73227   /* First replace any existing entry.
73228   **
73229   ** Actually, the way the column cache is currently used, we are guaranteed
73230   ** that the object will never already be in cache.  Verify this guarantee.
73231   */
73232 #ifndef NDEBUG
73233   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
73234 #if 0 /* This code wold remove the entry from the cache if it existed */
73235     if( p->iReg && p->iTable==iTab && p->iColumn==iCol ){
73236       cacheEntryClear(pParse, p);
73237       p->iLevel = pParse->iCacheLevel;
73238       p->iReg = iReg;
73239       p->lru = pParse->iCacheCnt++;
73240       return;
73241     }
73242 #endif
73243     assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
73244   }
73245 #endif
73246
73247   /* Find an empty slot and replace it */
73248   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
73249     if( p->iReg==0 ){
73250       p->iLevel = pParse->iCacheLevel;
73251       p->iTable = iTab;
73252       p->iColumn = iCol;
73253       p->iReg = iReg;
73254       p->tempReg = 0;
73255       p->lru = pParse->iCacheCnt++;
73256       return;
73257     }
73258   }
73259
73260   /* Replace the last recently used */
73261   minLru = 0x7fffffff;
73262   idxLru = -1;
73263   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
73264     if( p->lru<minLru ){
73265       idxLru = i;
73266       minLru = p->lru;
73267     }
73268   }
73269   if( ALWAYS(idxLru>=0) ){
73270     p = &pParse->aColCache[idxLru];
73271     p->iLevel = pParse->iCacheLevel;
73272     p->iTable = iTab;
73273     p->iColumn = iCol;
73274     p->iReg = iReg;
73275     p->tempReg = 0;
73276     p->lru = pParse->iCacheCnt++;
73277     return;
73278   }
73279 }
73280
73281 /*
73282 ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
73283 ** Purge the range of registers from the column cache.
73284 */
73285 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
73286   int i;
73287   int iLast = iReg + nReg - 1;
73288   struct yColCache *p;
73289   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
73290     int r = p->iReg;
73291     if( r>=iReg && r<=iLast ){
73292       cacheEntryClear(pParse, p);
73293       p->iReg = 0;
73294     }
73295   }
73296 }
73297
73298 /*
73299 ** Remember the current column cache context.  Any new entries added
73300 ** added to the column cache after this call are removed when the
73301 ** corresponding pop occurs.
73302 */
73303 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
73304   pParse->iCacheLevel++;
73305 }
73306
73307 /*
73308 ** Remove from the column cache any entries that were added since the
73309 ** the previous N Push operations.  In other words, restore the cache
73310 ** to the state it was in N Pushes ago.
73311 */
73312 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse, int N){
73313   int i;
73314   struct yColCache *p;
73315   assert( N>0 );
73316   assert( pParse->iCacheLevel>=N );
73317   pParse->iCacheLevel -= N;
73318   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
73319     if( p->iReg && p->iLevel>pParse->iCacheLevel ){
73320       cacheEntryClear(pParse, p);
73321       p->iReg = 0;
73322     }
73323   }
73324 }
73325
73326 /*
73327 ** When a cached column is reused, make sure that its register is
73328 ** no longer available as a temp register.  ticket #3879:  that same
73329 ** register might be in the cache in multiple places, so be sure to
73330 ** get them all.
73331 */
73332 static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
73333   int i;
73334   struct yColCache *p;
73335   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
73336     if( p->iReg==iReg ){
73337       p->tempReg = 0;
73338     }
73339   }
73340 }
73341
73342 /*
73343 ** Generate code to extract the value of the iCol-th column of a table.
73344 */
73345 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
73346   Vdbe *v,        /* The VDBE under construction */
73347   Table *pTab,    /* The table containing the value */
73348   int iTabCur,    /* The cursor for this table */
73349   int iCol,       /* Index of the column to extract */
73350   int regOut      /* Extract the valud into this register */
73351 ){
73352   if( iCol<0 || iCol==pTab->iPKey ){
73353     sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
73354   }else{
73355     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
73356     sqlite3VdbeAddOp3(v, op, iTabCur, iCol, regOut);
73357   }
73358   if( iCol>=0 ){
73359     sqlite3ColumnDefault(v, pTab, iCol, regOut);
73360   }
73361 }
73362
73363 /*
73364 ** Generate code that will extract the iColumn-th column from
73365 ** table pTab and store the column value in a register.  An effort
73366 ** is made to store the column value in register iReg, but this is
73367 ** not guaranteed.  The location of the column value is returned.
73368 **
73369 ** There must be an open cursor to pTab in iTable when this routine
73370 ** is called.  If iColumn<0 then code is generated that extracts the rowid.
73371 */
73372 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
73373   Parse *pParse,   /* Parsing and code generating context */
73374   Table *pTab,     /* Description of the table we are reading from */
73375   int iColumn,     /* Index of the table column */
73376   int iTable,      /* The cursor pointing to the table */
73377   int iReg         /* Store results here */
73378 ){
73379   Vdbe *v = pParse->pVdbe;
73380   int i;
73381   struct yColCache *p;
73382
73383   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
73384     if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
73385       p->lru = pParse->iCacheCnt++;
73386       sqlite3ExprCachePinRegister(pParse, p->iReg);
73387       return p->iReg;
73388     }
73389   }  
73390   assert( v!=0 );
73391   sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
73392   sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
73393   return iReg;
73394 }
73395
73396 /*
73397 ** Clear all column cache entries.
73398 */
73399 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
73400   int i;
73401   struct yColCache *p;
73402
73403   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
73404     if( p->iReg ){
73405       cacheEntryClear(pParse, p);
73406       p->iReg = 0;
73407     }
73408   }
73409 }
73410
73411 /*
73412 ** Record the fact that an affinity change has occurred on iCount
73413 ** registers starting with iStart.
73414 */
73415 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
73416   sqlite3ExprCacheRemove(pParse, iStart, iCount);
73417 }
73418
73419 /*
73420 ** Generate code to move content from registers iFrom...iFrom+nReg-1
73421 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
73422 */
73423 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
73424   int i;
73425   struct yColCache *p;
73426   if( NEVER(iFrom==iTo) ) return;
73427   sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
73428   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
73429     int x = p->iReg;
73430     if( x>=iFrom && x<iFrom+nReg ){
73431       p->iReg += iTo-iFrom;
73432     }
73433   }
73434 }
73435
73436 /*
73437 ** Generate code to copy content from registers iFrom...iFrom+nReg-1
73438 ** over to iTo..iTo+nReg-1.
73439 */
73440 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, int iFrom, int iTo, int nReg){
73441   int i;
73442   if( NEVER(iFrom==iTo) ) return;
73443   for(i=0; i<nReg; i++){
73444     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, iFrom+i, iTo+i);
73445   }
73446 }
73447
73448 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
73449 /*
73450 ** Return true if any register in the range iFrom..iTo (inclusive)
73451 ** is used as part of the column cache.
73452 **
73453 ** This routine is used within assert() and testcase() macros only
73454 ** and does not appear in a normal build.
73455 */
73456 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
73457   int i;
73458   struct yColCache *p;
73459   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
73460     int r = p->iReg;
73461     if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
73462   }
73463   return 0;
73464 }
73465 #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
73466
73467 /*
73468 ** Generate code into the current Vdbe to evaluate the given
73469 ** expression.  Attempt to store the results in register "target".
73470 ** Return the register where results are stored.
73471 **
73472 ** With this routine, there is no guarantee that results will
73473 ** be stored in target.  The result might be stored in some other
73474 ** register if it is convenient to do so.  The calling function
73475 ** must check the return code and move the results to the desired
73476 ** register.
73477 */
73478 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
73479   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
73480   int op;                   /* The opcode being coded */
73481   int inReg = target;       /* Results stored in register inReg */
73482   int regFree1 = 0;         /* If non-zero free this temporary register */
73483   int regFree2 = 0;         /* If non-zero free this temporary register */
73484   int r1, r2, r3, r4;       /* Various register numbers */
73485   sqlite3 *db = pParse->db; /* The database connection */
73486
73487   assert( target>0 && target<=pParse->nMem );
73488   if( v==0 ){
73489     assert( pParse->db->mallocFailed );
73490     return 0;
73491   }
73492
73493   if( pExpr==0 ){
73494     op = TK_NULL;
73495   }else{
73496     op = pExpr->op;
73497   }
73498   switch( op ){
73499     case TK_AGG_COLUMN: {
73500       AggInfo *pAggInfo = pExpr->pAggInfo;
73501       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
73502       if( !pAggInfo->directMode ){
73503         assert( pCol->iMem>0 );
73504         inReg = pCol->iMem;
73505         break;
73506       }else if( pAggInfo->useSortingIdx ){
73507         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdx,
73508                               pCol->iSorterColumn, target);
73509         break;
73510       }
73511       /* Otherwise, fall thru into the TK_COLUMN case */
73512     }
73513     case TK_COLUMN: {
73514       if( pExpr->iTable<0 ){
73515         /* This only happens when coding check constraints */
73516         assert( pParse->ckBase>0 );
73517         inReg = pExpr->iColumn + pParse->ckBase;
73518       }else{
73519         inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
73520                                  pExpr->iColumn, pExpr->iTable, target);
73521       }
73522       break;
73523     }
73524     case TK_INTEGER: {
73525       codeInteger(pParse, pExpr, 0, target);
73526       break;
73527     }
73528 #ifndef SQLITE_OMIT_FLOATING_POINT
73529     case TK_FLOAT: {
73530       assert( !ExprHasProperty(pExpr, EP_IntValue) );
73531       codeReal(v, pExpr->u.zToken, 0, target);
73532       break;
73533     }
73534 #endif
73535     case TK_STRING: {
73536       assert( !ExprHasProperty(pExpr, EP_IntValue) );
73537       sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
73538       break;
73539     }
73540     case TK_NULL: {
73541       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
73542       break;
73543     }
73544 #ifndef SQLITE_OMIT_BLOB_LITERAL
73545     case TK_BLOB: {
73546       int n;
73547       const char *z;
73548       char *zBlob;
73549       assert( !ExprHasProperty(pExpr, EP_IntValue) );
73550       assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
73551       assert( pExpr->u.zToken[1]=='\'' );
73552       z = &pExpr->u.zToken[2];
73553       n = sqlite3Strlen30(z) - 1;
73554       assert( z[n]=='\'' );
73555       zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
73556       sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
73557       break;
73558     }
73559 #endif
73560     case TK_VARIABLE: {
73561       assert( !ExprHasProperty(pExpr, EP_IntValue) );
73562       assert( pExpr->u.zToken!=0 );
73563       assert( pExpr->u.zToken[0]!=0 );
73564       sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
73565       if( pExpr->u.zToken[1]!=0 ){
73566         assert( pExpr->u.zToken[0]=='?' 
73567              || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
73568         sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
73569       }
73570       break;
73571     }
73572     case TK_REGISTER: {
73573       inReg = pExpr->iTable;
73574       break;
73575     }
73576     case TK_AS: {
73577       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
73578       break;
73579     }
73580 #ifndef SQLITE_OMIT_CAST
73581     case TK_CAST: {
73582       /* Expressions of the form:   CAST(pLeft AS token) */
73583       int aff, to_op;
73584       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
73585       assert( !ExprHasProperty(pExpr, EP_IntValue) );
73586       aff = sqlite3AffinityType(pExpr->u.zToken);
73587       to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
73588       assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
73589       assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
73590       assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
73591       assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
73592       assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
73593       testcase( to_op==OP_ToText );
73594       testcase( to_op==OP_ToBlob );
73595       testcase( to_op==OP_ToNumeric );
73596       testcase( to_op==OP_ToInt );
73597       testcase( to_op==OP_ToReal );
73598       if( inReg!=target ){
73599         sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
73600         inReg = target;
73601       }
73602       sqlite3VdbeAddOp1(v, to_op, inReg);
73603       testcase( usedAsColumnCache(pParse, inReg, inReg) );
73604       sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
73605       break;
73606     }
73607 #endif /* SQLITE_OMIT_CAST */
73608     case TK_LT:
73609     case TK_LE:
73610     case TK_GT:
73611     case TK_GE:
73612     case TK_NE:
73613     case TK_EQ: {
73614       assert( TK_LT==OP_Lt );
73615       assert( TK_LE==OP_Le );
73616       assert( TK_GT==OP_Gt );
73617       assert( TK_GE==OP_Ge );
73618       assert( TK_EQ==OP_Eq );
73619       assert( TK_NE==OP_Ne );
73620       testcase( op==TK_LT );
73621       testcase( op==TK_LE );
73622       testcase( op==TK_GT );
73623       testcase( op==TK_GE );
73624       testcase( op==TK_EQ );
73625       testcase( op==TK_NE );
73626       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
73627       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
73628       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
73629                   r1, r2, inReg, SQLITE_STOREP2);
73630       testcase( regFree1==0 );
73631       testcase( regFree2==0 );
73632       break;
73633     }
73634     case TK_IS:
73635     case TK_ISNOT: {
73636       testcase( op==TK_IS );
73637       testcase( op==TK_ISNOT );
73638       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
73639       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
73640       op = (op==TK_IS) ? TK_EQ : TK_NE;
73641       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
73642                   r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
73643       testcase( regFree1==0 );
73644       testcase( regFree2==0 );
73645       break;
73646     }
73647     case TK_AND:
73648     case TK_OR:
73649     case TK_PLUS:
73650     case TK_STAR:
73651     case TK_MINUS:
73652     case TK_REM:
73653     case TK_BITAND:
73654     case TK_BITOR:
73655     case TK_SLASH:
73656     case TK_LSHIFT:
73657     case TK_RSHIFT: 
73658     case TK_CONCAT: {
73659       assert( TK_AND==OP_And );
73660       assert( TK_OR==OP_Or );
73661       assert( TK_PLUS==OP_Add );
73662       assert( TK_MINUS==OP_Subtract );
73663       assert( TK_REM==OP_Remainder );
73664       assert( TK_BITAND==OP_BitAnd );
73665       assert( TK_BITOR==OP_BitOr );
73666       assert( TK_SLASH==OP_Divide );
73667       assert( TK_LSHIFT==OP_ShiftLeft );
73668       assert( TK_RSHIFT==OP_ShiftRight );
73669       assert( TK_CONCAT==OP_Concat );
73670       testcase( op==TK_AND );
73671       testcase( op==TK_OR );
73672       testcase( op==TK_PLUS );
73673       testcase( op==TK_MINUS );
73674       testcase( op==TK_REM );
73675       testcase( op==TK_BITAND );
73676       testcase( op==TK_BITOR );
73677       testcase( op==TK_SLASH );
73678       testcase( op==TK_LSHIFT );
73679       testcase( op==TK_RSHIFT );
73680       testcase( op==TK_CONCAT );
73681       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
73682       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
73683       sqlite3VdbeAddOp3(v, op, r2, r1, target);
73684       testcase( regFree1==0 );
73685       testcase( regFree2==0 );
73686       break;
73687     }
73688     case TK_UMINUS: {
73689       Expr *pLeft = pExpr->pLeft;
73690       assert( pLeft );
73691       if( pLeft->op==TK_INTEGER ){
73692         codeInteger(pParse, pLeft, 1, target);
73693 #ifndef SQLITE_OMIT_FLOATING_POINT
73694       }else if( pLeft->op==TK_FLOAT ){
73695         assert( !ExprHasProperty(pExpr, EP_IntValue) );
73696         codeReal(v, pLeft->u.zToken, 1, target);
73697 #endif
73698       }else{
73699         regFree1 = r1 = sqlite3GetTempReg(pParse);
73700         sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
73701         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
73702         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
73703         testcase( regFree2==0 );
73704       }
73705       inReg = target;
73706       break;
73707     }
73708     case TK_BITNOT:
73709     case TK_NOT: {
73710       assert( TK_BITNOT==OP_BitNot );
73711       assert( TK_NOT==OP_Not );
73712       testcase( op==TK_BITNOT );
73713       testcase( op==TK_NOT );
73714       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
73715       testcase( regFree1==0 );
73716       inReg = target;
73717       sqlite3VdbeAddOp2(v, op, r1, inReg);
73718       break;
73719     }
73720     case TK_ISNULL:
73721     case TK_NOTNULL: {
73722       int addr;
73723       assert( TK_ISNULL==OP_IsNull );
73724       assert( TK_NOTNULL==OP_NotNull );
73725       testcase( op==TK_ISNULL );
73726       testcase( op==TK_NOTNULL );
73727       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
73728       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
73729       testcase( regFree1==0 );
73730       addr = sqlite3VdbeAddOp1(v, op, r1);
73731       sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
73732       sqlite3VdbeJumpHere(v, addr);
73733       break;
73734     }
73735     case TK_AGG_FUNCTION: {
73736       AggInfo *pInfo = pExpr->pAggInfo;
73737       if( pInfo==0 ){
73738         assert( !ExprHasProperty(pExpr, EP_IntValue) );
73739         sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
73740       }else{
73741         inReg = pInfo->aFunc[pExpr->iAgg].iMem;
73742       }
73743       break;
73744     }
73745     case TK_CONST_FUNC:
73746     case TK_FUNCTION: {
73747       ExprList *pFarg;       /* List of function arguments */
73748       int nFarg;             /* Number of function arguments */
73749       FuncDef *pDef;         /* The function definition object */
73750       int nId;               /* Length of the function name in bytes */
73751       const char *zId;       /* The function name */
73752       int constMask = 0;     /* Mask of function arguments that are constant */
73753       int i;                 /* Loop counter */
73754       u8 enc = ENC(db);      /* The text encoding used by this database */
73755       CollSeq *pColl = 0;    /* A collating sequence */
73756
73757       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
73758       testcase( op==TK_CONST_FUNC );
73759       testcase( op==TK_FUNCTION );
73760       if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
73761         pFarg = 0;
73762       }else{
73763         pFarg = pExpr->x.pList;
73764       }
73765       nFarg = pFarg ? pFarg->nExpr : 0;
73766       assert( !ExprHasProperty(pExpr, EP_IntValue) );
73767       zId = pExpr->u.zToken;
73768       nId = sqlite3Strlen30(zId);
73769       pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
73770       if( pDef==0 ){
73771         sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
73772         break;
73773       }
73774
73775       /* Attempt a direct implementation of the built-in COALESCE() and
73776       ** IFNULL() functions.  This avoids unnecessary evalation of
73777       ** arguments past the first non-NULL argument.
73778       */
73779       if( pDef->flags & SQLITE_FUNC_COALESCE ){
73780         int endCoalesce = sqlite3VdbeMakeLabel(v);
73781         assert( nFarg>=2 );
73782         sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
73783         for(i=1; i<nFarg; i++){
73784           sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
73785           sqlite3ExprCacheRemove(pParse, target, 1);
73786           sqlite3ExprCachePush(pParse);
73787           sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
73788           sqlite3ExprCachePop(pParse, 1);
73789         }
73790         sqlite3VdbeResolveLabel(v, endCoalesce);
73791         break;
73792       }
73793
73794
73795       if( pFarg ){
73796         r1 = sqlite3GetTempRange(pParse, nFarg);
73797         sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
73798         sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
73799         sqlite3ExprCachePop(pParse, 1);   /* Ticket 2ea2425d34be */
73800       }else{
73801         r1 = 0;
73802       }
73803 #ifndef SQLITE_OMIT_VIRTUALTABLE
73804       /* Possibly overload the function if the first argument is
73805       ** a virtual table column.
73806       **
73807       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
73808       ** second argument, not the first, as the argument to test to
73809       ** see if it is a column in a virtual table.  This is done because
73810       ** the left operand of infix functions (the operand we want to
73811       ** control overloading) ends up as the second argument to the
73812       ** function.  The expression "A glob B" is equivalent to 
73813       ** "glob(B,A).  We want to use the A in "A glob B" to test
73814       ** for function overloading.  But we use the B term in "glob(B,A)".
73815       */
73816       if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
73817         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
73818       }else if( nFarg>0 ){
73819         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
73820       }
73821 #endif
73822       for(i=0; i<nFarg; i++){
73823         if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
73824           constMask |= (1<<i);
73825         }
73826         if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
73827           pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
73828         }
73829       }
73830       if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
73831         if( !pColl ) pColl = db->pDfltColl; 
73832         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
73833       }
73834       sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
73835                         (char*)pDef, P4_FUNCDEF);
73836       sqlite3VdbeChangeP5(v, (u8)nFarg);
73837       if( nFarg ){
73838         sqlite3ReleaseTempRange(pParse, r1, nFarg);
73839       }
73840       break;
73841     }
73842 #ifndef SQLITE_OMIT_SUBQUERY
73843     case TK_EXISTS:
73844     case TK_SELECT: {
73845       testcase( op==TK_EXISTS );
73846       testcase( op==TK_SELECT );
73847       inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
73848       break;
73849     }
73850     case TK_IN: {
73851       int destIfFalse = sqlite3VdbeMakeLabel(v);
73852       int destIfNull = sqlite3VdbeMakeLabel(v);
73853       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
73854       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
73855       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
73856       sqlite3VdbeResolveLabel(v, destIfFalse);
73857       sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
73858       sqlite3VdbeResolveLabel(v, destIfNull);
73859       break;
73860     }
73861 #endif /* SQLITE_OMIT_SUBQUERY */
73862
73863
73864     /*
73865     **    x BETWEEN y AND z
73866     **
73867     ** This is equivalent to
73868     **
73869     **    x>=y AND x<=z
73870     **
73871     ** X is stored in pExpr->pLeft.
73872     ** Y is stored in pExpr->pList->a[0].pExpr.
73873     ** Z is stored in pExpr->pList->a[1].pExpr.
73874     */
73875     case TK_BETWEEN: {
73876       Expr *pLeft = pExpr->pLeft;
73877       struct ExprList_item *pLItem = pExpr->x.pList->a;
73878       Expr *pRight = pLItem->pExpr;
73879
73880       r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
73881       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
73882       testcase( regFree1==0 );
73883       testcase( regFree2==0 );
73884       r3 = sqlite3GetTempReg(pParse);
73885       r4 = sqlite3GetTempReg(pParse);
73886       codeCompare(pParse, pLeft, pRight, OP_Ge,
73887                   r1, r2, r3, SQLITE_STOREP2);
73888       pLItem++;
73889       pRight = pLItem->pExpr;
73890       sqlite3ReleaseTempReg(pParse, regFree2);
73891       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
73892       testcase( regFree2==0 );
73893       codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
73894       sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
73895       sqlite3ReleaseTempReg(pParse, r3);
73896       sqlite3ReleaseTempReg(pParse, r4);
73897       break;
73898     }
73899     case TK_UPLUS: {
73900       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
73901       break;
73902     }
73903
73904     case TK_TRIGGER: {
73905       /* If the opcode is TK_TRIGGER, then the expression is a reference
73906       ** to a column in the new.* or old.* pseudo-tables available to
73907       ** trigger programs. In this case Expr.iTable is set to 1 for the
73908       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
73909       ** is set to the column of the pseudo-table to read, or to -1 to
73910       ** read the rowid field.
73911       **
73912       ** The expression is implemented using an OP_Param opcode. The p1
73913       ** parameter is set to 0 for an old.rowid reference, or to (i+1)
73914       ** to reference another column of the old.* pseudo-table, where 
73915       ** i is the index of the column. For a new.rowid reference, p1 is
73916       ** set to (n+1), where n is the number of columns in each pseudo-table.
73917       ** For a reference to any other column in the new.* pseudo-table, p1
73918       ** is set to (n+2+i), where n and i are as defined previously. For
73919       ** example, if the table on which triggers are being fired is
73920       ** declared as:
73921       **
73922       **   CREATE TABLE t1(a, b);
73923       **
73924       ** Then p1 is interpreted as follows:
73925       **
73926       **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
73927       **   p1==1   ->    old.a         p1==4   ->    new.a
73928       **   p1==2   ->    old.b         p1==5   ->    new.b       
73929       */
73930       Table *pTab = pExpr->pTab;
73931       int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
73932
73933       assert( pExpr->iTable==0 || pExpr->iTable==1 );
73934       assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
73935       assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
73936       assert( p1>=0 && p1<(pTab->nCol*2+2) );
73937
73938       sqlite3VdbeAddOp2(v, OP_Param, p1, target);
73939       VdbeComment((v, "%s.%s -> $%d",
73940         (pExpr->iTable ? "new" : "old"),
73941         (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
73942         target
73943       ));
73944
73945 #ifndef SQLITE_OMIT_FLOATING_POINT
73946       /* If the column has REAL affinity, it may currently be stored as an
73947       ** integer. Use OP_RealAffinity to make sure it is really real.  */
73948       if( pExpr->iColumn>=0 
73949        && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
73950       ){
73951         sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
73952       }
73953 #endif
73954       break;
73955     }
73956
73957
73958     /*
73959     ** Form A:
73960     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
73961     **
73962     ** Form B:
73963     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
73964     **
73965     ** Form A is can be transformed into the equivalent form B as follows:
73966     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
73967     **        WHEN x=eN THEN rN ELSE y END
73968     **
73969     ** X (if it exists) is in pExpr->pLeft.
73970     ** Y is in pExpr->pRight.  The Y is also optional.  If there is no
73971     ** ELSE clause and no other term matches, then the result of the
73972     ** exprssion is NULL.
73973     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
73974     **
73975     ** The result of the expression is the Ri for the first matching Ei,
73976     ** or if there is no matching Ei, the ELSE term Y, or if there is
73977     ** no ELSE term, NULL.
73978     */
73979     default: assert( op==TK_CASE ); {
73980       int endLabel;                     /* GOTO label for end of CASE stmt */
73981       int nextCase;                     /* GOTO label for next WHEN clause */
73982       int nExpr;                        /* 2x number of WHEN terms */
73983       int i;                            /* Loop counter */
73984       ExprList *pEList;                 /* List of WHEN terms */
73985       struct ExprList_item *aListelem;  /* Array of WHEN terms */
73986       Expr opCompare;                   /* The X==Ei expression */
73987       Expr cacheX;                      /* Cached expression X */
73988       Expr *pX;                         /* The X expression */
73989       Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
73990       VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
73991
73992       assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
73993       assert((pExpr->x.pList->nExpr % 2) == 0);
73994       assert(pExpr->x.pList->nExpr > 0);
73995       pEList = pExpr->x.pList;
73996       aListelem = pEList->a;
73997       nExpr = pEList->nExpr;
73998       endLabel = sqlite3VdbeMakeLabel(v);
73999       if( (pX = pExpr->pLeft)!=0 ){
74000         cacheX = *pX;
74001         testcase( pX->op==TK_COLUMN );
74002         testcase( pX->op==TK_REGISTER );
74003         cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
74004         testcase( regFree1==0 );
74005         cacheX.op = TK_REGISTER;
74006         opCompare.op = TK_EQ;
74007         opCompare.pLeft = &cacheX;
74008         pTest = &opCompare;
74009         /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
74010         ** The value in regFree1 might get SCopy-ed into the file result.
74011         ** So make sure that the regFree1 register is not reused for other
74012         ** purposes and possibly overwritten.  */
74013         regFree1 = 0;
74014       }
74015       for(i=0; i<nExpr; i=i+2){
74016         sqlite3ExprCachePush(pParse);
74017         if( pX ){
74018           assert( pTest!=0 );
74019           opCompare.pRight = aListelem[i].pExpr;
74020         }else{
74021           pTest = aListelem[i].pExpr;
74022         }
74023         nextCase = sqlite3VdbeMakeLabel(v);
74024         testcase( pTest->op==TK_COLUMN );
74025         sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
74026         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
74027         testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
74028         sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
74029         sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
74030         sqlite3ExprCachePop(pParse, 1);
74031         sqlite3VdbeResolveLabel(v, nextCase);
74032       }
74033       if( pExpr->pRight ){
74034         sqlite3ExprCachePush(pParse);
74035         sqlite3ExprCode(pParse, pExpr->pRight, target);
74036         sqlite3ExprCachePop(pParse, 1);
74037       }else{
74038         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
74039       }
74040       assert( db->mallocFailed || pParse->nErr>0 
74041            || pParse->iCacheLevel==iCacheLevel );
74042       sqlite3VdbeResolveLabel(v, endLabel);
74043       break;
74044     }
74045 #ifndef SQLITE_OMIT_TRIGGER
74046     case TK_RAISE: {
74047       assert( pExpr->affinity==OE_Rollback 
74048            || pExpr->affinity==OE_Abort
74049            || pExpr->affinity==OE_Fail
74050            || pExpr->affinity==OE_Ignore
74051       );
74052       if( !pParse->pTriggerTab ){
74053         sqlite3ErrorMsg(pParse,
74054                        "RAISE() may only be used within a trigger-program");
74055         return 0;
74056       }
74057       if( pExpr->affinity==OE_Abort ){
74058         sqlite3MayAbort(pParse);
74059       }
74060       assert( !ExprHasProperty(pExpr, EP_IntValue) );
74061       if( pExpr->affinity==OE_Ignore ){
74062         sqlite3VdbeAddOp4(
74063             v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
74064       }else{
74065         sqlite3HaltConstraint(pParse, pExpr->affinity, pExpr->u.zToken, 0);
74066       }
74067
74068       break;
74069     }
74070 #endif
74071   }
74072   sqlite3ReleaseTempReg(pParse, regFree1);
74073   sqlite3ReleaseTempReg(pParse, regFree2);
74074   return inReg;
74075 }
74076
74077 /*
74078 ** Generate code to evaluate an expression and store the results
74079 ** into a register.  Return the register number where the results
74080 ** are stored.
74081 **
74082 ** If the register is a temporary register that can be deallocated,
74083 ** then write its number into *pReg.  If the result register is not
74084 ** a temporary, then set *pReg to zero.
74085 */
74086 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
74087   int r1 = sqlite3GetTempReg(pParse);
74088   int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
74089   if( r2==r1 ){
74090     *pReg = r1;
74091   }else{
74092     sqlite3ReleaseTempReg(pParse, r1);
74093     *pReg = 0;
74094   }
74095   return r2;
74096 }
74097
74098 /*
74099 ** Generate code that will evaluate expression pExpr and store the
74100 ** results in register target.  The results are guaranteed to appear
74101 ** in register target.
74102 */
74103 SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
74104   int inReg;
74105
74106   assert( target>0 && target<=pParse->nMem );
74107   if( pExpr && pExpr->op==TK_REGISTER ){
74108     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
74109   }else{
74110     inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
74111     assert( pParse->pVdbe || pParse->db->mallocFailed );
74112     if( inReg!=target && pParse->pVdbe ){
74113       sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
74114     }
74115   }
74116   return target;
74117 }
74118
74119 /*
74120 ** Generate code that evalutes the given expression and puts the result
74121 ** in register target.
74122 **
74123 ** Also make a copy of the expression results into another "cache" register
74124 ** and modify the expression so that the next time it is evaluated,
74125 ** the result is a copy of the cache register.
74126 **
74127 ** This routine is used for expressions that are used multiple 
74128 ** times.  They are evaluated once and the results of the expression
74129 ** are reused.
74130 */
74131 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
74132   Vdbe *v = pParse->pVdbe;
74133   int inReg;
74134   inReg = sqlite3ExprCode(pParse, pExpr, target);
74135   assert( target>0 );
74136   /* This routine is called for terms to INSERT or UPDATE.  And the only
74137   ** other place where expressions can be converted into TK_REGISTER is
74138   ** in WHERE clause processing.  So as currently implemented, there is
74139   ** no way for a TK_REGISTER to exist here.  But it seems prudent to
74140   ** keep the ALWAYS() in case the conditions above change with future
74141   ** modifications or enhancements. */
74142   if( ALWAYS(pExpr->op!=TK_REGISTER) ){  
74143     int iMem;
74144     iMem = ++pParse->nMem;
74145     sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
74146     pExpr->iTable = iMem;
74147     pExpr->op2 = pExpr->op;
74148     pExpr->op = TK_REGISTER;
74149   }
74150   return inReg;
74151 }
74152
74153 /*
74154 ** Return TRUE if pExpr is an constant expression that is appropriate
74155 ** for factoring out of a loop.  Appropriate expressions are:
74156 **
74157 **    *  Any expression that evaluates to two or more opcodes.
74158 **
74159 **    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null, 
74160 **       or OP_Variable that does not need to be placed in a 
74161 **       specific register.
74162 **
74163 ** There is no point in factoring out single-instruction constant
74164 ** expressions that need to be placed in a particular register.  
74165 ** We could factor them out, but then we would end up adding an
74166 ** OP_SCopy instruction to move the value into the correct register
74167 ** later.  We might as well just use the original instruction and
74168 ** avoid the OP_SCopy.
74169 */
74170 static int isAppropriateForFactoring(Expr *p){
74171   if( !sqlite3ExprIsConstantNotJoin(p) ){
74172     return 0;  /* Only constant expressions are appropriate for factoring */
74173   }
74174   if( (p->flags & EP_FixedDest)==0 ){
74175     return 1;  /* Any constant without a fixed destination is appropriate */
74176   }
74177   while( p->op==TK_UPLUS ) p = p->pLeft;
74178   switch( p->op ){
74179 #ifndef SQLITE_OMIT_BLOB_LITERAL
74180     case TK_BLOB:
74181 #endif
74182     case TK_VARIABLE:
74183     case TK_INTEGER:
74184     case TK_FLOAT:
74185     case TK_NULL:
74186     case TK_STRING: {
74187       testcase( p->op==TK_BLOB );
74188       testcase( p->op==TK_VARIABLE );
74189       testcase( p->op==TK_INTEGER );
74190       testcase( p->op==TK_FLOAT );
74191       testcase( p->op==TK_NULL );
74192       testcase( p->op==TK_STRING );
74193       /* Single-instruction constants with a fixed destination are
74194       ** better done in-line.  If we factor them, they will just end
74195       ** up generating an OP_SCopy to move the value to the destination
74196       ** register. */
74197       return 0;
74198     }
74199     case TK_UMINUS: {
74200       if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
74201         return 0;
74202       }
74203       break;
74204     }
74205     default: {
74206       break;
74207     }
74208   }
74209   return 1;
74210 }
74211
74212 /*
74213 ** If pExpr is a constant expression that is appropriate for
74214 ** factoring out of a loop, then evaluate the expression
74215 ** into a register and convert the expression into a TK_REGISTER
74216 ** expression.
74217 */
74218 static int evalConstExpr(Walker *pWalker, Expr *pExpr){
74219   Parse *pParse = pWalker->pParse;
74220   switch( pExpr->op ){
74221     case TK_IN:
74222     case TK_REGISTER: {
74223       return WRC_Prune;
74224     }
74225     case TK_FUNCTION:
74226     case TK_AGG_FUNCTION:
74227     case TK_CONST_FUNC: {
74228       /* The arguments to a function have a fixed destination.
74229       ** Mark them this way to avoid generated unneeded OP_SCopy
74230       ** instructions. 
74231       */
74232       ExprList *pList = pExpr->x.pList;
74233       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
74234       if( pList ){
74235         int i = pList->nExpr;
74236         struct ExprList_item *pItem = pList->a;
74237         for(; i>0; i--, pItem++){
74238           if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
74239         }
74240       }
74241       break;
74242     }
74243   }
74244   if( isAppropriateForFactoring(pExpr) ){
74245     int r1 = ++pParse->nMem;
74246     int r2;
74247     r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
74248     if( NEVER(r1!=r2) ) sqlite3ReleaseTempReg(pParse, r1);
74249     pExpr->op2 = pExpr->op;
74250     pExpr->op = TK_REGISTER;
74251     pExpr->iTable = r2;
74252     return WRC_Prune;
74253   }
74254   return WRC_Continue;
74255 }
74256
74257 /*
74258 ** Preevaluate constant subexpressions within pExpr and store the
74259 ** results in registers.  Modify pExpr so that the constant subexpresions
74260 ** are TK_REGISTER opcodes that refer to the precomputed values.
74261 **
74262 ** This routine is a no-op if the jump to the cookie-check code has
74263 ** already occur.  Since the cookie-check jump is generated prior to
74264 ** any other serious processing, this check ensures that there is no
74265 ** way to accidently bypass the constant initializations.
74266 **
74267 ** This routine is also a no-op if the SQLITE_FactorOutConst optimization
74268 ** is disabled via the sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS)
74269 ** interface.  This allows test logic to verify that the same answer is
74270 ** obtained for queries regardless of whether or not constants are
74271 ** precomputed into registers or if they are inserted in-line.
74272 */
74273 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
74274   Walker w;
74275   if( pParse->cookieGoto ) return;
74276   if( (pParse->db->flags & SQLITE_FactorOutConst)!=0 ) return;
74277   w.xExprCallback = evalConstExpr;
74278   w.xSelectCallback = 0;
74279   w.pParse = pParse;
74280   sqlite3WalkExpr(&w, pExpr);
74281 }
74282
74283
74284 /*
74285 ** Generate code that pushes the value of every element of the given
74286 ** expression list into a sequence of registers beginning at target.
74287 **
74288 ** Return the number of elements evaluated.
74289 */
74290 SQLITE_PRIVATE int sqlite3ExprCodeExprList(
74291   Parse *pParse,     /* Parsing context */
74292   ExprList *pList,   /* The expression list to be coded */
74293   int target,        /* Where to write results */
74294   int doHardCopy     /* Make a hard copy of every element */
74295 ){
74296   struct ExprList_item *pItem;
74297   int i, n;
74298   assert( pList!=0 );
74299   assert( target>0 );
74300   assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
74301   n = pList->nExpr;
74302   for(pItem=pList->a, i=0; i<n; i++, pItem++){
74303     Expr *pExpr = pItem->pExpr;
74304     int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
74305     if( inReg!=target+i ){
74306       sqlite3VdbeAddOp2(pParse->pVdbe, doHardCopy ? OP_Copy : OP_SCopy,
74307                         inReg, target+i);
74308     }
74309   }
74310   return n;
74311 }
74312
74313 /*
74314 ** Generate code for a BETWEEN operator.
74315 **
74316 **    x BETWEEN y AND z
74317 **
74318 ** The above is equivalent to 
74319 **
74320 **    x>=y AND x<=z
74321 **
74322 ** Code it as such, taking care to do the common subexpression
74323 ** elementation of x.
74324 */
74325 static void exprCodeBetween(
74326   Parse *pParse,    /* Parsing and code generating context */
74327   Expr *pExpr,      /* The BETWEEN expression */
74328   int dest,         /* Jump here if the jump is taken */
74329   int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
74330   int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
74331 ){
74332   Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
74333   Expr compLeft;    /* The  x>=y  term */
74334   Expr compRight;   /* The  x<=z  term */
74335   Expr exprX;       /* The  x  subexpression */
74336   int regFree1 = 0; /* Temporary use register */
74337
74338   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
74339   exprX = *pExpr->pLeft;
74340   exprAnd.op = TK_AND;
74341   exprAnd.pLeft = &compLeft;
74342   exprAnd.pRight = &compRight;
74343   compLeft.op = TK_GE;
74344   compLeft.pLeft = &exprX;
74345   compLeft.pRight = pExpr->x.pList->a[0].pExpr;
74346   compRight.op = TK_LE;
74347   compRight.pLeft = &exprX;
74348   compRight.pRight = pExpr->x.pList->a[1].pExpr;
74349   exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
74350   exprX.op = TK_REGISTER;
74351   if( jumpIfTrue ){
74352     sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
74353   }else{
74354     sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
74355   }
74356   sqlite3ReleaseTempReg(pParse, regFree1);
74357
74358   /* Ensure adequate test coverage */
74359   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
74360   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
74361   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
74362   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
74363   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
74364   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
74365   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
74366   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
74367 }
74368
74369 /*
74370 ** Generate code for a boolean expression such that a jump is made
74371 ** to the label "dest" if the expression is true but execution
74372 ** continues straight thru if the expression is false.
74373 **
74374 ** If the expression evaluates to NULL (neither true nor false), then
74375 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
74376 **
74377 ** This code depends on the fact that certain token values (ex: TK_EQ)
74378 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
74379 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
74380 ** the make process cause these values to align.  Assert()s in the code
74381 ** below verify that the numbers are aligned correctly.
74382 */
74383 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
74384   Vdbe *v = pParse->pVdbe;
74385   int op = 0;
74386   int regFree1 = 0;
74387   int regFree2 = 0;
74388   int r1, r2;
74389
74390   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
74391   if( NEVER(v==0) )     return;  /* Existance of VDBE checked by caller */
74392   if( NEVER(pExpr==0) ) return;  /* No way this can happen */
74393   op = pExpr->op;
74394   switch( op ){
74395     case TK_AND: {
74396       int d2 = sqlite3VdbeMakeLabel(v);
74397       testcase( jumpIfNull==0 );
74398       sqlite3ExprCachePush(pParse);
74399       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
74400       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
74401       sqlite3VdbeResolveLabel(v, d2);
74402       sqlite3ExprCachePop(pParse, 1);
74403       break;
74404     }
74405     case TK_OR: {
74406       testcase( jumpIfNull==0 );
74407       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
74408       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
74409       break;
74410     }
74411     case TK_NOT: {
74412       testcase( jumpIfNull==0 );
74413       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
74414       break;
74415     }
74416     case TK_LT:
74417     case TK_LE:
74418     case TK_GT:
74419     case TK_GE:
74420     case TK_NE:
74421     case TK_EQ: {
74422       assert( TK_LT==OP_Lt );
74423       assert( TK_LE==OP_Le );
74424       assert( TK_GT==OP_Gt );
74425       assert( TK_GE==OP_Ge );
74426       assert( TK_EQ==OP_Eq );
74427       assert( TK_NE==OP_Ne );
74428       testcase( op==TK_LT );
74429       testcase( op==TK_LE );
74430       testcase( op==TK_GT );
74431       testcase( op==TK_GE );
74432       testcase( op==TK_EQ );
74433       testcase( op==TK_NE );
74434       testcase( jumpIfNull==0 );
74435       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
74436       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
74437       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
74438                   r1, r2, dest, jumpIfNull);
74439       testcase( regFree1==0 );
74440       testcase( regFree2==0 );
74441       break;
74442     }
74443     case TK_IS:
74444     case TK_ISNOT: {
74445       testcase( op==TK_IS );
74446       testcase( op==TK_ISNOT );
74447       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
74448       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
74449       op = (op==TK_IS) ? TK_EQ : TK_NE;
74450       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
74451                   r1, r2, dest, SQLITE_NULLEQ);
74452       testcase( regFree1==0 );
74453       testcase( regFree2==0 );
74454       break;
74455     }
74456     case TK_ISNULL:
74457     case TK_NOTNULL: {
74458       assert( TK_ISNULL==OP_IsNull );
74459       assert( TK_NOTNULL==OP_NotNull );
74460       testcase( op==TK_ISNULL );
74461       testcase( op==TK_NOTNULL );
74462       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
74463       sqlite3VdbeAddOp2(v, op, r1, dest);
74464       testcase( regFree1==0 );
74465       break;
74466     }
74467     case TK_BETWEEN: {
74468       testcase( jumpIfNull==0 );
74469       exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
74470       break;
74471     }
74472 #ifndef SQLITE_OMIT_SUBQUERY
74473     case TK_IN: {
74474       int destIfFalse = sqlite3VdbeMakeLabel(v);
74475       int destIfNull = jumpIfNull ? dest : destIfFalse;
74476       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
74477       sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
74478       sqlite3VdbeResolveLabel(v, destIfFalse);
74479       break;
74480     }
74481 #endif
74482     default: {
74483       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
74484       sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
74485       testcase( regFree1==0 );
74486       testcase( jumpIfNull==0 );
74487       break;
74488     }
74489   }
74490   sqlite3ReleaseTempReg(pParse, regFree1);
74491   sqlite3ReleaseTempReg(pParse, regFree2);  
74492 }
74493
74494 /*
74495 ** Generate code for a boolean expression such that a jump is made
74496 ** to the label "dest" if the expression is false but execution
74497 ** continues straight thru if the expression is true.
74498 **
74499 ** If the expression evaluates to NULL (neither true nor false) then
74500 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
74501 ** is 0.
74502 */
74503 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
74504   Vdbe *v = pParse->pVdbe;
74505   int op = 0;
74506   int regFree1 = 0;
74507   int regFree2 = 0;
74508   int r1, r2;
74509
74510   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
74511   if( NEVER(v==0) ) return; /* Existance of VDBE checked by caller */
74512   if( pExpr==0 )    return;
74513
74514   /* The value of pExpr->op and op are related as follows:
74515   **
74516   **       pExpr->op            op
74517   **       ---------          ----------
74518   **       TK_ISNULL          OP_NotNull
74519   **       TK_NOTNULL         OP_IsNull
74520   **       TK_NE              OP_Eq
74521   **       TK_EQ              OP_Ne
74522   **       TK_GT              OP_Le
74523   **       TK_LE              OP_Gt
74524   **       TK_GE              OP_Lt
74525   **       TK_LT              OP_Ge
74526   **
74527   ** For other values of pExpr->op, op is undefined and unused.
74528   ** The value of TK_ and OP_ constants are arranged such that we
74529   ** can compute the mapping above using the following expression.
74530   ** Assert()s verify that the computation is correct.
74531   */
74532   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
74533
74534   /* Verify correct alignment of TK_ and OP_ constants
74535   */
74536   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
74537   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
74538   assert( pExpr->op!=TK_NE || op==OP_Eq );
74539   assert( pExpr->op!=TK_EQ || op==OP_Ne );
74540   assert( pExpr->op!=TK_LT || op==OP_Ge );
74541   assert( pExpr->op!=TK_LE || op==OP_Gt );
74542   assert( pExpr->op!=TK_GT || op==OP_Le );
74543   assert( pExpr->op!=TK_GE || op==OP_Lt );
74544
74545   switch( pExpr->op ){
74546     case TK_AND: {
74547       testcase( jumpIfNull==0 );
74548       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
74549       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
74550       break;
74551     }
74552     case TK_OR: {
74553       int d2 = sqlite3VdbeMakeLabel(v);
74554       testcase( jumpIfNull==0 );
74555       sqlite3ExprCachePush(pParse);
74556       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
74557       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
74558       sqlite3VdbeResolveLabel(v, d2);
74559       sqlite3ExprCachePop(pParse, 1);
74560       break;
74561     }
74562     case TK_NOT: {
74563       testcase( jumpIfNull==0 );
74564       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
74565       break;
74566     }
74567     case TK_LT:
74568     case TK_LE:
74569     case TK_GT:
74570     case TK_GE:
74571     case TK_NE:
74572     case TK_EQ: {
74573       testcase( op==TK_LT );
74574       testcase( op==TK_LE );
74575       testcase( op==TK_GT );
74576       testcase( op==TK_GE );
74577       testcase( op==TK_EQ );
74578       testcase( op==TK_NE );
74579       testcase( jumpIfNull==0 );
74580       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
74581       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
74582       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
74583                   r1, r2, dest, jumpIfNull);
74584       testcase( regFree1==0 );
74585       testcase( regFree2==0 );
74586       break;
74587     }
74588     case TK_IS:
74589     case TK_ISNOT: {
74590       testcase( pExpr->op==TK_IS );
74591       testcase( pExpr->op==TK_ISNOT );
74592       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
74593       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
74594       op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
74595       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
74596                   r1, r2, dest, SQLITE_NULLEQ);
74597       testcase( regFree1==0 );
74598       testcase( regFree2==0 );
74599       break;
74600     }
74601     case TK_ISNULL:
74602     case TK_NOTNULL: {
74603       testcase( op==TK_ISNULL );
74604       testcase( op==TK_NOTNULL );
74605       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
74606       sqlite3VdbeAddOp2(v, op, r1, dest);
74607       testcase( regFree1==0 );
74608       break;
74609     }
74610     case TK_BETWEEN: {
74611       testcase( jumpIfNull==0 );
74612       exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
74613       break;
74614     }
74615 #ifndef SQLITE_OMIT_SUBQUERY
74616     case TK_IN: {
74617       if( jumpIfNull ){
74618         sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
74619       }else{
74620         int destIfNull = sqlite3VdbeMakeLabel(v);
74621         sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
74622         sqlite3VdbeResolveLabel(v, destIfNull);
74623       }
74624       break;
74625     }
74626 #endif
74627     default: {
74628       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
74629       sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
74630       testcase( regFree1==0 );
74631       testcase( jumpIfNull==0 );
74632       break;
74633     }
74634   }
74635   sqlite3ReleaseTempReg(pParse, regFree1);
74636   sqlite3ReleaseTempReg(pParse, regFree2);
74637 }
74638
74639 /*
74640 ** Do a deep comparison of two expression trees.  Return 0 if the two
74641 ** expressions are completely identical.  Return 1 if they differ only
74642 ** by a COLLATE operator at the top level.  Return 2 if there are differences
74643 ** other than the top-level COLLATE operator.
74644 **
74645 ** Sometimes this routine will return 2 even if the two expressions
74646 ** really are equivalent.  If we cannot prove that the expressions are
74647 ** identical, we return 2 just to be safe.  So if this routine
74648 ** returns 2, then you do not really know for certain if the two
74649 ** expressions are the same.  But if you get a 0 or 1 return, then you
74650 ** can be sure the expressions are the same.  In the places where
74651 ** this routine is used, it does not hurt to get an extra 2 - that
74652 ** just might result in some slightly slower code.  But returning
74653 ** an incorrect 0 or 1 could lead to a malfunction.
74654 */
74655 SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
74656   if( pA==0||pB==0 ){
74657     return pB==pA ? 0 : 2;
74658   }
74659   assert( !ExprHasAnyProperty(pA, EP_TokenOnly|EP_Reduced) );
74660   assert( !ExprHasAnyProperty(pB, EP_TokenOnly|EP_Reduced) );
74661   if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
74662     return 2;
74663   }
74664   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
74665   if( pA->op!=pB->op ) return 2;
74666   if( sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 2;
74667   if( sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 2;
74668   if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList) ) return 2;
74669   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 2;
74670   if( ExprHasProperty(pA, EP_IntValue) ){
74671     if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
74672       return 2;
74673     }
74674   }else if( pA->op!=TK_COLUMN && pA->u.zToken ){
74675     if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2;
74676     if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ){
74677       return 2;
74678     }
74679   }
74680   if( (pA->flags & EP_ExpCollate)!=(pB->flags & EP_ExpCollate) ) return 1;
74681   if( (pA->flags & EP_ExpCollate)!=0 && pA->pColl!=pB->pColl ) return 2;
74682   return 0;
74683 }
74684
74685 /*
74686 ** Compare two ExprList objects.  Return 0 if they are identical and 
74687 ** non-zero if they differ in any way.
74688 **
74689 ** This routine might return non-zero for equivalent ExprLists.  The
74690 ** only consequence will be disabled optimizations.  But this routine
74691 ** must never return 0 if the two ExprList objects are different, or
74692 ** a malfunction will result.
74693 **
74694 ** Two NULL pointers are considered to be the same.  But a NULL pointer
74695 ** always differs from a non-NULL pointer.
74696 */
74697 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB){
74698   int i;
74699   if( pA==0 && pB==0 ) return 0;
74700   if( pA==0 || pB==0 ) return 1;
74701   if( pA->nExpr!=pB->nExpr ) return 1;
74702   for(i=0; i<pA->nExpr; i++){
74703     Expr *pExprA = pA->a[i].pExpr;
74704     Expr *pExprB = pB->a[i].pExpr;
74705     if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
74706     if( sqlite3ExprCompare(pExprA, pExprB) ) return 1;
74707   }
74708   return 0;
74709 }
74710
74711 /*
74712 ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
74713 ** the new element.  Return a negative number if malloc fails.
74714 */
74715 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
74716   int i;
74717   pInfo->aCol = sqlite3ArrayAllocate(
74718        db,
74719        pInfo->aCol,
74720        sizeof(pInfo->aCol[0]),
74721        3,
74722        &pInfo->nColumn,
74723        &pInfo->nColumnAlloc,
74724        &i
74725   );
74726   return i;
74727 }    
74728
74729 /*
74730 ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
74731 ** the new element.  Return a negative number if malloc fails.
74732 */
74733 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
74734   int i;
74735   pInfo->aFunc = sqlite3ArrayAllocate(
74736        db, 
74737        pInfo->aFunc,
74738        sizeof(pInfo->aFunc[0]),
74739        3,
74740        &pInfo->nFunc,
74741        &pInfo->nFuncAlloc,
74742        &i
74743   );
74744   return i;
74745 }    
74746
74747 /*
74748 ** This is the xExprCallback for a tree walker.  It is used to
74749 ** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
74750 ** for additional information.
74751 */
74752 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
74753   int i;
74754   NameContext *pNC = pWalker->u.pNC;
74755   Parse *pParse = pNC->pParse;
74756   SrcList *pSrcList = pNC->pSrcList;
74757   AggInfo *pAggInfo = pNC->pAggInfo;
74758
74759   switch( pExpr->op ){
74760     case TK_AGG_COLUMN:
74761     case TK_COLUMN: {
74762       testcase( pExpr->op==TK_AGG_COLUMN );
74763       testcase( pExpr->op==TK_COLUMN );
74764       /* Check to see if the column is in one of the tables in the FROM
74765       ** clause of the aggregate query */
74766       if( ALWAYS(pSrcList!=0) ){
74767         struct SrcList_item *pItem = pSrcList->a;
74768         for(i=0; i<pSrcList->nSrc; i++, pItem++){
74769           struct AggInfo_col *pCol;
74770           assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
74771           if( pExpr->iTable==pItem->iCursor ){
74772             /* If we reach this point, it means that pExpr refers to a table
74773             ** that is in the FROM clause of the aggregate query.  
74774             **
74775             ** Make an entry for the column in pAggInfo->aCol[] if there
74776             ** is not an entry there already.
74777             */
74778             int k;
74779             pCol = pAggInfo->aCol;
74780             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
74781               if( pCol->iTable==pExpr->iTable &&
74782                   pCol->iColumn==pExpr->iColumn ){
74783                 break;
74784               }
74785             }
74786             if( (k>=pAggInfo->nColumn)
74787              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0 
74788             ){
74789               pCol = &pAggInfo->aCol[k];
74790               pCol->pTab = pExpr->pTab;
74791               pCol->iTable = pExpr->iTable;
74792               pCol->iColumn = pExpr->iColumn;
74793               pCol->iMem = ++pParse->nMem;
74794               pCol->iSorterColumn = -1;
74795               pCol->pExpr = pExpr;
74796               if( pAggInfo->pGroupBy ){
74797                 int j, n;
74798                 ExprList *pGB = pAggInfo->pGroupBy;
74799                 struct ExprList_item *pTerm = pGB->a;
74800                 n = pGB->nExpr;
74801                 for(j=0; j<n; j++, pTerm++){
74802                   Expr *pE = pTerm->pExpr;
74803                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
74804                       pE->iColumn==pExpr->iColumn ){
74805                     pCol->iSorterColumn = j;
74806                     break;
74807                   }
74808                 }
74809               }
74810               if( pCol->iSorterColumn<0 ){
74811                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
74812               }
74813             }
74814             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
74815             ** because it was there before or because we just created it).
74816             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
74817             ** pAggInfo->aCol[] entry.
74818             */
74819             ExprSetIrreducible(pExpr);
74820             pExpr->pAggInfo = pAggInfo;
74821             pExpr->op = TK_AGG_COLUMN;
74822             pExpr->iAgg = (i16)k;
74823             break;
74824           } /* endif pExpr->iTable==pItem->iCursor */
74825         } /* end loop over pSrcList */
74826       }
74827       return WRC_Prune;
74828     }
74829     case TK_AGG_FUNCTION: {
74830       /* The pNC->nDepth==0 test causes aggregate functions in subqueries
74831       ** to be ignored */
74832       if( pNC->nDepth==0 ){
74833         /* Check to see if pExpr is a duplicate of another aggregate 
74834         ** function that is already in the pAggInfo structure
74835         */
74836         struct AggInfo_func *pItem = pAggInfo->aFunc;
74837         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
74838           if( sqlite3ExprCompare(pItem->pExpr, pExpr)==0 ){
74839             break;
74840           }
74841         }
74842         if( i>=pAggInfo->nFunc ){
74843           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
74844           */
74845           u8 enc = ENC(pParse->db);
74846           i = addAggInfoFunc(pParse->db, pAggInfo);
74847           if( i>=0 ){
74848             assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
74849             pItem = &pAggInfo->aFunc[i];
74850             pItem->pExpr = pExpr;
74851             pItem->iMem = ++pParse->nMem;
74852             assert( !ExprHasProperty(pExpr, EP_IntValue) );
74853             pItem->pFunc = sqlite3FindFunction(pParse->db,
74854                    pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
74855                    pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
74856             if( pExpr->flags & EP_Distinct ){
74857               pItem->iDistinct = pParse->nTab++;
74858             }else{
74859               pItem->iDistinct = -1;
74860             }
74861           }
74862         }
74863         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
74864         */
74865         assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
74866         ExprSetIrreducible(pExpr);
74867         pExpr->iAgg = (i16)i;
74868         pExpr->pAggInfo = pAggInfo;
74869         return WRC_Prune;
74870       }
74871     }
74872   }
74873   return WRC_Continue;
74874 }
74875 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
74876   NameContext *pNC = pWalker->u.pNC;
74877   if( pNC->nDepth==0 ){
74878     pNC->nDepth++;
74879     sqlite3WalkSelect(pWalker, pSelect);
74880     pNC->nDepth--;
74881     return WRC_Prune;
74882   }else{
74883     return WRC_Continue;
74884   }
74885 }
74886
74887 /*
74888 ** Analyze the given expression looking for aggregate functions and
74889 ** for variables that need to be added to the pParse->aAgg[] array.
74890 ** Make additional entries to the pParse->aAgg[] array as necessary.
74891 **
74892 ** This routine should only be called after the expression has been
74893 ** analyzed by sqlite3ResolveExprNames().
74894 */
74895 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
74896   Walker w;
74897   w.xExprCallback = analyzeAggregate;
74898   w.xSelectCallback = analyzeAggregatesInSelect;
74899   w.u.pNC = pNC;
74900   assert( pNC->pSrcList!=0 );
74901   sqlite3WalkExpr(&w, pExpr);
74902 }
74903
74904 /*
74905 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
74906 ** expression list.  Return the number of errors.
74907 **
74908 ** If an error is found, the analysis is cut short.
74909 */
74910 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
74911   struct ExprList_item *pItem;
74912   int i;
74913   if( pList ){
74914     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
74915       sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
74916     }
74917   }
74918 }
74919
74920 /*
74921 ** Allocate a single new register for use to hold some intermediate result.
74922 */
74923 SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
74924   if( pParse->nTempReg==0 ){
74925     return ++pParse->nMem;
74926   }
74927   return pParse->aTempReg[--pParse->nTempReg];
74928 }
74929
74930 /*
74931 ** Deallocate a register, making available for reuse for some other
74932 ** purpose.
74933 **
74934 ** If a register is currently being used by the column cache, then
74935 ** the dallocation is deferred until the column cache line that uses
74936 ** the register becomes stale.
74937 */
74938 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
74939   if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
74940     int i;
74941     struct yColCache *p;
74942     for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
74943       if( p->iReg==iReg ){
74944         p->tempReg = 1;
74945         return;
74946       }
74947     }
74948     pParse->aTempReg[pParse->nTempReg++] = iReg;
74949   }
74950 }
74951
74952 /*
74953 ** Allocate or deallocate a block of nReg consecutive registers
74954 */
74955 SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
74956   int i, n;
74957   i = pParse->iRangeReg;
74958   n = pParse->nRangeReg;
74959   if( nReg<=n ){
74960     assert( !usedAsColumnCache(pParse, i, i+n-1) );
74961     pParse->iRangeReg += nReg;
74962     pParse->nRangeReg -= nReg;
74963   }else{
74964     i = pParse->nMem+1;
74965     pParse->nMem += nReg;
74966   }
74967   return i;
74968 }
74969 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
74970   sqlite3ExprCacheRemove(pParse, iReg, nReg);
74971   if( nReg>pParse->nRangeReg ){
74972     pParse->nRangeReg = nReg;
74973     pParse->iRangeReg = iReg;
74974   }
74975 }
74976
74977 /************** End of expr.c ************************************************/
74978 /************** Begin file alter.c *******************************************/
74979 /*
74980 ** 2005 February 15
74981 **
74982 ** The author disclaims copyright to this source code.  In place of
74983 ** a legal notice, here is a blessing:
74984 **
74985 **    May you do good and not evil.
74986 **    May you find forgiveness for yourself and forgive others.
74987 **    May you share freely, never taking more than you give.
74988 **
74989 *************************************************************************
74990 ** This file contains C code routines that used to generate VDBE code
74991 ** that implements the ALTER TABLE command.
74992 */
74993
74994 /*
74995 ** The code in this file only exists if we are not omitting the
74996 ** ALTER TABLE logic from the build.
74997 */
74998 #ifndef SQLITE_OMIT_ALTERTABLE
74999
75000
75001 /*
75002 ** This function is used by SQL generated to implement the 
75003 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
75004 ** CREATE INDEX command. The second is a table name. The table name in 
75005 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
75006 ** argument and the result returned. Examples:
75007 **
75008 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
75009 **     -> 'CREATE TABLE def(a, b, c)'
75010 **
75011 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
75012 **     -> 'CREATE INDEX i ON def(a, b, c)'
75013 */
75014 static void renameTableFunc(
75015   sqlite3_context *context,
75016   int NotUsed,
75017   sqlite3_value **argv
75018 ){
75019   unsigned char const *zSql = sqlite3_value_text(argv[0]);
75020   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
75021
75022   int token;
75023   Token tname;
75024   unsigned char const *zCsr = zSql;
75025   int len = 0;
75026   char *zRet;
75027
75028   sqlite3 *db = sqlite3_context_db_handle(context);
75029
75030   UNUSED_PARAMETER(NotUsed);
75031
75032   /* The principle used to locate the table name in the CREATE TABLE 
75033   ** statement is that the table name is the first non-space token that
75034   ** is immediately followed by a TK_LP or TK_USING token.
75035   */
75036   if( zSql ){
75037     do {
75038       if( !*zCsr ){
75039         /* Ran out of input before finding an opening bracket. Return NULL. */
75040         return;
75041       }
75042
75043       /* Store the token that zCsr points to in tname. */
75044       tname.z = (char*)zCsr;
75045       tname.n = len;
75046
75047       /* Advance zCsr to the next token. Store that token type in 'token',
75048       ** and its length in 'len' (to be used next iteration of this loop).
75049       */
75050       do {
75051         zCsr += len;
75052         len = sqlite3GetToken(zCsr, &token);
75053       } while( token==TK_SPACE );
75054       assert( len>0 );
75055     } while( token!=TK_LP && token!=TK_USING );
75056
75057     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql, 
75058        zTableName, tname.z+tname.n);
75059     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
75060   }
75061 }
75062
75063 /*
75064 ** This C function implements an SQL user function that is used by SQL code
75065 ** generated by the ALTER TABLE ... RENAME command to modify the definition
75066 ** of any foreign key constraints that use the table being renamed as the 
75067 ** parent table. It is passed three arguments:
75068 **
75069 **   1) The complete text of the CREATE TABLE statement being modified,
75070 **   2) The old name of the table being renamed, and
75071 **   3) The new name of the table being renamed.
75072 **
75073 ** It returns the new CREATE TABLE statement. For example:
75074 **
75075 **   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
75076 **       -> 'CREATE TABLE t1(a REFERENCES t3)'
75077 */
75078 #ifndef SQLITE_OMIT_FOREIGN_KEY
75079 static void renameParentFunc(
75080   sqlite3_context *context,
75081   int NotUsed,
75082   sqlite3_value **argv
75083 ){
75084   sqlite3 *db = sqlite3_context_db_handle(context);
75085   char *zOutput = 0;
75086   char *zResult;
75087   unsigned char const *zInput = sqlite3_value_text(argv[0]);
75088   unsigned char const *zOld = sqlite3_value_text(argv[1]);
75089   unsigned char const *zNew = sqlite3_value_text(argv[2]);
75090
75091   unsigned const char *z;         /* Pointer to token */
75092   int n;                          /* Length of token z */
75093   int token;                      /* Type of token */
75094
75095   UNUSED_PARAMETER(NotUsed);
75096   for(z=zInput; *z; z=z+n){
75097     n = sqlite3GetToken(z, &token);
75098     if( token==TK_REFERENCES ){
75099       char *zParent;
75100       do {
75101         z += n;
75102         n = sqlite3GetToken(z, &token);
75103       }while( token==TK_SPACE );
75104
75105       zParent = sqlite3DbStrNDup(db, (const char *)z, n);
75106       if( zParent==0 ) break;
75107       sqlite3Dequote(zParent);
75108       if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
75109         char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"", 
75110             (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
75111         );
75112         sqlite3DbFree(db, zOutput);
75113         zOutput = zOut;
75114         zInput = &z[n];
75115       }
75116       sqlite3DbFree(db, zParent);
75117     }
75118   }
75119
75120   zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput), 
75121   sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
75122   sqlite3DbFree(db, zOutput);
75123 }
75124 #endif
75125
75126 #ifndef SQLITE_OMIT_TRIGGER
75127 /* This function is used by SQL generated to implement the
75128 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER 
75129 ** statement. The second is a table name. The table name in the CREATE 
75130 ** TRIGGER statement is replaced with the third argument and the result 
75131 ** returned. This is analagous to renameTableFunc() above, except for CREATE
75132 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
75133 */
75134 static void renameTriggerFunc(
75135   sqlite3_context *context,
75136   int NotUsed,
75137   sqlite3_value **argv
75138 ){
75139   unsigned char const *zSql = sqlite3_value_text(argv[0]);
75140   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
75141
75142   int token;
75143   Token tname;
75144   int dist = 3;
75145   unsigned char const *zCsr = zSql;
75146   int len = 0;
75147   char *zRet;
75148   sqlite3 *db = sqlite3_context_db_handle(context);
75149
75150   UNUSED_PARAMETER(NotUsed);
75151
75152   /* The principle used to locate the table name in the CREATE TRIGGER 
75153   ** statement is that the table name is the first token that is immediatedly
75154   ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
75155   ** of TK_WHEN, TK_BEGIN or TK_FOR.
75156   */
75157   if( zSql ){
75158     do {
75159
75160       if( !*zCsr ){
75161         /* Ran out of input before finding the table name. Return NULL. */
75162         return;
75163       }
75164
75165       /* Store the token that zCsr points to in tname. */
75166       tname.z = (char*)zCsr;
75167       tname.n = len;
75168
75169       /* Advance zCsr to the next token. Store that token type in 'token',
75170       ** and its length in 'len' (to be used next iteration of this loop).
75171       */
75172       do {
75173         zCsr += len;
75174         len = sqlite3GetToken(zCsr, &token);
75175       }while( token==TK_SPACE );
75176       assert( len>0 );
75177
75178       /* Variable 'dist' stores the number of tokens read since the most
75179       ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN 
75180       ** token is read and 'dist' equals 2, the condition stated above
75181       ** to be met.
75182       **
75183       ** Note that ON cannot be a database, table or column name, so
75184       ** there is no need to worry about syntax like 
75185       ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
75186       */
75187       dist++;
75188       if( token==TK_DOT || token==TK_ON ){
75189         dist = 0;
75190       }
75191     } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
75192
75193     /* Variable tname now contains the token that is the old table-name
75194     ** in the CREATE TRIGGER statement.
75195     */
75196     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql, 
75197        zTableName, tname.z+tname.n);
75198     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
75199   }
75200 }
75201 #endif   /* !SQLITE_OMIT_TRIGGER */
75202
75203 /*
75204 ** Register built-in functions used to help implement ALTER TABLE
75205 */
75206 SQLITE_PRIVATE void sqlite3AlterFunctions(void){
75207   static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
75208     FUNCTION(sqlite_rename_table,   2, 0, 0, renameTableFunc),
75209 #ifndef SQLITE_OMIT_TRIGGER
75210     FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
75211 #endif
75212 #ifndef SQLITE_OMIT_FOREIGN_KEY
75213     FUNCTION(sqlite_rename_parent,  3, 0, 0, renameParentFunc),
75214 #endif
75215   };
75216   int i;
75217   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
75218   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
75219
75220   for(i=0; i<ArraySize(aAlterTableFuncs); i++){
75221     sqlite3FuncDefInsert(pHash, &aFunc[i]);
75222   }
75223 }
75224
75225 /*
75226 ** This function is used to create the text of expressions of the form:
75227 **
75228 **   name=<constant1> OR name=<constant2> OR ...
75229 **
75230 ** If argument zWhere is NULL, then a pointer string containing the text 
75231 ** "name=<constant>" is returned, where <constant> is the quoted version
75232 ** of the string passed as argument zConstant. The returned buffer is
75233 ** allocated using sqlite3DbMalloc(). It is the responsibility of the
75234 ** caller to ensure that it is eventually freed.
75235 **
75236 ** If argument zWhere is not NULL, then the string returned is 
75237 ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
75238 ** In this case zWhere is passed to sqlite3DbFree() before returning.
75239 ** 
75240 */
75241 static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
75242   char *zNew;
75243   if( !zWhere ){
75244     zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
75245   }else{
75246     zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
75247     sqlite3DbFree(db, zWhere);
75248   }
75249   return zNew;
75250 }
75251
75252 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
75253 /*
75254 ** Generate the text of a WHERE expression which can be used to select all
75255 ** tables that have foreign key constraints that refer to table pTab (i.e.
75256 ** constraints for which pTab is the parent table) from the sqlite_master
75257 ** table.
75258 */
75259 static char *whereForeignKeys(Parse *pParse, Table *pTab){
75260   FKey *p;
75261   char *zWhere = 0;
75262   for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
75263     zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
75264   }
75265   return zWhere;
75266 }
75267 #endif
75268
75269 /*
75270 ** Generate the text of a WHERE expression which can be used to select all
75271 ** temporary triggers on table pTab from the sqlite_temp_master table. If
75272 ** table pTab has no temporary triggers, or is itself stored in the 
75273 ** temporary database, NULL is returned.
75274 */
75275 static char *whereTempTriggers(Parse *pParse, Table *pTab){
75276   Trigger *pTrig;
75277   char *zWhere = 0;
75278   const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
75279
75280   /* If the table is not located in the temp-db (in which case NULL is 
75281   ** returned, loop through the tables list of triggers. For each trigger
75282   ** that is not part of the temp-db schema, add a clause to the WHERE 
75283   ** expression being built up in zWhere.
75284   */
75285   if( pTab->pSchema!=pTempSchema ){
75286     sqlite3 *db = pParse->db;
75287     for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
75288       if( pTrig->pSchema==pTempSchema ){
75289         zWhere = whereOrName(db, zWhere, pTrig->zName);
75290       }
75291     }
75292   }
75293   if( zWhere ){
75294     char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
75295     sqlite3DbFree(pParse->db, zWhere);
75296     zWhere = zNew;
75297   }
75298   return zWhere;
75299 }
75300
75301 /*
75302 ** Generate code to drop and reload the internal representation of table
75303 ** pTab from the database, including triggers and temporary triggers.
75304 ** Argument zName is the name of the table in the database schema at
75305 ** the time the generated code is executed. This can be different from
75306 ** pTab->zName if this function is being called to code part of an 
75307 ** "ALTER TABLE RENAME TO" statement.
75308 */
75309 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
75310   Vdbe *v;
75311   char *zWhere;
75312   int iDb;                   /* Index of database containing pTab */
75313 #ifndef SQLITE_OMIT_TRIGGER
75314   Trigger *pTrig;
75315 #endif
75316
75317   v = sqlite3GetVdbe(pParse);
75318   if( NEVER(v==0) ) return;
75319   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
75320   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
75321   assert( iDb>=0 );
75322
75323 #ifndef SQLITE_OMIT_TRIGGER
75324   /* Drop any table triggers from the internal schema. */
75325   for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
75326     int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
75327     assert( iTrigDb==iDb || iTrigDb==1 );
75328     sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
75329   }
75330 #endif
75331
75332   /* Drop the table and index from the internal schema.  */
75333   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
75334
75335   /* Reload the table, index and permanent trigger schemas. */
75336   zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
75337   if( !zWhere ) return;
75338   sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
75339
75340 #ifndef SQLITE_OMIT_TRIGGER
75341   /* Now, if the table is not stored in the temp database, reload any temp 
75342   ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined. 
75343   */
75344   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
75345     sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
75346   }
75347 #endif
75348 }
75349
75350 /*
75351 ** Parameter zName is the name of a table that is about to be altered
75352 ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
75353 ** If the table is a system table, this function leaves an error message
75354 ** in pParse->zErr (system tables may not be altered) and returns non-zero.
75355 **
75356 ** Or, if zName is not a system table, zero is returned.
75357 */
75358 static int isSystemTable(Parse *pParse, const char *zName){
75359   if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
75360     sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
75361     return 1;
75362   }
75363   return 0;
75364 }
75365
75366 /*
75367 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy" 
75368 ** command. 
75369 */
75370 SQLITE_PRIVATE void sqlite3AlterRenameTable(
75371   Parse *pParse,            /* Parser context. */
75372   SrcList *pSrc,            /* The table to rename. */
75373   Token *pName              /* The new table name. */
75374 ){
75375   int iDb;                  /* Database that contains the table */
75376   char *zDb;                /* Name of database iDb */
75377   Table *pTab;              /* Table being renamed */
75378   char *zName = 0;          /* NULL-terminated version of pName */ 
75379   sqlite3 *db = pParse->db; /* Database connection */
75380   int nTabName;             /* Number of UTF-8 characters in zTabName */
75381   const char *zTabName;     /* Original name of the table */
75382   Vdbe *v;
75383 #ifndef SQLITE_OMIT_TRIGGER
75384   char *zWhere = 0;         /* Where clause to locate temp triggers */
75385 #endif
75386   VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
75387   int savedDbFlags;         /* Saved value of db->flags */
75388
75389   savedDbFlags = db->flags;  
75390   if( NEVER(db->mallocFailed) ) goto exit_rename_table;
75391   assert( pSrc->nSrc==1 );
75392   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
75393
75394   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
75395   if( !pTab ) goto exit_rename_table;
75396   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
75397   zDb = db->aDb[iDb].zName;
75398   db->flags |= SQLITE_PreferBuiltin;
75399
75400   /* Get a NULL terminated version of the new table name. */
75401   zName = sqlite3NameFromToken(db, pName);
75402   if( !zName ) goto exit_rename_table;
75403
75404   /* Check that a table or index named 'zName' does not already exist
75405   ** in database iDb. If so, this is an error.
75406   */
75407   if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
75408     sqlite3ErrorMsg(pParse, 
75409         "there is already another table or index with this name: %s", zName);
75410     goto exit_rename_table;
75411   }
75412
75413   /* Make sure it is not a system table being altered, or a reserved name
75414   ** that the table is being renamed to.
75415   */
75416   if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
75417     goto exit_rename_table;
75418   }
75419   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
75420     exit_rename_table;
75421   }
75422
75423 #ifndef SQLITE_OMIT_VIEW
75424   if( pTab->pSelect ){
75425     sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
75426     goto exit_rename_table;
75427   }
75428 #endif
75429
75430 #ifndef SQLITE_OMIT_AUTHORIZATION
75431   /* Invoke the authorization callback. */
75432   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
75433     goto exit_rename_table;
75434   }
75435 #endif
75436
75437 #ifndef SQLITE_OMIT_VIRTUALTABLE
75438   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
75439     goto exit_rename_table;
75440   }
75441   if( IsVirtual(pTab) ){
75442     pVTab = sqlite3GetVTable(db, pTab);
75443     if( pVTab->pVtab->pModule->xRename==0 ){
75444       pVTab = 0;
75445     }
75446   }
75447 #endif
75448
75449   /* Begin a transaction and code the VerifyCookie for database iDb. 
75450   ** Then modify the schema cookie (since the ALTER TABLE modifies the
75451   ** schema). Open a statement transaction if the table is a virtual
75452   ** table.
75453   */
75454   v = sqlite3GetVdbe(pParse);
75455   if( v==0 ){
75456     goto exit_rename_table;
75457   }
75458   sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
75459   sqlite3ChangeCookie(pParse, iDb);
75460
75461   /* If this is a virtual table, invoke the xRename() function if
75462   ** one is defined. The xRename() callback will modify the names
75463   ** of any resources used by the v-table implementation (including other
75464   ** SQLite tables) that are identified by the name of the virtual table.
75465   */
75466 #ifndef SQLITE_OMIT_VIRTUALTABLE
75467   if( pVTab ){
75468     int i = ++pParse->nMem;
75469     sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
75470     sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
75471     sqlite3MayAbort(pParse);
75472   }
75473 #endif
75474
75475   /* figure out how many UTF-8 characters are in zName */
75476   zTabName = pTab->zName;
75477   nTabName = sqlite3Utf8CharLen(zTabName, -1);
75478
75479 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
75480   if( db->flags&SQLITE_ForeignKeys ){
75481     /* If foreign-key support is enabled, rewrite the CREATE TABLE 
75482     ** statements corresponding to all child tables of foreign key constraints
75483     ** for which the renamed table is the parent table.  */
75484     if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
75485       sqlite3NestedParse(pParse, 
75486           "UPDATE \"%w\".%s SET "
75487               "sql = sqlite_rename_parent(sql, %Q, %Q) "
75488               "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
75489       sqlite3DbFree(db, zWhere);
75490     }
75491   }
75492 #endif
75493
75494   /* Modify the sqlite_master table to use the new table name. */
75495   sqlite3NestedParse(pParse,
75496       "UPDATE %Q.%s SET "
75497 #ifdef SQLITE_OMIT_TRIGGER
75498           "sql = sqlite_rename_table(sql, %Q), "
75499 #else
75500           "sql = CASE "
75501             "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
75502             "ELSE sqlite_rename_table(sql, %Q) END, "
75503 #endif
75504           "tbl_name = %Q, "
75505           "name = CASE "
75506             "WHEN type='table' THEN %Q "
75507             "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
75508              "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
75509             "ELSE name END "
75510       "WHERE tbl_name=%Q AND "
75511           "(type='table' OR type='index' OR type='trigger');", 
75512       zDb, SCHEMA_TABLE(iDb), zName, zName, zName, 
75513 #ifndef SQLITE_OMIT_TRIGGER
75514       zName,
75515 #endif
75516       zName, nTabName, zTabName
75517   );
75518
75519 #ifndef SQLITE_OMIT_AUTOINCREMENT
75520   /* If the sqlite_sequence table exists in this database, then update 
75521   ** it with the new table name.
75522   */
75523   if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
75524     sqlite3NestedParse(pParse,
75525         "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
75526         zDb, zName, pTab->zName);
75527   }
75528 #endif
75529
75530 #ifndef SQLITE_OMIT_TRIGGER
75531   /* If there are TEMP triggers on this table, modify the sqlite_temp_master
75532   ** table. Don't do this if the table being ALTERed is itself located in
75533   ** the temp database.
75534   */
75535   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
75536     sqlite3NestedParse(pParse, 
75537         "UPDATE sqlite_temp_master SET "
75538             "sql = sqlite_rename_trigger(sql, %Q), "
75539             "tbl_name = %Q "
75540             "WHERE %s;", zName, zName, zWhere);
75541     sqlite3DbFree(db, zWhere);
75542   }
75543 #endif
75544
75545 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
75546   if( db->flags&SQLITE_ForeignKeys ){
75547     FKey *p;
75548     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
75549       Table *pFrom = p->pFrom;
75550       if( pFrom!=pTab ){
75551         reloadTableSchema(pParse, p->pFrom, pFrom->zName);
75552       }
75553     }
75554   }
75555 #endif
75556
75557   /* Drop and reload the internal table schema. */
75558   reloadTableSchema(pParse, pTab, zName);
75559
75560 exit_rename_table:
75561   sqlite3SrcListDelete(db, pSrc);
75562   sqlite3DbFree(db, zName);
75563   db->flags = savedDbFlags;
75564 }
75565
75566
75567 /*
75568 ** Generate code to make sure the file format number is at least minFormat.
75569 ** The generated code will increase the file format number if necessary.
75570 */
75571 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
75572   Vdbe *v;
75573   v = sqlite3GetVdbe(pParse);
75574   /* The VDBE should have been allocated before this routine is called.
75575   ** If that allocation failed, we would have quit before reaching this
75576   ** point */
75577   if( ALWAYS(v) ){
75578     int r1 = sqlite3GetTempReg(pParse);
75579     int r2 = sqlite3GetTempReg(pParse);
75580     int j1;
75581     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
75582     sqlite3VdbeUsesBtree(v, iDb);
75583     sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
75584     j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
75585     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
75586     sqlite3VdbeJumpHere(v, j1);
75587     sqlite3ReleaseTempReg(pParse, r1);
75588     sqlite3ReleaseTempReg(pParse, r2);
75589   }
75590 }
75591
75592 /*
75593 ** This function is called after an "ALTER TABLE ... ADD" statement
75594 ** has been parsed. Argument pColDef contains the text of the new
75595 ** column definition.
75596 **
75597 ** The Table structure pParse->pNewTable was extended to include
75598 ** the new column during parsing.
75599 */
75600 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
75601   Table *pNew;              /* Copy of pParse->pNewTable */
75602   Table *pTab;              /* Table being altered */
75603   int iDb;                  /* Database number */
75604   const char *zDb;          /* Database name */
75605   const char *zTab;         /* Table name */
75606   char *zCol;               /* Null-terminated column definition */
75607   Column *pCol;             /* The new column */
75608   Expr *pDflt;              /* Default value for the new column */
75609   sqlite3 *db;              /* The database connection; */
75610
75611   db = pParse->db;
75612   if( pParse->nErr || db->mallocFailed ) return;
75613   pNew = pParse->pNewTable;
75614   assert( pNew );
75615
75616   assert( sqlite3BtreeHoldsAllMutexes(db) );
75617   iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
75618   zDb = db->aDb[iDb].zName;
75619   zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
75620   pCol = &pNew->aCol[pNew->nCol-1];
75621   pDflt = pCol->pDflt;
75622   pTab = sqlite3FindTable(db, zTab, zDb);
75623   assert( pTab );
75624
75625 #ifndef SQLITE_OMIT_AUTHORIZATION
75626   /* Invoke the authorization callback. */
75627   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
75628     return;
75629   }
75630 #endif
75631
75632   /* If the default value for the new column was specified with a 
75633   ** literal NULL, then set pDflt to 0. This simplifies checking
75634   ** for an SQL NULL default below.
75635   */
75636   if( pDflt && pDflt->op==TK_NULL ){
75637     pDflt = 0;
75638   }
75639
75640   /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
75641   ** If there is a NOT NULL constraint, then the default value for the
75642   ** column must not be NULL.
75643   */
75644   if( pCol->isPrimKey ){
75645     sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
75646     return;
75647   }
75648   if( pNew->pIndex ){
75649     sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
75650     return;
75651   }
75652   if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
75653     sqlite3ErrorMsg(pParse, 
75654         "Cannot add a REFERENCES column with non-NULL default value");
75655     return;
75656   }
75657   if( pCol->notNull && !pDflt ){
75658     sqlite3ErrorMsg(pParse, 
75659         "Cannot add a NOT NULL column with default value NULL");
75660     return;
75661   }
75662
75663   /* Ensure the default expression is something that sqlite3ValueFromExpr()
75664   ** can handle (i.e. not CURRENT_TIME etc.)
75665   */
75666   if( pDflt ){
75667     sqlite3_value *pVal;
75668     if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
75669       db->mallocFailed = 1;
75670       return;
75671     }
75672     if( !pVal ){
75673       sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
75674       return;
75675     }
75676     sqlite3ValueFree(pVal);
75677   }
75678
75679   /* Modify the CREATE TABLE statement. */
75680   zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
75681   if( zCol ){
75682     char *zEnd = &zCol[pColDef->n-1];
75683     int savedDbFlags = db->flags;
75684     while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
75685       *zEnd-- = '\0';
75686     }
75687     db->flags |= SQLITE_PreferBuiltin;
75688     sqlite3NestedParse(pParse, 
75689         "UPDATE \"%w\".%s SET "
75690           "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
75691         "WHERE type = 'table' AND name = %Q", 
75692       zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
75693       zTab
75694     );
75695     sqlite3DbFree(db, zCol);
75696     db->flags = savedDbFlags;
75697   }
75698
75699   /* If the default value of the new column is NULL, then set the file
75700   ** format to 2. If the default value of the new column is not NULL,
75701   ** the file format becomes 3.
75702   */
75703   sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
75704
75705   /* Reload the schema of the modified table. */
75706   reloadTableSchema(pParse, pTab, pTab->zName);
75707 }
75708
75709 /*
75710 ** This function is called by the parser after the table-name in
75711 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument 
75712 ** pSrc is the full-name of the table being altered.
75713 **
75714 ** This routine makes a (partial) copy of the Table structure
75715 ** for the table being altered and sets Parse.pNewTable to point
75716 ** to it. Routines called by the parser as the column definition
75717 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to 
75718 ** the copy. The copy of the Table structure is deleted by tokenize.c 
75719 ** after parsing is finished.
75720 **
75721 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
75722 ** coding the "ALTER TABLE ... ADD" statement.
75723 */
75724 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
75725   Table *pNew;
75726   Table *pTab;
75727   Vdbe *v;
75728   int iDb;
75729   int i;
75730   int nAlloc;
75731   sqlite3 *db = pParse->db;
75732
75733   /* Look up the table being altered. */
75734   assert( pParse->pNewTable==0 );
75735   assert( sqlite3BtreeHoldsAllMutexes(db) );
75736   if( db->mallocFailed ) goto exit_begin_add_column;
75737   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
75738   if( !pTab ) goto exit_begin_add_column;
75739
75740 #ifndef SQLITE_OMIT_VIRTUALTABLE
75741   if( IsVirtual(pTab) ){
75742     sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
75743     goto exit_begin_add_column;
75744   }
75745 #endif
75746
75747   /* Make sure this is not an attempt to ALTER a view. */
75748   if( pTab->pSelect ){
75749     sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
75750     goto exit_begin_add_column;
75751   }
75752   if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
75753     goto exit_begin_add_column;
75754   }
75755
75756   assert( pTab->addColOffset>0 );
75757   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
75758
75759   /* Put a copy of the Table struct in Parse.pNewTable for the
75760   ** sqlite3AddColumn() function and friends to modify.  But modify
75761   ** the name by adding an "sqlite_altertab_" prefix.  By adding this
75762   ** prefix, we insure that the name will not collide with an existing
75763   ** table because user table are not allowed to have the "sqlite_"
75764   ** prefix on their name.
75765   */
75766   pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
75767   if( !pNew ) goto exit_begin_add_column;
75768   pParse->pNewTable = pNew;
75769   pNew->nRef = 1;
75770   pNew->nCol = pTab->nCol;
75771   assert( pNew->nCol>0 );
75772   nAlloc = (((pNew->nCol-1)/8)*8)+8;
75773   assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
75774   pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
75775   pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
75776   if( !pNew->aCol || !pNew->zName ){
75777     db->mallocFailed = 1;
75778     goto exit_begin_add_column;
75779   }
75780   memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
75781   for(i=0; i<pNew->nCol; i++){
75782     Column *pCol = &pNew->aCol[i];
75783     pCol->zName = sqlite3DbStrDup(db, pCol->zName);
75784     pCol->zColl = 0;
75785     pCol->zType = 0;
75786     pCol->pDflt = 0;
75787     pCol->zDflt = 0;
75788   }
75789   pNew->pSchema = db->aDb[iDb].pSchema;
75790   pNew->addColOffset = pTab->addColOffset;
75791   pNew->nRef = 1;
75792
75793   /* Begin a transaction and increment the schema cookie.  */
75794   sqlite3BeginWriteOperation(pParse, 0, iDb);
75795   v = sqlite3GetVdbe(pParse);
75796   if( !v ) goto exit_begin_add_column;
75797   sqlite3ChangeCookie(pParse, iDb);
75798
75799 exit_begin_add_column:
75800   sqlite3SrcListDelete(db, pSrc);
75801   return;
75802 }
75803 #endif  /* SQLITE_ALTER_TABLE */
75804
75805 /************** End of alter.c ***********************************************/
75806 /************** Begin file analyze.c *****************************************/
75807 /*
75808 ** 2005 July 8
75809 **
75810 ** The author disclaims copyright to this source code.  In place of
75811 ** a legal notice, here is a blessing:
75812 **
75813 **    May you do good and not evil.
75814 **    May you find forgiveness for yourself and forgive others.
75815 **    May you share freely, never taking more than you give.
75816 **
75817 *************************************************************************
75818 ** This file contains code associated with the ANALYZE command.
75819 */
75820 #ifndef SQLITE_OMIT_ANALYZE
75821
75822 /*
75823 ** This routine generates code that opens the sqlite_stat1 table for
75824 ** writing with cursor iStatCur. If the library was built with the
75825 ** SQLITE_ENABLE_STAT2 macro defined, then the sqlite_stat2 table is
75826 ** opened for writing using cursor (iStatCur+1)
75827 **
75828 ** If the sqlite_stat1 tables does not previously exist, it is created.
75829 ** Similarly, if the sqlite_stat2 table does not exist and the library
75830 ** is compiled with SQLITE_ENABLE_STAT2 defined, it is created. 
75831 **
75832 ** Argument zWhere may be a pointer to a buffer containing a table name,
75833 ** or it may be a NULL pointer. If it is not NULL, then all entries in
75834 ** the sqlite_stat1 and (if applicable) sqlite_stat2 tables associated
75835 ** with the named table are deleted. If zWhere==0, then code is generated
75836 ** to delete all stat table entries.
75837 */
75838 static void openStatTable(
75839   Parse *pParse,          /* Parsing context */
75840   int iDb,                /* The database we are looking in */
75841   int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
75842   const char *zWhere,     /* Delete entries for this table or index */
75843   const char *zWhereType  /* Either "tbl" or "idx" */
75844 ){
75845   static const struct {
75846     const char *zName;
75847     const char *zCols;
75848   } aTable[] = {
75849     { "sqlite_stat1", "tbl,idx,stat" },
75850 #ifdef SQLITE_ENABLE_STAT2
75851     { "sqlite_stat2", "tbl,idx,sampleno,sample" },
75852 #endif
75853   };
75854
75855   int aRoot[] = {0, 0};
75856   u8 aCreateTbl[] = {0, 0};
75857
75858   int i;
75859   sqlite3 *db = pParse->db;
75860   Db *pDb;
75861   Vdbe *v = sqlite3GetVdbe(pParse);
75862   if( v==0 ) return;
75863   assert( sqlite3BtreeHoldsAllMutexes(db) );
75864   assert( sqlite3VdbeDb(v)==db );
75865   pDb = &db->aDb[iDb];
75866
75867   for(i=0; i<ArraySize(aTable); i++){
75868     const char *zTab = aTable[i].zName;
75869     Table *pStat;
75870     if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
75871       /* The sqlite_stat[12] table does not exist. Create it. Note that a 
75872       ** side-effect of the CREATE TABLE statement is to leave the rootpage 
75873       ** of the new table in register pParse->regRoot. This is important 
75874       ** because the OpenWrite opcode below will be needing it. */
75875       sqlite3NestedParse(pParse,
75876           "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
75877       );
75878       aRoot[i] = pParse->regRoot;
75879       aCreateTbl[i] = 1;
75880     }else{
75881       /* The table already exists. If zWhere is not NULL, delete all entries 
75882       ** associated with the table zWhere. If zWhere is NULL, delete the
75883       ** entire contents of the table. */
75884       aRoot[i] = pStat->tnum;
75885       sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
75886       if( zWhere ){
75887         sqlite3NestedParse(pParse,
75888            "DELETE FROM %Q.%s WHERE %s=%Q", pDb->zName, zTab, zWhereType, zWhere
75889         );
75890       }else{
75891         /* The sqlite_stat[12] table already exists.  Delete all rows. */
75892         sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
75893       }
75894     }
75895   }
75896
75897   /* Open the sqlite_stat[12] tables for writing. */
75898   for(i=0; i<ArraySize(aTable); i++){
75899     sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb);
75900     sqlite3VdbeChangeP4(v, -1, (char *)3, P4_INT32);
75901     sqlite3VdbeChangeP5(v, aCreateTbl[i]);
75902   }
75903 }
75904
75905 /*
75906 ** Generate code to do an analysis of all indices associated with
75907 ** a single table.
75908 */
75909 static void analyzeOneTable(
75910   Parse *pParse,   /* Parser context */
75911   Table *pTab,     /* Table whose indices are to be analyzed */
75912   Index *pOnlyIdx, /* If not NULL, only analyze this one index */
75913   int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
75914   int iMem         /* Available memory locations begin here */
75915 ){
75916   sqlite3 *db = pParse->db;    /* Database handle */
75917   Index *pIdx;                 /* An index to being analyzed */
75918   int iIdxCur;                 /* Cursor open on index being analyzed */
75919   Vdbe *v;                     /* The virtual machine being built up */
75920   int i;                       /* Loop counter */
75921   int topOfLoop;               /* The top of the loop */
75922   int endOfLoop;               /* The end of the loop */
75923   int jZeroRows = -1;          /* Jump from here if number of rows is zero */
75924   int iDb;                     /* Index of database containing pTab */
75925   int regTabname = iMem++;     /* Register containing table name */
75926   int regIdxname = iMem++;     /* Register containing index name */
75927   int regSampleno = iMem++;    /* Register containing next sample number */
75928   int regCol = iMem++;         /* Content of a column analyzed table */
75929   int regRec = iMem++;         /* Register holding completed record */
75930   int regTemp = iMem++;        /* Temporary use register */
75931   int regRowid = iMem++;       /* Rowid for the inserted record */
75932
75933 #ifdef SQLITE_ENABLE_STAT2
75934   int addr = 0;                /* Instruction address */
75935   int regTemp2 = iMem++;       /* Temporary use register */
75936   int regSamplerecno = iMem++; /* Index of next sample to record */
75937   int regRecno = iMem++;       /* Current sample index */
75938   int regLast = iMem++;        /* Index of last sample to record */
75939   int regFirst = iMem++;       /* Index of first sample to record */
75940 #endif
75941
75942   v = sqlite3GetVdbe(pParse);
75943   if( v==0 || NEVER(pTab==0) ){
75944     return;
75945   }
75946   if( pTab->tnum==0 ){
75947     /* Do not gather statistics on views or virtual tables */
75948     return;
75949   }
75950   if( memcmp(pTab->zName, "sqlite_", 7)==0 ){
75951     /* Do not gather statistics on system tables */
75952     return;
75953   }
75954   assert( sqlite3BtreeHoldsAllMutexes(db) );
75955   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
75956   assert( iDb>=0 );
75957   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
75958 #ifndef SQLITE_OMIT_AUTHORIZATION
75959   if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
75960       db->aDb[iDb].zName ) ){
75961     return;
75962   }
75963 #endif
75964
75965   /* Establish a read-lock on the table at the shared-cache level. */
75966   sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
75967
75968   iIdxCur = pParse->nTab++;
75969   sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
75970   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
75971     int nCol;
75972     KeyInfo *pKey;
75973
75974     if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
75975     nCol = pIdx->nColumn;
75976     pKey = sqlite3IndexKeyinfo(pParse, pIdx);
75977     if( iMem+1+(nCol*2)>pParse->nMem ){
75978       pParse->nMem = iMem+1+(nCol*2);
75979     }
75980
75981     /* Open a cursor to the index to be analyzed. */
75982     assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
75983     sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
75984         (char *)pKey, P4_KEYINFO_HANDOFF);
75985     VdbeComment((v, "%s", pIdx->zName));
75986
75987     /* Populate the register containing the index name. */
75988     sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
75989
75990 #ifdef SQLITE_ENABLE_STAT2
75991
75992     /* If this iteration of the loop is generating code to analyze the
75993     ** first index in the pTab->pIndex list, then register regLast has
75994     ** not been populated. In this case populate it now.  */
75995     if( pTab->pIndex==pIdx ){
75996       sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES, regSamplerecno);
75997       sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES*2-1, regTemp);
75998       sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES*2, regTemp2);
75999
76000       sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regLast);
76001       sqlite3VdbeAddOp2(v, OP_Null, 0, regFirst);
76002       addr = sqlite3VdbeAddOp3(v, OP_Lt, regSamplerecno, 0, regLast);
76003       sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regLast, regFirst);
76004       sqlite3VdbeAddOp3(v, OP_Multiply, regLast, regTemp, regLast);
76005       sqlite3VdbeAddOp2(v, OP_AddImm, regLast, SQLITE_INDEX_SAMPLES*2-2);
76006       sqlite3VdbeAddOp3(v, OP_Divide,  regTemp2, regLast, regLast);
76007       sqlite3VdbeJumpHere(v, addr);
76008     }
76009
76010     /* Zero the regSampleno and regRecno registers. */
76011     sqlite3VdbeAddOp2(v, OP_Integer, 0, regSampleno);
76012     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRecno);
76013     sqlite3VdbeAddOp2(v, OP_Copy, regFirst, regSamplerecno);
76014 #endif
76015
76016     /* The block of memory cells initialized here is used as follows.
76017     **
76018     **    iMem:                
76019     **        The total number of rows in the table.
76020     **
76021     **    iMem+1 .. iMem+nCol: 
76022     **        Number of distinct entries in index considering the 
76023     **        left-most N columns only, where N is between 1 and nCol, 
76024     **        inclusive.
76025     **
76026     **    iMem+nCol+1 .. Mem+2*nCol:  
76027     **        Previous value of indexed columns, from left to right.
76028     **
76029     ** Cells iMem through iMem+nCol are initialized to 0. The others are 
76030     ** initialized to contain an SQL NULL.
76031     */
76032     for(i=0; i<=nCol; i++){
76033       sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
76034     }
76035     for(i=0; i<nCol; i++){
76036       sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
76037     }
76038
76039     /* Start the analysis loop. This loop runs through all the entries in
76040     ** the index b-tree.  */
76041     endOfLoop = sqlite3VdbeMakeLabel(v);
76042     sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
76043     topOfLoop = sqlite3VdbeCurrentAddr(v);
76044     sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1);
76045
76046     for(i=0; i<nCol; i++){
76047       CollSeq *pColl;
76048       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
76049       if( i==0 ){
76050 #ifdef SQLITE_ENABLE_STAT2
76051         /* Check if the record that cursor iIdxCur points to contains a
76052         ** value that should be stored in the sqlite_stat2 table. If so,
76053         ** store it.  */
76054         int ne = sqlite3VdbeAddOp3(v, OP_Ne, regRecno, 0, regSamplerecno);
76055         assert( regTabname+1==regIdxname 
76056              && regTabname+2==regSampleno
76057              && regTabname+3==regCol
76058         );
76059         sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
76060         sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 4, regRec, "aaab", 0);
76061         sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regRowid);
76062         sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regRec, regRowid);
76063
76064         /* Calculate new values for regSamplerecno and regSampleno.
76065         **
76066         **   sampleno = sampleno + 1
76067         **   samplerecno = samplerecno+(remaining records)/(remaining samples)
76068         */
76069         sqlite3VdbeAddOp2(v, OP_AddImm, regSampleno, 1);
76070         sqlite3VdbeAddOp3(v, OP_Subtract, regRecno, regLast, regTemp);
76071         sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
76072         sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES, regTemp2);
76073         sqlite3VdbeAddOp3(v, OP_Subtract, regSampleno, regTemp2, regTemp2);
76074         sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regTemp, regTemp);
76075         sqlite3VdbeAddOp3(v, OP_Add, regSamplerecno, regTemp, regSamplerecno);
76076
76077         sqlite3VdbeJumpHere(v, ne);
76078         sqlite3VdbeAddOp2(v, OP_AddImm, regRecno, 1);
76079 #endif
76080
76081         /* Always record the very first row */
76082         sqlite3VdbeAddOp1(v, OP_IfNot, iMem+1);
76083       }
76084       assert( pIdx->azColl!=0 );
76085       assert( pIdx->azColl[i]!=0 );
76086       pColl = sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
76087       sqlite3VdbeAddOp4(v, OP_Ne, regCol, 0, iMem+nCol+i+1,
76088                        (char*)pColl, P4_COLLSEQ);
76089       sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
76090     }
76091     if( db->mallocFailed ){
76092       /* If a malloc failure has occurred, then the result of the expression 
76093       ** passed as the second argument to the call to sqlite3VdbeJumpHere() 
76094       ** below may be negative. Which causes an assert() to fail (or an
76095       ** out-of-bounds write if SQLITE_DEBUG is not defined).  */
76096       return;
76097     }
76098     sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
76099     for(i=0; i<nCol; i++){
76100       int addr2 = sqlite3VdbeCurrentAddr(v) - (nCol*2);
76101       if( i==0 ){
76102         sqlite3VdbeJumpHere(v, addr2-1);  /* Set jump dest for the OP_IfNot */
76103       }
76104       sqlite3VdbeJumpHere(v, addr2);      /* Set jump dest for the OP_Ne */
76105       sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
76106       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
76107     }
76108
76109     /* End of the analysis loop. */
76110     sqlite3VdbeResolveLabel(v, endOfLoop);
76111     sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
76112     sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
76113
76114     /* Store the results in sqlite_stat1.
76115     **
76116     ** The result is a single row of the sqlite_stat1 table.  The first
76117     ** two columns are the names of the table and index.  The third column
76118     ** is a string composed of a list of integer statistics about the
76119     ** index.  The first integer in the list is the total number of entries
76120     ** in the index.  There is one additional integer in the list for each
76121     ** column of the table.  This additional integer is a guess of how many
76122     ** rows of the table the index will select.  If D is the count of distinct
76123     ** values and K is the total number of rows, then the integer is computed
76124     ** as:
76125     **
76126     **        I = (K+D-1)/D
76127     **
76128     ** If K==0 then no entry is made into the sqlite_stat1 table.  
76129     ** If K>0 then it is always the case the D>0 so division by zero
76130     ** is never possible.
76131     */
76132     sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regSampleno);
76133     if( jZeroRows<0 ){
76134       jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
76135     }
76136     for(i=0; i<nCol; i++){
76137       sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
76138       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
76139       sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
76140       sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
76141       sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
76142       sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
76143       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
76144     }
76145     sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
76146     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
76147     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
76148     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
76149   }
76150
76151   /* If the table has no indices, create a single sqlite_stat1 entry
76152   ** containing NULL as the index name and the row count as the content.
76153   */
76154   if( pTab->pIndex==0 ){
76155     sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pTab->tnum, iDb);
76156     VdbeComment((v, "%s", pTab->zName));
76157     sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regSampleno);
76158     sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
76159     jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regSampleno);
76160   }else{
76161     sqlite3VdbeJumpHere(v, jZeroRows);
76162     jZeroRows = sqlite3VdbeAddOp0(v, OP_Goto);
76163   }
76164   sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
76165   sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
76166   sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
76167   sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
76168   sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
76169   if( pParse->nMem<regRec ) pParse->nMem = regRec;
76170   sqlite3VdbeJumpHere(v, jZeroRows);
76171 }
76172
76173 /*
76174 ** Generate code that will cause the most recent index analysis to
76175 ** be loaded into internal hash tables where is can be used.
76176 */
76177 static void loadAnalysis(Parse *pParse, int iDb){
76178   Vdbe *v = sqlite3GetVdbe(pParse);
76179   if( v ){
76180     sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
76181   }
76182 }
76183
76184 /*
76185 ** Generate code that will do an analysis of an entire database
76186 */
76187 static void analyzeDatabase(Parse *pParse, int iDb){
76188   sqlite3 *db = pParse->db;
76189   Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
76190   HashElem *k;
76191   int iStatCur;
76192   int iMem;
76193
76194   sqlite3BeginWriteOperation(pParse, 0, iDb);
76195   iStatCur = pParse->nTab;
76196   pParse->nTab += 2;
76197   openStatTable(pParse, iDb, iStatCur, 0, 0);
76198   iMem = pParse->nMem+1;
76199   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
76200   for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
76201     Table *pTab = (Table*)sqliteHashData(k);
76202     analyzeOneTable(pParse, pTab, 0, iStatCur, iMem);
76203   }
76204   loadAnalysis(pParse, iDb);
76205 }
76206
76207 /*
76208 ** Generate code that will do an analysis of a single table in
76209 ** a database.  If pOnlyIdx is not NULL then it is a single index
76210 ** in pTab that should be analyzed.
76211 */
76212 static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
76213   int iDb;
76214   int iStatCur;
76215
76216   assert( pTab!=0 );
76217   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
76218   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
76219   sqlite3BeginWriteOperation(pParse, 0, iDb);
76220   iStatCur = pParse->nTab;
76221   pParse->nTab += 2;
76222   if( pOnlyIdx ){
76223     openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
76224   }else{
76225     openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
76226   }
76227   analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur, pParse->nMem+1);
76228   loadAnalysis(pParse, iDb);
76229 }
76230
76231 /*
76232 ** Generate code for the ANALYZE command.  The parser calls this routine
76233 ** when it recognizes an ANALYZE command.
76234 **
76235 **        ANALYZE                            -- 1
76236 **        ANALYZE  <database>                -- 2
76237 **        ANALYZE  ?<database>.?<tablename>  -- 3
76238 **
76239 ** Form 1 causes all indices in all attached databases to be analyzed.
76240 ** Form 2 analyzes all indices the single database named.
76241 ** Form 3 analyzes all indices associated with the named table.
76242 */
76243 SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
76244   sqlite3 *db = pParse->db;
76245   int iDb;
76246   int i;
76247   char *z, *zDb;
76248   Table *pTab;
76249   Index *pIdx;
76250   Token *pTableName;
76251
76252   /* Read the database schema. If an error occurs, leave an error message
76253   ** and code in pParse and return NULL. */
76254   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
76255   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
76256     return;
76257   }
76258
76259   assert( pName2!=0 || pName1==0 );
76260   if( pName1==0 ){
76261     /* Form 1:  Analyze everything */
76262     for(i=0; i<db->nDb; i++){
76263       if( i==1 ) continue;  /* Do not analyze the TEMP database */
76264       analyzeDatabase(pParse, i);
76265     }
76266   }else if( pName2->n==0 ){
76267     /* Form 2:  Analyze the database or table named */
76268     iDb = sqlite3FindDb(db, pName1);
76269     if( iDb>=0 ){
76270       analyzeDatabase(pParse, iDb);
76271     }else{
76272       z = sqlite3NameFromToken(db, pName1);
76273       if( z ){
76274         if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
76275           analyzeTable(pParse, pIdx->pTable, pIdx);
76276         }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
76277           analyzeTable(pParse, pTab, 0);
76278         }
76279         sqlite3DbFree(db, z);
76280       }
76281     }
76282   }else{
76283     /* Form 3: Analyze the fully qualified table name */
76284     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
76285     if( iDb>=0 ){
76286       zDb = db->aDb[iDb].zName;
76287       z = sqlite3NameFromToken(db, pTableName);
76288       if( z ){
76289         if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
76290           analyzeTable(pParse, pIdx->pTable, pIdx);
76291         }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
76292           analyzeTable(pParse, pTab, 0);
76293         }
76294         sqlite3DbFree(db, z);
76295       }
76296     }   
76297   }
76298 }
76299
76300 /*
76301 ** Used to pass information from the analyzer reader through to the
76302 ** callback routine.
76303 */
76304 typedef struct analysisInfo analysisInfo;
76305 struct analysisInfo {
76306   sqlite3 *db;
76307   const char *zDatabase;
76308 };
76309
76310 /*
76311 ** This callback is invoked once for each index when reading the
76312 ** sqlite_stat1 table.  
76313 **
76314 **     argv[0] = name of the table
76315 **     argv[1] = name of the index (might be NULL)
76316 **     argv[2] = results of analysis - on integer for each column
76317 **
76318 ** Entries for which argv[1]==NULL simply record the number of rows in
76319 ** the table.
76320 */
76321 static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
76322   analysisInfo *pInfo = (analysisInfo*)pData;
76323   Index *pIndex;
76324   Table *pTable;
76325   int i, c, n;
76326   unsigned int v;
76327   const char *z;
76328
76329   assert( argc==3 );
76330   UNUSED_PARAMETER2(NotUsed, argc);
76331
76332   if( argv==0 || argv[0]==0 || argv[2]==0 ){
76333     return 0;
76334   }
76335   pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
76336   if( pTable==0 ){
76337     return 0;
76338   }
76339   if( argv[1] ){
76340     pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
76341   }else{
76342     pIndex = 0;
76343   }
76344   n = pIndex ? pIndex->nColumn : 0;
76345   z = argv[2];
76346   for(i=0; *z && i<=n; i++){
76347     v = 0;
76348     while( (c=z[0])>='0' && c<='9' ){
76349       v = v*10 + c - '0';
76350       z++;
76351     }
76352     if( i==0 ) pTable->nRowEst = v;
76353     if( pIndex==0 ) break;
76354     pIndex->aiRowEst[i] = v;
76355     if( *z==' ' ) z++;
76356     if( memcmp(z, "unordered", 10)==0 ){
76357       pIndex->bUnordered = 1;
76358       break;
76359     }
76360   }
76361   return 0;
76362 }
76363
76364 /*
76365 ** If the Index.aSample variable is not NULL, delete the aSample[] array
76366 ** and its contents.
76367 */
76368 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
76369 #ifdef SQLITE_ENABLE_STAT2
76370   if( pIdx->aSample ){
76371     int j;
76372     for(j=0; j<SQLITE_INDEX_SAMPLES; j++){
76373       IndexSample *p = &pIdx->aSample[j];
76374       if( p->eType==SQLITE_TEXT || p->eType==SQLITE_BLOB ){
76375         sqlite3DbFree(db, p->u.z);
76376       }
76377     }
76378     sqlite3DbFree(db, pIdx->aSample);
76379   }
76380 #else
76381   UNUSED_PARAMETER(db);
76382   UNUSED_PARAMETER(pIdx);
76383 #endif
76384 }
76385
76386 /*
76387 ** Load the content of the sqlite_stat1 and sqlite_stat2 tables. The
76388 ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
76389 ** arrays. The contents of sqlite_stat2 are used to populate the
76390 ** Index.aSample[] arrays.
76391 **
76392 ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
76393 ** is returned. In this case, even if SQLITE_ENABLE_STAT2 was defined 
76394 ** during compilation and the sqlite_stat2 table is present, no data is 
76395 ** read from it.
76396 **
76397 ** If SQLITE_ENABLE_STAT2 was defined during compilation and the 
76398 ** sqlite_stat2 table is not present in the database, SQLITE_ERROR is
76399 ** returned. However, in this case, data is read from the sqlite_stat1
76400 ** table (if it is present) before returning.
76401 **
76402 ** If an OOM error occurs, this function always sets db->mallocFailed.
76403 ** This means if the caller does not care about other errors, the return
76404 ** code may be ignored.
76405 */
76406 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
76407   analysisInfo sInfo;
76408   HashElem *i;
76409   char *zSql;
76410   int rc;
76411
76412   assert( iDb>=0 && iDb<db->nDb );
76413   assert( db->aDb[iDb].pBt!=0 );
76414
76415   /* Clear any prior statistics */
76416   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
76417   for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
76418     Index *pIdx = sqliteHashData(i);
76419     sqlite3DefaultRowEst(pIdx);
76420     sqlite3DeleteIndexSamples(db, pIdx);
76421     pIdx->aSample = 0;
76422   }
76423
76424   /* Check to make sure the sqlite_stat1 table exists */
76425   sInfo.db = db;
76426   sInfo.zDatabase = db->aDb[iDb].zName;
76427   if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
76428     return SQLITE_ERROR;
76429   }
76430
76431   /* Load new statistics out of the sqlite_stat1 table */
76432   zSql = sqlite3MPrintf(db, 
76433       "SELECT tbl, idx, stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
76434   if( zSql==0 ){
76435     rc = SQLITE_NOMEM;
76436   }else{
76437     rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
76438     sqlite3DbFree(db, zSql);
76439   }
76440
76441
76442   /* Load the statistics from the sqlite_stat2 table. */
76443 #ifdef SQLITE_ENABLE_STAT2
76444   if( rc==SQLITE_OK && !sqlite3FindTable(db, "sqlite_stat2", sInfo.zDatabase) ){
76445     rc = SQLITE_ERROR;
76446   }
76447   if( rc==SQLITE_OK ){
76448     sqlite3_stmt *pStmt = 0;
76449
76450     zSql = sqlite3MPrintf(db, 
76451         "SELECT idx,sampleno,sample FROM %Q.sqlite_stat2", sInfo.zDatabase);
76452     if( !zSql ){
76453       rc = SQLITE_NOMEM;
76454     }else{
76455       rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
76456       sqlite3DbFree(db, zSql);
76457     }
76458
76459     if( rc==SQLITE_OK ){
76460       while( sqlite3_step(pStmt)==SQLITE_ROW ){
76461         char *zIndex;   /* Index name */
76462         Index *pIdx;    /* Pointer to the index object */
76463
76464         zIndex = (char *)sqlite3_column_text(pStmt, 0);
76465         pIdx = zIndex ? sqlite3FindIndex(db, zIndex, sInfo.zDatabase) : 0;
76466         if( pIdx ){
76467           int iSample = sqlite3_column_int(pStmt, 1);
76468           if( iSample<SQLITE_INDEX_SAMPLES && iSample>=0 ){
76469             int eType = sqlite3_column_type(pStmt, 2);
76470
76471             if( pIdx->aSample==0 ){
76472               static const int sz = sizeof(IndexSample)*SQLITE_INDEX_SAMPLES;
76473               pIdx->aSample = (IndexSample *)sqlite3DbMallocRaw(0, sz);
76474               if( pIdx->aSample==0 ){
76475                 db->mallocFailed = 1;
76476                 break;
76477               }
76478               memset(pIdx->aSample, 0, sz);
76479             }
76480
76481             assert( pIdx->aSample );
76482             {
76483               IndexSample *pSample = &pIdx->aSample[iSample];
76484               pSample->eType = (u8)eType;
76485               if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
76486                 pSample->u.r = sqlite3_column_double(pStmt, 2);
76487               }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
76488                 const char *z = (const char *)(
76489                     (eType==SQLITE_BLOB) ?
76490                     sqlite3_column_blob(pStmt, 2):
76491                     sqlite3_column_text(pStmt, 2)
76492                 );
76493                 int n = sqlite3_column_bytes(pStmt, 2);
76494                 if( n>24 ){
76495                   n = 24;
76496                 }
76497                 pSample->nByte = (u8)n;
76498                 if( n < 1){
76499                   pSample->u.z = 0;
76500                 }else{
76501                   pSample->u.z = sqlite3DbStrNDup(0, z, n);
76502                   if( pSample->u.z==0 ){
76503                     db->mallocFailed = 1;
76504                     break;
76505                   }
76506                 }
76507               }
76508             }
76509           }
76510         }
76511       }
76512       rc = sqlite3_finalize(pStmt);
76513     }
76514   }
76515 #endif
76516
76517   if( rc==SQLITE_NOMEM ){
76518     db->mallocFailed = 1;
76519   }
76520   return rc;
76521 }
76522
76523
76524 #endif /* SQLITE_OMIT_ANALYZE */
76525
76526 /************** End of analyze.c *********************************************/
76527 /************** Begin file attach.c ******************************************/
76528 /*
76529 ** 2003 April 6
76530 **
76531 ** The author disclaims copyright to this source code.  In place of
76532 ** a legal notice, here is a blessing:
76533 **
76534 **    May you do good and not evil.
76535 **    May you find forgiveness for yourself and forgive others.
76536 **    May you share freely, never taking more than you give.
76537 **
76538 *************************************************************************
76539 ** This file contains code used to implement the ATTACH and DETACH commands.
76540 */
76541
76542 #ifndef SQLITE_OMIT_ATTACH
76543 /*
76544 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
76545 ** is slightly different from resolving a normal SQL expression, because simple
76546 ** identifiers are treated as strings, not possible column names or aliases.
76547 **
76548 ** i.e. if the parser sees:
76549 **
76550 **     ATTACH DATABASE abc AS def
76551 **
76552 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
76553 ** looking for columns of the same name.
76554 **
76555 ** This only applies to the root node of pExpr, so the statement:
76556 **
76557 **     ATTACH DATABASE abc||def AS 'db2'
76558 **
76559 ** will fail because neither abc or def can be resolved.
76560 */
76561 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
76562 {
76563   int rc = SQLITE_OK;
76564   if( pExpr ){
76565     if( pExpr->op!=TK_ID ){
76566       rc = sqlite3ResolveExprNames(pName, pExpr);
76567       if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
76568         sqlite3ErrorMsg(pName->pParse, "invalid name: \"%s\"", pExpr->u.zToken);
76569         return SQLITE_ERROR;
76570       }
76571     }else{
76572       pExpr->op = TK_STRING;
76573     }
76574   }
76575   return rc;
76576 }
76577
76578 /*
76579 ** An SQL user-function registered to do the work of an ATTACH statement. The
76580 ** three arguments to the function come directly from an attach statement:
76581 **
76582 **     ATTACH DATABASE x AS y KEY z
76583 **
76584 **     SELECT sqlite_attach(x, y, z)
76585 **
76586 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
76587 ** third argument.
76588 */
76589 static void attachFunc(
76590   sqlite3_context *context,
76591   int NotUsed,
76592   sqlite3_value **argv
76593 ){
76594   int i;
76595   int rc = 0;
76596   sqlite3 *db = sqlite3_context_db_handle(context);
76597   const char *zName;
76598   const char *zFile;
76599   char *zPath = 0;
76600   char *zErr = 0;
76601   unsigned int flags;
76602   Db *aNew;
76603   char *zErrDyn = 0;
76604   sqlite3_vfs *pVfs;
76605
76606   UNUSED_PARAMETER(NotUsed);
76607
76608   zFile = (const char *)sqlite3_value_text(argv[0]);
76609   zName = (const char *)sqlite3_value_text(argv[1]);
76610   if( zFile==0 ) zFile = "";
76611   if( zName==0 ) zName = "";
76612
76613   /* Check for the following errors:
76614   **
76615   **     * Too many attached databases,
76616   **     * Transaction currently open
76617   **     * Specified database name already being used.
76618   */
76619   if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
76620     zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d", 
76621       db->aLimit[SQLITE_LIMIT_ATTACHED]
76622     );
76623     goto attach_error;
76624   }
76625   if( !db->autoCommit ){
76626     zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
76627     goto attach_error;
76628   }
76629   for(i=0; i<db->nDb; i++){
76630     char *z = db->aDb[i].zName;
76631     assert( z && zName );
76632     if( sqlite3StrICmp(z, zName)==0 ){
76633       zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
76634       goto attach_error;
76635     }
76636   }
76637
76638   /* Allocate the new entry in the db->aDb[] array and initialise the schema
76639   ** hash tables.
76640   */
76641   if( db->aDb==db->aDbStatic ){
76642     aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
76643     if( aNew==0 ) return;
76644     memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
76645   }else{
76646     aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
76647     if( aNew==0 ) return;
76648   }
76649   db->aDb = aNew;
76650   aNew = &db->aDb[db->nDb];
76651   memset(aNew, 0, sizeof(*aNew));
76652
76653   /* Open the database file. If the btree is successfully opened, use
76654   ** it to obtain the database schema. At this point the schema may
76655   ** or may not be initialised.
76656   */
76657   flags = db->openFlags;
76658   rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
76659   if( rc!=SQLITE_OK ){
76660     if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
76661     sqlite3_result_error(context, zErr, -1);
76662     sqlite3_free(zErr);
76663     return;
76664   }
76665   assert( pVfs );
76666   flags |= SQLITE_OPEN_MAIN_DB;
76667   rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
76668   sqlite3_free( zPath );
76669   db->nDb++;
76670   if( rc==SQLITE_CONSTRAINT ){
76671     rc = SQLITE_ERROR;
76672     zErrDyn = sqlite3MPrintf(db, "database is already attached");
76673   }else if( rc==SQLITE_OK ){
76674     Pager *pPager;
76675     aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
76676     if( !aNew->pSchema ){
76677       rc = SQLITE_NOMEM;
76678     }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
76679       zErrDyn = sqlite3MPrintf(db, 
76680         "attached databases must use the same text encoding as main database");
76681       rc = SQLITE_ERROR;
76682     }
76683     pPager = sqlite3BtreePager(aNew->pBt);
76684     sqlite3PagerLockingMode(pPager, db->dfltLockMode);
76685     sqlite3BtreeSecureDelete(aNew->pBt,
76686                              sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
76687   }
76688   aNew->safety_level = 3;
76689   aNew->zName = sqlite3DbStrDup(db, zName);
76690   if( rc==SQLITE_OK && aNew->zName==0 ){
76691     rc = SQLITE_NOMEM;
76692   }
76693
76694
76695 #ifdef SQLITE_HAS_CODEC
76696   if( rc==SQLITE_OK ){
76697     extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
76698     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
76699     int nKey;
76700     char *zKey;
76701     int t = sqlite3_value_type(argv[2]);
76702     switch( t ){
76703       case SQLITE_INTEGER:
76704       case SQLITE_FLOAT:
76705         zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
76706         rc = SQLITE_ERROR;
76707         break;
76708         
76709       case SQLITE_TEXT:
76710       case SQLITE_BLOB:
76711         nKey = sqlite3_value_bytes(argv[2]);
76712         zKey = (char *)sqlite3_value_blob(argv[2]);
76713         rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
76714         break;
76715
76716       case SQLITE_NULL:
76717         /* No key specified.  Use the key from the main database */
76718         sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
76719         if( nKey>0 || sqlite3BtreeGetReserve(db->aDb[0].pBt)>0 ){
76720           rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
76721         }
76722         break;
76723     }
76724   }
76725 #endif
76726
76727   /* If the file was opened successfully, read the schema for the new database.
76728   ** If this fails, or if opening the file failed, then close the file and 
76729   ** remove the entry from the db->aDb[] array. i.e. put everything back the way
76730   ** we found it.
76731   */
76732   if( rc==SQLITE_OK ){
76733     sqlite3BtreeEnterAll(db);
76734     rc = sqlite3Init(db, &zErrDyn);
76735     sqlite3BtreeLeaveAll(db);
76736   }
76737   if( rc ){
76738     int iDb = db->nDb - 1;
76739     assert( iDb>=2 );
76740     if( db->aDb[iDb].pBt ){
76741       sqlite3BtreeClose(db->aDb[iDb].pBt);
76742       db->aDb[iDb].pBt = 0;
76743       db->aDb[iDb].pSchema = 0;
76744     }
76745     sqlite3ResetInternalSchema(db, -1);
76746     db->nDb = iDb;
76747     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
76748       db->mallocFailed = 1;
76749       sqlite3DbFree(db, zErrDyn);
76750       zErrDyn = sqlite3MPrintf(db, "out of memory");
76751     }else if( zErrDyn==0 ){
76752       zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
76753     }
76754     goto attach_error;
76755   }
76756   
76757   return;
76758
76759 attach_error:
76760   /* Return an error if we get here */
76761   if( zErrDyn ){
76762     sqlite3_result_error(context, zErrDyn, -1);
76763     sqlite3DbFree(db, zErrDyn);
76764   }
76765   if( rc ) sqlite3_result_error_code(context, rc);
76766 }
76767
76768 /*
76769 ** An SQL user-function registered to do the work of an DETACH statement. The
76770 ** three arguments to the function come directly from a detach statement:
76771 **
76772 **     DETACH DATABASE x
76773 **
76774 **     SELECT sqlite_detach(x)
76775 */
76776 static void detachFunc(
76777   sqlite3_context *context,
76778   int NotUsed,
76779   sqlite3_value **argv
76780 ){
76781   const char *zName = (const char *)sqlite3_value_text(argv[0]);
76782   sqlite3 *db = sqlite3_context_db_handle(context);
76783   int i;
76784   Db *pDb = 0;
76785   char zErr[128];
76786
76787   UNUSED_PARAMETER(NotUsed);
76788
76789   if( zName==0 ) zName = "";
76790   for(i=0; i<db->nDb; i++){
76791     pDb = &db->aDb[i];
76792     if( pDb->pBt==0 ) continue;
76793     if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
76794   }
76795
76796   if( i>=db->nDb ){
76797     sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
76798     goto detach_error;
76799   }
76800   if( i<2 ){
76801     sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
76802     goto detach_error;
76803   }
76804   if( !db->autoCommit ){
76805     sqlite3_snprintf(sizeof(zErr), zErr,
76806                      "cannot DETACH database within transaction");
76807     goto detach_error;
76808   }
76809   if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
76810     sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
76811     goto detach_error;
76812   }
76813
76814   sqlite3BtreeClose(pDb->pBt);
76815   pDb->pBt = 0;
76816   pDb->pSchema = 0;
76817   sqlite3ResetInternalSchema(db, -1);
76818   return;
76819
76820 detach_error:
76821   sqlite3_result_error(context, zErr, -1);
76822 }
76823
76824 /*
76825 ** This procedure generates VDBE code for a single invocation of either the
76826 ** sqlite_detach() or sqlite_attach() SQL user functions.
76827 */
76828 static void codeAttach(
76829   Parse *pParse,       /* The parser context */
76830   int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
76831   FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
76832   Expr *pAuthArg,      /* Expression to pass to authorization callback */
76833   Expr *pFilename,     /* Name of database file */
76834   Expr *pDbname,       /* Name of the database to use internally */
76835   Expr *pKey           /* Database key for encryption extension */
76836 ){
76837   int rc;
76838   NameContext sName;
76839   Vdbe *v;
76840   sqlite3* db = pParse->db;
76841   int regArgs;
76842
76843   memset(&sName, 0, sizeof(NameContext));
76844   sName.pParse = pParse;
76845
76846   if( 
76847       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
76848       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
76849       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
76850   ){
76851     pParse->nErr++;
76852     goto attach_end;
76853   }
76854
76855 #ifndef SQLITE_OMIT_AUTHORIZATION
76856   if( pAuthArg ){
76857     char *zAuthArg;
76858     if( pAuthArg->op==TK_STRING ){
76859       zAuthArg = pAuthArg->u.zToken;
76860     }else{
76861       zAuthArg = 0;
76862     }
76863     rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
76864     if(rc!=SQLITE_OK ){
76865       goto attach_end;
76866     }
76867   }
76868 #endif /* SQLITE_OMIT_AUTHORIZATION */
76869
76870
76871   v = sqlite3GetVdbe(pParse);
76872   regArgs = sqlite3GetTempRange(pParse, 4);
76873   sqlite3ExprCode(pParse, pFilename, regArgs);
76874   sqlite3ExprCode(pParse, pDbname, regArgs+1);
76875   sqlite3ExprCode(pParse, pKey, regArgs+2);
76876
76877   assert( v || db->mallocFailed );
76878   if( v ){
76879     sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
76880     assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
76881     sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
76882     sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
76883
76884     /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
76885     ** statement only). For DETACH, set it to false (expire all existing
76886     ** statements).
76887     */
76888     sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
76889   }
76890   
76891 attach_end:
76892   sqlite3ExprDelete(db, pFilename);
76893   sqlite3ExprDelete(db, pDbname);
76894   sqlite3ExprDelete(db, pKey);
76895 }
76896
76897 /*
76898 ** Called by the parser to compile a DETACH statement.
76899 **
76900 **     DETACH pDbname
76901 */
76902 SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
76903   static const FuncDef detach_func = {
76904     1,                /* nArg */
76905     SQLITE_UTF8,      /* iPrefEnc */
76906     0,                /* flags */
76907     0,                /* pUserData */
76908     0,                /* pNext */
76909     detachFunc,       /* xFunc */
76910     0,                /* xStep */
76911     0,                /* xFinalize */
76912     "sqlite_detach",  /* zName */
76913     0,                /* pHash */
76914     0                 /* pDestructor */
76915   };
76916   codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
76917 }
76918
76919 /*
76920 ** Called by the parser to compile an ATTACH statement.
76921 **
76922 **     ATTACH p AS pDbname KEY pKey
76923 */
76924 SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
76925   static const FuncDef attach_func = {
76926     3,                /* nArg */
76927     SQLITE_UTF8,      /* iPrefEnc */
76928     0,                /* flags */
76929     0,                /* pUserData */
76930     0,                /* pNext */
76931     attachFunc,       /* xFunc */
76932     0,                /* xStep */
76933     0,                /* xFinalize */
76934     "sqlite_attach",  /* zName */
76935     0,                /* pHash */
76936     0                 /* pDestructor */
76937   };
76938   codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
76939 }
76940 #endif /* SQLITE_OMIT_ATTACH */
76941
76942 /*
76943 ** Initialize a DbFixer structure.  This routine must be called prior
76944 ** to passing the structure to one of the sqliteFixAAAA() routines below.
76945 **
76946 ** The return value indicates whether or not fixation is required.  TRUE
76947 ** means we do need to fix the database references, FALSE means we do not.
76948 */
76949 SQLITE_PRIVATE int sqlite3FixInit(
76950   DbFixer *pFix,      /* The fixer to be initialized */
76951   Parse *pParse,      /* Error messages will be written here */
76952   int iDb,            /* This is the database that must be used */
76953   const char *zType,  /* "view", "trigger", or "index" */
76954   const Token *pName  /* Name of the view, trigger, or index */
76955 ){
76956   sqlite3 *db;
76957
76958   if( NEVER(iDb<0) || iDb==1 ) return 0;
76959   db = pParse->db;
76960   assert( db->nDb>iDb );
76961   pFix->pParse = pParse;
76962   pFix->zDb = db->aDb[iDb].zName;
76963   pFix->zType = zType;
76964   pFix->pName = pName;
76965   return 1;
76966 }
76967
76968 /*
76969 ** The following set of routines walk through the parse tree and assign
76970 ** a specific database to all table references where the database name
76971 ** was left unspecified in the original SQL statement.  The pFix structure
76972 ** must have been initialized by a prior call to sqlite3FixInit().
76973 **
76974 ** These routines are used to make sure that an index, trigger, or
76975 ** view in one database does not refer to objects in a different database.
76976 ** (Exception: indices, triggers, and views in the TEMP database are
76977 ** allowed to refer to anything.)  If a reference is explicitly made
76978 ** to an object in a different database, an error message is added to
76979 ** pParse->zErrMsg and these routines return non-zero.  If everything
76980 ** checks out, these routines return 0.
76981 */
76982 SQLITE_PRIVATE int sqlite3FixSrcList(
76983   DbFixer *pFix,       /* Context of the fixation */
76984   SrcList *pList       /* The Source list to check and modify */
76985 ){
76986   int i;
76987   const char *zDb;
76988   struct SrcList_item *pItem;
76989
76990   if( NEVER(pList==0) ) return 0;
76991   zDb = pFix->zDb;
76992   for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
76993     if( pItem->zDatabase==0 ){
76994       pItem->zDatabase = sqlite3DbStrDup(pFix->pParse->db, zDb);
76995     }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
76996       sqlite3ErrorMsg(pFix->pParse,
76997          "%s %T cannot reference objects in database %s",
76998          pFix->zType, pFix->pName, pItem->zDatabase);
76999       return 1;
77000     }
77001 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
77002     if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
77003     if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
77004 #endif
77005   }
77006   return 0;
77007 }
77008 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
77009 SQLITE_PRIVATE int sqlite3FixSelect(
77010   DbFixer *pFix,       /* Context of the fixation */
77011   Select *pSelect      /* The SELECT statement to be fixed to one database */
77012 ){
77013   while( pSelect ){
77014     if( sqlite3FixExprList(pFix, pSelect->pEList) ){
77015       return 1;
77016     }
77017     if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
77018       return 1;
77019     }
77020     if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
77021       return 1;
77022     }
77023     if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
77024       return 1;
77025     }
77026     pSelect = pSelect->pPrior;
77027   }
77028   return 0;
77029 }
77030 SQLITE_PRIVATE int sqlite3FixExpr(
77031   DbFixer *pFix,     /* Context of the fixation */
77032   Expr *pExpr        /* The expression to be fixed to one database */
77033 ){
77034   while( pExpr ){
77035     if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ) break;
77036     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
77037       if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
77038     }else{
77039       if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
77040     }
77041     if( sqlite3FixExpr(pFix, pExpr->pRight) ){
77042       return 1;
77043     }
77044     pExpr = pExpr->pLeft;
77045   }
77046   return 0;
77047 }
77048 SQLITE_PRIVATE int sqlite3FixExprList(
77049   DbFixer *pFix,     /* Context of the fixation */
77050   ExprList *pList    /* The expression to be fixed to one database */
77051 ){
77052   int i;
77053   struct ExprList_item *pItem;
77054   if( pList==0 ) return 0;
77055   for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
77056     if( sqlite3FixExpr(pFix, pItem->pExpr) ){
77057       return 1;
77058     }
77059   }
77060   return 0;
77061 }
77062 #endif
77063
77064 #ifndef SQLITE_OMIT_TRIGGER
77065 SQLITE_PRIVATE int sqlite3FixTriggerStep(
77066   DbFixer *pFix,     /* Context of the fixation */
77067   TriggerStep *pStep /* The trigger step be fixed to one database */
77068 ){
77069   while( pStep ){
77070     if( sqlite3FixSelect(pFix, pStep->pSelect) ){
77071       return 1;
77072     }
77073     if( sqlite3FixExpr(pFix, pStep->pWhere) ){
77074       return 1;
77075     }
77076     if( sqlite3FixExprList(pFix, pStep->pExprList) ){
77077       return 1;
77078     }
77079     pStep = pStep->pNext;
77080   }
77081   return 0;
77082 }
77083 #endif
77084
77085 /************** End of attach.c **********************************************/
77086 /************** Begin file auth.c ********************************************/
77087 /*
77088 ** 2003 January 11
77089 **
77090 ** The author disclaims copyright to this source code.  In place of
77091 ** a legal notice, here is a blessing:
77092 **
77093 **    May you do good and not evil.
77094 **    May you find forgiveness for yourself and forgive others.
77095 **    May you share freely, never taking more than you give.
77096 **
77097 *************************************************************************
77098 ** This file contains code used to implement the sqlite3_set_authorizer()
77099 ** API.  This facility is an optional feature of the library.  Embedded
77100 ** systems that do not need this facility may omit it by recompiling
77101 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
77102 */
77103
77104 /*
77105 ** All of the code in this file may be omitted by defining a single
77106 ** macro.
77107 */
77108 #ifndef SQLITE_OMIT_AUTHORIZATION
77109
77110 /*
77111 ** Set or clear the access authorization function.
77112 **
77113 ** The access authorization function is be called during the compilation
77114 ** phase to verify that the user has read and/or write access permission on
77115 ** various fields of the database.  The first argument to the auth function
77116 ** is a copy of the 3rd argument to this routine.  The second argument
77117 ** to the auth function is one of these constants:
77118 **
77119 **       SQLITE_CREATE_INDEX
77120 **       SQLITE_CREATE_TABLE
77121 **       SQLITE_CREATE_TEMP_INDEX
77122 **       SQLITE_CREATE_TEMP_TABLE
77123 **       SQLITE_CREATE_TEMP_TRIGGER
77124 **       SQLITE_CREATE_TEMP_VIEW
77125 **       SQLITE_CREATE_TRIGGER
77126 **       SQLITE_CREATE_VIEW
77127 **       SQLITE_DELETE
77128 **       SQLITE_DROP_INDEX
77129 **       SQLITE_DROP_TABLE
77130 **       SQLITE_DROP_TEMP_INDEX
77131 **       SQLITE_DROP_TEMP_TABLE
77132 **       SQLITE_DROP_TEMP_TRIGGER
77133 **       SQLITE_DROP_TEMP_VIEW
77134 **       SQLITE_DROP_TRIGGER
77135 **       SQLITE_DROP_VIEW
77136 **       SQLITE_INSERT
77137 **       SQLITE_PRAGMA
77138 **       SQLITE_READ
77139 **       SQLITE_SELECT
77140 **       SQLITE_TRANSACTION
77141 **       SQLITE_UPDATE
77142 **
77143 ** The third and fourth arguments to the auth function are the name of
77144 ** the table and the column that are being accessed.  The auth function
77145 ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
77146 ** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
77147 ** means that the SQL statement will never-run - the sqlite3_exec() call
77148 ** will return with an error.  SQLITE_IGNORE means that the SQL statement
77149 ** should run but attempts to read the specified column will return NULL
77150 ** and attempts to write the column will be ignored.
77151 **
77152 ** Setting the auth function to NULL disables this hook.  The default
77153 ** setting of the auth function is NULL.
77154 */
77155 SQLITE_API int sqlite3_set_authorizer(
77156   sqlite3 *db,
77157   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
77158   void *pArg
77159 ){
77160   sqlite3_mutex_enter(db->mutex);
77161   db->xAuth = xAuth;
77162   db->pAuthArg = pArg;
77163   sqlite3ExpirePreparedStatements(db);
77164   sqlite3_mutex_leave(db->mutex);
77165   return SQLITE_OK;
77166 }
77167
77168 /*
77169 ** Write an error message into pParse->zErrMsg that explains that the
77170 ** user-supplied authorization function returned an illegal value.
77171 */
77172 static void sqliteAuthBadReturnCode(Parse *pParse){
77173   sqlite3ErrorMsg(pParse, "authorizer malfunction");
77174   pParse->rc = SQLITE_ERROR;
77175 }
77176
77177 /*
77178 ** Invoke the authorization callback for permission to read column zCol from
77179 ** table zTab in database zDb. This function assumes that an authorization
77180 ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
77181 **
77182 ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
77183 ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
77184 ** is treated as SQLITE_DENY. In this case an error is left in pParse.
77185 */
77186 SQLITE_PRIVATE int sqlite3AuthReadCol(
77187   Parse *pParse,                  /* The parser context */
77188   const char *zTab,               /* Table name */
77189   const char *zCol,               /* Column name */
77190   int iDb                         /* Index of containing database. */
77191 ){
77192   sqlite3 *db = pParse->db;       /* Database handle */
77193   char *zDb = db->aDb[iDb].zName; /* Name of attached database */
77194   int rc;                         /* Auth callback return code */
77195
77196   rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
77197   if( rc==SQLITE_DENY ){
77198     if( db->nDb>2 || iDb!=0 ){
77199       sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
77200     }else{
77201       sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
77202     }
77203     pParse->rc = SQLITE_AUTH;
77204   }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
77205     sqliteAuthBadReturnCode(pParse);
77206   }
77207   return rc;
77208 }
77209
77210 /*
77211 ** The pExpr should be a TK_COLUMN expression.  The table referred to
77212 ** is in pTabList or else it is the NEW or OLD table of a trigger.  
77213 ** Check to see if it is OK to read this particular column.
77214 **
77215 ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN 
77216 ** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
77217 ** then generate an error.
77218 */
77219 SQLITE_PRIVATE void sqlite3AuthRead(
77220   Parse *pParse,        /* The parser context */
77221   Expr *pExpr,          /* The expression to check authorization on */
77222   Schema *pSchema,      /* The schema of the expression */
77223   SrcList *pTabList     /* All table that pExpr might refer to */
77224 ){
77225   sqlite3 *db = pParse->db;
77226   Table *pTab = 0;      /* The table being read */
77227   const char *zCol;     /* Name of the column of the table */
77228   int iSrc;             /* Index in pTabList->a[] of table being read */
77229   int iDb;              /* The index of the database the expression refers to */
77230   int iCol;             /* Index of column in table */
77231
77232   if( db->xAuth==0 ) return;
77233   iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
77234   if( iDb<0 ){
77235     /* An attempt to read a column out of a subquery or other
77236     ** temporary table. */
77237     return;
77238   }
77239
77240   assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
77241   if( pExpr->op==TK_TRIGGER ){
77242     pTab = pParse->pTriggerTab;
77243   }else{
77244     assert( pTabList );
77245     for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
77246       if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
77247         pTab = pTabList->a[iSrc].pTab;
77248         break;
77249       }
77250     }
77251   }
77252   iCol = pExpr->iColumn;
77253   if( NEVER(pTab==0) ) return;
77254
77255   if( iCol>=0 ){
77256     assert( iCol<pTab->nCol );
77257     zCol = pTab->aCol[iCol].zName;
77258   }else if( pTab->iPKey>=0 ){
77259     assert( pTab->iPKey<pTab->nCol );
77260     zCol = pTab->aCol[pTab->iPKey].zName;
77261   }else{
77262     zCol = "ROWID";
77263   }
77264   assert( iDb>=0 && iDb<db->nDb );
77265   if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
77266     pExpr->op = TK_NULL;
77267   }
77268 }
77269
77270 /*
77271 ** Do an authorization check using the code and arguments given.  Return
77272 ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
77273 ** is returned, then the error count and error message in pParse are
77274 ** modified appropriately.
77275 */
77276 SQLITE_PRIVATE int sqlite3AuthCheck(
77277   Parse *pParse,
77278   int code,
77279   const char *zArg1,
77280   const char *zArg2,
77281   const char *zArg3
77282 ){
77283   sqlite3 *db = pParse->db;
77284   int rc;
77285
77286   /* Don't do any authorization checks if the database is initialising
77287   ** or if the parser is being invoked from within sqlite3_declare_vtab.
77288   */
77289   if( db->init.busy || IN_DECLARE_VTAB ){
77290     return SQLITE_OK;
77291   }
77292
77293   if( db->xAuth==0 ){
77294     return SQLITE_OK;
77295   }
77296   rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
77297   if( rc==SQLITE_DENY ){
77298     sqlite3ErrorMsg(pParse, "not authorized");
77299     pParse->rc = SQLITE_AUTH;
77300   }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
77301     rc = SQLITE_DENY;
77302     sqliteAuthBadReturnCode(pParse);
77303   }
77304   return rc;
77305 }
77306
77307 /*
77308 ** Push an authorization context.  After this routine is called, the
77309 ** zArg3 argument to authorization callbacks will be zContext until
77310 ** popped.  Or if pParse==0, this routine is a no-op.
77311 */
77312 SQLITE_PRIVATE void sqlite3AuthContextPush(
77313   Parse *pParse,
77314   AuthContext *pContext, 
77315   const char *zContext
77316 ){
77317   assert( pParse );
77318   pContext->pParse = pParse;
77319   pContext->zAuthContext = pParse->zAuthContext;
77320   pParse->zAuthContext = zContext;
77321 }
77322
77323 /*
77324 ** Pop an authorization context that was previously pushed
77325 ** by sqlite3AuthContextPush
77326 */
77327 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
77328   if( pContext->pParse ){
77329     pContext->pParse->zAuthContext = pContext->zAuthContext;
77330     pContext->pParse = 0;
77331   }
77332 }
77333
77334 #endif /* SQLITE_OMIT_AUTHORIZATION */
77335
77336 /************** End of auth.c ************************************************/
77337 /************** Begin file build.c *******************************************/
77338 /*
77339 ** 2001 September 15
77340 **
77341 ** The author disclaims copyright to this source code.  In place of
77342 ** a legal notice, here is a blessing:
77343 **
77344 **    May you do good and not evil.
77345 **    May you find forgiveness for yourself and forgive others.
77346 **    May you share freely, never taking more than you give.
77347 **
77348 *************************************************************************
77349 ** This file contains C code routines that are called by the SQLite parser
77350 ** when syntax rules are reduced.  The routines in this file handle the
77351 ** following kinds of SQL syntax:
77352 **
77353 **     CREATE TABLE
77354 **     DROP TABLE
77355 **     CREATE INDEX
77356 **     DROP INDEX
77357 **     creating ID lists
77358 **     BEGIN TRANSACTION
77359 **     COMMIT
77360 **     ROLLBACK
77361 */
77362
77363 /*
77364 ** This routine is called when a new SQL statement is beginning to
77365 ** be parsed.  Initialize the pParse structure as needed.
77366 */
77367 SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
77368   pParse->explain = (u8)explainFlag;
77369   pParse->nVar = 0;
77370 }
77371
77372 #ifndef SQLITE_OMIT_SHARED_CACHE
77373 /*
77374 ** The TableLock structure is only used by the sqlite3TableLock() and
77375 ** codeTableLocks() functions.
77376 */
77377 struct TableLock {
77378   int iDb;             /* The database containing the table to be locked */
77379   int iTab;            /* The root page of the table to be locked */
77380   u8 isWriteLock;      /* True for write lock.  False for a read lock */
77381   const char *zName;   /* Name of the table */
77382 };
77383
77384 /*
77385 ** Record the fact that we want to lock a table at run-time.  
77386 **
77387 ** The table to be locked has root page iTab and is found in database iDb.
77388 ** A read or a write lock can be taken depending on isWritelock.
77389 **
77390 ** This routine just records the fact that the lock is desired.  The
77391 ** code to make the lock occur is generated by a later call to
77392 ** codeTableLocks() which occurs during sqlite3FinishCoding().
77393 */
77394 SQLITE_PRIVATE void sqlite3TableLock(
77395   Parse *pParse,     /* Parsing context */
77396   int iDb,           /* Index of the database containing the table to lock */
77397   int iTab,          /* Root page number of the table to be locked */
77398   u8 isWriteLock,    /* True for a write lock */
77399   const char *zName  /* Name of the table to be locked */
77400 ){
77401   Parse *pToplevel = sqlite3ParseToplevel(pParse);
77402   int i;
77403   int nBytes;
77404   TableLock *p;
77405   assert( iDb>=0 );
77406
77407   for(i=0; i<pToplevel->nTableLock; i++){
77408     p = &pToplevel->aTableLock[i];
77409     if( p->iDb==iDb && p->iTab==iTab ){
77410       p->isWriteLock = (p->isWriteLock || isWriteLock);
77411       return;
77412     }
77413   }
77414
77415   nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
77416   pToplevel->aTableLock =
77417       sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
77418   if( pToplevel->aTableLock ){
77419     p = &pToplevel->aTableLock[pToplevel->nTableLock++];
77420     p->iDb = iDb;
77421     p->iTab = iTab;
77422     p->isWriteLock = isWriteLock;
77423     p->zName = zName;
77424   }else{
77425     pToplevel->nTableLock = 0;
77426     pToplevel->db->mallocFailed = 1;
77427   }
77428 }
77429
77430 /*
77431 ** Code an OP_TableLock instruction for each table locked by the
77432 ** statement (configured by calls to sqlite3TableLock()).
77433 */
77434 static void codeTableLocks(Parse *pParse){
77435   int i;
77436   Vdbe *pVdbe; 
77437
77438   pVdbe = sqlite3GetVdbe(pParse);
77439   assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
77440
77441   for(i=0; i<pParse->nTableLock; i++){
77442     TableLock *p = &pParse->aTableLock[i];
77443     int p1 = p->iDb;
77444     sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
77445                       p->zName, P4_STATIC);
77446   }
77447 }
77448 #else
77449   #define codeTableLocks(x)
77450 #endif
77451
77452 /*
77453 ** This routine is called after a single SQL statement has been
77454 ** parsed and a VDBE program to execute that statement has been
77455 ** prepared.  This routine puts the finishing touches on the
77456 ** VDBE program and resets the pParse structure for the next
77457 ** parse.
77458 **
77459 ** Note that if an error occurred, it might be the case that
77460 ** no VDBE code was generated.
77461 */
77462 SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
77463   sqlite3 *db;
77464   Vdbe *v;
77465
77466   db = pParse->db;
77467   if( db->mallocFailed ) return;
77468   if( pParse->nested ) return;
77469   if( pParse->nErr ) return;
77470
77471   /* Begin by generating some termination code at the end of the
77472   ** vdbe program
77473   */
77474   v = sqlite3GetVdbe(pParse);
77475   assert( !pParse->isMultiWrite 
77476        || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
77477   if( v ){
77478     sqlite3VdbeAddOp0(v, OP_Halt);
77479
77480     /* The cookie mask contains one bit for each database file open.
77481     ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
77482     ** set for each database that is used.  Generate code to start a
77483     ** transaction on each used database and to verify the schema cookie
77484     ** on each used database.
77485     */
77486     if( pParse->cookieGoto>0 ){
77487       yDbMask mask;
77488       int iDb;
77489       sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
77490       for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
77491         if( (mask & pParse->cookieMask)==0 ) continue;
77492         sqlite3VdbeUsesBtree(v, iDb);
77493         sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
77494         if( db->init.busy==0 ){
77495           assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
77496           sqlite3VdbeAddOp3(v, OP_VerifyCookie,
77497                             iDb, pParse->cookieValue[iDb],
77498                             db->aDb[iDb].pSchema->iGeneration);
77499         }
77500       }
77501 #ifndef SQLITE_OMIT_VIRTUALTABLE
77502       {
77503         int i;
77504         for(i=0; i<pParse->nVtabLock; i++){
77505           char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
77506           sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
77507         }
77508         pParse->nVtabLock = 0;
77509       }
77510 #endif
77511
77512       /* Once all the cookies have been verified and transactions opened, 
77513       ** obtain the required table-locks. This is a no-op unless the 
77514       ** shared-cache feature is enabled.
77515       */
77516       codeTableLocks(pParse);
77517
77518       /* Initialize any AUTOINCREMENT data structures required.
77519       */
77520       sqlite3AutoincrementBegin(pParse);
77521
77522       /* Finally, jump back to the beginning of the executable code. */
77523       sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
77524     }
77525   }
77526
77527
77528   /* Get the VDBE program ready for execution
77529   */
77530   if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
77531 #ifdef SQLITE_DEBUG
77532     FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
77533     sqlite3VdbeTrace(v, trace);
77534 #endif
77535     assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
77536     /* A minimum of one cursor is required if autoincrement is used
77537     *  See ticket [a696379c1f08866] */
77538     if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
77539     sqlite3VdbeMakeReady(v, pParse);
77540     pParse->rc = SQLITE_DONE;
77541     pParse->colNamesSet = 0;
77542   }else{
77543     pParse->rc = SQLITE_ERROR;
77544   }
77545   pParse->nTab = 0;
77546   pParse->nMem = 0;
77547   pParse->nSet = 0;
77548   pParse->nVar = 0;
77549   pParse->cookieMask = 0;
77550   pParse->cookieGoto = 0;
77551 }
77552
77553 /*
77554 ** Run the parser and code generator recursively in order to generate
77555 ** code for the SQL statement given onto the end of the pParse context
77556 ** currently under construction.  When the parser is run recursively
77557 ** this way, the final OP_Halt is not appended and other initialization
77558 ** and finalization steps are omitted because those are handling by the
77559 ** outermost parser.
77560 **
77561 ** Not everything is nestable.  This facility is designed to permit
77562 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
77563 ** care if you decide to try to use this routine for some other purposes.
77564 */
77565 SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
77566   va_list ap;
77567   char *zSql;
77568   char *zErrMsg = 0;
77569   sqlite3 *db = pParse->db;
77570 # define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
77571   char saveBuf[SAVE_SZ];
77572
77573   if( pParse->nErr ) return;
77574   assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
77575   va_start(ap, zFormat);
77576   zSql = sqlite3VMPrintf(db, zFormat, ap);
77577   va_end(ap);
77578   if( zSql==0 ){
77579     return;   /* A malloc must have failed */
77580   }
77581   pParse->nested++;
77582   memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
77583   memset(&pParse->nVar, 0, SAVE_SZ);
77584   sqlite3RunParser(pParse, zSql, &zErrMsg);
77585   sqlite3DbFree(db, zErrMsg);
77586   sqlite3DbFree(db, zSql);
77587   memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
77588   pParse->nested--;
77589 }
77590
77591 /*
77592 ** Locate the in-memory structure that describes a particular database
77593 ** table given the name of that table and (optionally) the name of the
77594 ** database containing the table.  Return NULL if not found.
77595 **
77596 ** If zDatabase is 0, all databases are searched for the table and the
77597 ** first matching table is returned.  (No checking for duplicate table
77598 ** names is done.)  The search order is TEMP first, then MAIN, then any
77599 ** auxiliary databases added using the ATTACH command.
77600 **
77601 ** See also sqlite3LocateTable().
77602 */
77603 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
77604   Table *p = 0;
77605   int i;
77606   int nName;
77607   assert( zName!=0 );
77608   nName = sqlite3Strlen30(zName);
77609   /* All mutexes are required for schema access.  Make sure we hold them. */
77610   assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
77611   for(i=OMIT_TEMPDB; i<db->nDb; i++){
77612     int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
77613     if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
77614     assert( sqlite3SchemaMutexHeld(db, j, 0) );
77615     p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
77616     if( p ) break;
77617   }
77618   return p;
77619 }
77620
77621 /*
77622 ** Locate the in-memory structure that describes a particular database
77623 ** table given the name of that table and (optionally) the name of the
77624 ** database containing the table.  Return NULL if not found.  Also leave an
77625 ** error message in pParse->zErrMsg.
77626 **
77627 ** The difference between this routine and sqlite3FindTable() is that this
77628 ** routine leaves an error message in pParse->zErrMsg where
77629 ** sqlite3FindTable() does not.
77630 */
77631 SQLITE_PRIVATE Table *sqlite3LocateTable(
77632   Parse *pParse,         /* context in which to report errors */
77633   int isView,            /* True if looking for a VIEW rather than a TABLE */
77634   const char *zName,     /* Name of the table we are looking for */
77635   const char *zDbase     /* Name of the database.  Might be NULL */
77636 ){
77637   Table *p;
77638
77639   /* Read the database schema. If an error occurs, leave an error message
77640   ** and code in pParse and return NULL. */
77641   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
77642     return 0;
77643   }
77644
77645   p = sqlite3FindTable(pParse->db, zName, zDbase);
77646   if( p==0 ){
77647     const char *zMsg = isView ? "no such view" : "no such table";
77648     if( zDbase ){
77649       sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
77650     }else{
77651       sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
77652     }
77653     pParse->checkSchema = 1;
77654   }
77655   return p;
77656 }
77657
77658 /*
77659 ** Locate the in-memory structure that describes 
77660 ** a particular index given the name of that index
77661 ** and the name of the database that contains the index.
77662 ** Return NULL if not found.
77663 **
77664 ** If zDatabase is 0, all databases are searched for the
77665 ** table and the first matching index is returned.  (No checking
77666 ** for duplicate index names is done.)  The search order is
77667 ** TEMP first, then MAIN, then any auxiliary databases added
77668 ** using the ATTACH command.
77669 */
77670 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
77671   Index *p = 0;
77672   int i;
77673   int nName = sqlite3Strlen30(zName);
77674   /* All mutexes are required for schema access.  Make sure we hold them. */
77675   assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
77676   for(i=OMIT_TEMPDB; i<db->nDb; i++){
77677     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
77678     Schema *pSchema = db->aDb[j].pSchema;
77679     assert( pSchema );
77680     if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
77681     assert( sqlite3SchemaMutexHeld(db, j, 0) );
77682     p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
77683     if( p ) break;
77684   }
77685   return p;
77686 }
77687
77688 /*
77689 ** Reclaim the memory used by an index
77690 */
77691 static void freeIndex(sqlite3 *db, Index *p){
77692 #ifndef SQLITE_OMIT_ANALYZE
77693   sqlite3DeleteIndexSamples(db, p);
77694 #endif
77695   sqlite3DbFree(db, p->zColAff);
77696   sqlite3DbFree(db, p);
77697 }
77698
77699 /*
77700 ** For the index called zIdxName which is found in the database iDb,
77701 ** unlike that index from its Table then remove the index from
77702 ** the index hash table and free all memory structures associated
77703 ** with the index.
77704 */
77705 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
77706   Index *pIndex;
77707   int len;
77708   Hash *pHash;
77709
77710   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
77711   pHash = &db->aDb[iDb].pSchema->idxHash;
77712   len = sqlite3Strlen30(zIdxName);
77713   pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
77714   if( ALWAYS(pIndex) ){
77715     if( pIndex->pTable->pIndex==pIndex ){
77716       pIndex->pTable->pIndex = pIndex->pNext;
77717     }else{
77718       Index *p;
77719       /* Justification of ALWAYS();  The index must be on the list of
77720       ** indices. */
77721       p = pIndex->pTable->pIndex;
77722       while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
77723       if( ALWAYS(p && p->pNext==pIndex) ){
77724         p->pNext = pIndex->pNext;
77725       }
77726     }
77727     freeIndex(db, pIndex);
77728   }
77729   db->flags |= SQLITE_InternChanges;
77730 }
77731
77732 /*
77733 ** Erase all schema information from the in-memory hash tables of
77734 ** a single database.  This routine is called to reclaim memory
77735 ** before the database closes.  It is also called during a rollback
77736 ** if there were schema changes during the transaction or if a
77737 ** schema-cookie mismatch occurs.
77738 **
77739 ** If iDb<0 then reset the internal schema tables for all database
77740 ** files.  If iDb>=0 then reset the internal schema for only the
77741 ** single file indicated.
77742 */
77743 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
77744   int i, j;
77745   assert( iDb<db->nDb );
77746
77747   if( iDb>=0 ){
77748     /* Case 1:  Reset the single schema identified by iDb */
77749     Db *pDb = &db->aDb[iDb];
77750     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
77751     assert( pDb->pSchema!=0 );
77752     sqlite3SchemaClear(pDb->pSchema);
77753
77754     /* If any database other than TEMP is reset, then also reset TEMP
77755     ** since TEMP might be holding triggers that reference tables in the
77756     ** other database.
77757     */
77758     if( iDb!=1 ){
77759       pDb = &db->aDb[1];
77760       assert( pDb->pSchema!=0 );
77761       sqlite3SchemaClear(pDb->pSchema);
77762     }
77763     return;
77764   }
77765   /* Case 2 (from here to the end): Reset all schemas for all attached
77766   ** databases. */
77767   assert( iDb<0 );
77768   sqlite3BtreeEnterAll(db);
77769   for(i=0; i<db->nDb; i++){
77770     Db *pDb = &db->aDb[i];
77771     if( pDb->pSchema ){
77772       sqlite3SchemaClear(pDb->pSchema);
77773     }
77774   }
77775   db->flags &= ~SQLITE_InternChanges;
77776   sqlite3VtabUnlockList(db);
77777   sqlite3BtreeLeaveAll(db);
77778
77779   /* If one or more of the auxiliary database files has been closed,
77780   ** then remove them from the auxiliary database list.  We take the
77781   ** opportunity to do this here since we have just deleted all of the
77782   ** schema hash tables and therefore do not have to make any changes
77783   ** to any of those tables.
77784   */
77785   for(i=j=2; i<db->nDb; i++){
77786     struct Db *pDb = &db->aDb[i];
77787     if( pDb->pBt==0 ){
77788       sqlite3DbFree(db, pDb->zName);
77789       pDb->zName = 0;
77790       continue;
77791     }
77792     if( j<i ){
77793       db->aDb[j] = db->aDb[i];
77794     }
77795     j++;
77796   }
77797   memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
77798   db->nDb = j;
77799   if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
77800     memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
77801     sqlite3DbFree(db, db->aDb);
77802     db->aDb = db->aDbStatic;
77803   }
77804 }
77805
77806 /*
77807 ** This routine is called when a commit occurs.
77808 */
77809 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
77810   db->flags &= ~SQLITE_InternChanges;
77811 }
77812
77813 /*
77814 ** Delete memory allocated for the column names of a table or view (the
77815 ** Table.aCol[] array).
77816 */
77817 static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
77818   int i;
77819   Column *pCol;
77820   assert( pTable!=0 );
77821   if( (pCol = pTable->aCol)!=0 ){
77822     for(i=0; i<pTable->nCol; i++, pCol++){
77823       sqlite3DbFree(db, pCol->zName);
77824       sqlite3ExprDelete(db, pCol->pDflt);
77825       sqlite3DbFree(db, pCol->zDflt);
77826       sqlite3DbFree(db, pCol->zType);
77827       sqlite3DbFree(db, pCol->zColl);
77828     }
77829     sqlite3DbFree(db, pTable->aCol);
77830   }
77831 }
77832
77833 /*
77834 ** Remove the memory data structures associated with the given
77835 ** Table.  No changes are made to disk by this routine.
77836 **
77837 ** This routine just deletes the data structure.  It does not unlink
77838 ** the table data structure from the hash table.  But it does destroy
77839 ** memory structures of the indices and foreign keys associated with 
77840 ** the table.
77841 */
77842 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
77843   Index *pIndex, *pNext;
77844
77845   assert( !pTable || pTable->nRef>0 );
77846
77847   /* Do not delete the table until the reference count reaches zero. */
77848   if( !pTable ) return;
77849   if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
77850
77851   /* Delete all indices associated with this table. */
77852   for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
77853     pNext = pIndex->pNext;
77854     assert( pIndex->pSchema==pTable->pSchema );
77855     if( !db || db->pnBytesFreed==0 ){
77856       char *zName = pIndex->zName; 
77857       TESTONLY ( Index *pOld = ) sqlite3HashInsert(
77858           &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0
77859       );
77860       assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
77861       assert( pOld==pIndex || pOld==0 );
77862     }
77863     freeIndex(db, pIndex);
77864   }
77865
77866   /* Delete any foreign keys attached to this table. */
77867   sqlite3FkDelete(db, pTable);
77868
77869   /* Delete the Table structure itself.
77870   */
77871   sqliteDeleteColumnNames(db, pTable);
77872   sqlite3DbFree(db, pTable->zName);
77873   sqlite3DbFree(db, pTable->zColAff);
77874   sqlite3SelectDelete(db, pTable->pSelect);
77875 #ifndef SQLITE_OMIT_CHECK
77876   sqlite3ExprDelete(db, pTable->pCheck);
77877 #endif
77878 #ifndef SQLITE_OMIT_VIRTUALTABLE
77879   sqlite3VtabClear(db, pTable);
77880 #endif
77881   sqlite3DbFree(db, pTable);
77882 }
77883
77884 /*
77885 ** Unlink the given table from the hash tables and the delete the
77886 ** table structure with all its indices and foreign keys.
77887 */
77888 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
77889   Table *p;
77890   Db *pDb;
77891
77892   assert( db!=0 );
77893   assert( iDb>=0 && iDb<db->nDb );
77894   assert( zTabName );
77895   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
77896   testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
77897   pDb = &db->aDb[iDb];
77898   p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
77899                         sqlite3Strlen30(zTabName),0);
77900   sqlite3DeleteTable(db, p);
77901   db->flags |= SQLITE_InternChanges;
77902 }
77903
77904 /*
77905 ** Given a token, return a string that consists of the text of that
77906 ** token.  Space to hold the returned string
77907 ** is obtained from sqliteMalloc() and must be freed by the calling
77908 ** function.
77909 **
77910 ** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
77911 ** surround the body of the token are removed.
77912 **
77913 ** Tokens are often just pointers into the original SQL text and so
77914 ** are not \000 terminated and are not persistent.  The returned string
77915 ** is \000 terminated and is persistent.
77916 */
77917 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
77918   char *zName;
77919   if( pName ){
77920     zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
77921     sqlite3Dequote(zName);
77922   }else{
77923     zName = 0;
77924   }
77925   return zName;
77926 }
77927
77928 /*
77929 ** Open the sqlite_master table stored in database number iDb for
77930 ** writing. The table is opened using cursor 0.
77931 */
77932 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
77933   Vdbe *v = sqlite3GetVdbe(p);
77934   sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
77935   sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
77936   sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32);  /* 5 column table */
77937   if( p->nTab==0 ){
77938     p->nTab = 1;
77939   }
77940 }
77941
77942 /*
77943 ** Parameter zName points to a nul-terminated buffer containing the name
77944 ** of a database ("main", "temp" or the name of an attached db). This
77945 ** function returns the index of the named database in db->aDb[], or
77946 ** -1 if the named db cannot be found.
77947 */
77948 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
77949   int i = -1;         /* Database number */
77950   if( zName ){
77951     Db *pDb;
77952     int n = sqlite3Strlen30(zName);
77953     for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
77954       if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) && 
77955           0==sqlite3StrICmp(pDb->zName, zName) ){
77956         break;
77957       }
77958     }
77959   }
77960   return i;
77961 }
77962
77963 /*
77964 ** The token *pName contains the name of a database (either "main" or
77965 ** "temp" or the name of an attached db). This routine returns the
77966 ** index of the named database in db->aDb[], or -1 if the named db 
77967 ** does not exist.
77968 */
77969 SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
77970   int i;                               /* Database number */
77971   char *zName;                         /* Name we are searching for */
77972   zName = sqlite3NameFromToken(db, pName);
77973   i = sqlite3FindDbName(db, zName);
77974   sqlite3DbFree(db, zName);
77975   return i;
77976 }
77977
77978 /* The table or view or trigger name is passed to this routine via tokens
77979 ** pName1 and pName2. If the table name was fully qualified, for example:
77980 **
77981 ** CREATE TABLE xxx.yyy (...);
77982 ** 
77983 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
77984 ** the table name is not fully qualified, i.e.:
77985 **
77986 ** CREATE TABLE yyy(...);
77987 **
77988 ** Then pName1 is set to "yyy" and pName2 is "".
77989 **
77990 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
77991 ** pName2) that stores the unqualified table name.  The index of the
77992 ** database "xxx" is returned.
77993 */
77994 SQLITE_PRIVATE int sqlite3TwoPartName(
77995   Parse *pParse,      /* Parsing and code generating context */
77996   Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
77997   Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
77998   Token **pUnqual     /* Write the unqualified object name here */
77999 ){
78000   int iDb;                    /* Database holding the object */
78001   sqlite3 *db = pParse->db;
78002
78003   if( ALWAYS(pName2!=0) && pName2->n>0 ){
78004     if( db->init.busy ) {
78005       sqlite3ErrorMsg(pParse, "corrupt database");
78006       pParse->nErr++;
78007       return -1;
78008     }
78009     *pUnqual = pName2;
78010     iDb = sqlite3FindDb(db, pName1);
78011     if( iDb<0 ){
78012       sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
78013       pParse->nErr++;
78014       return -1;
78015     }
78016   }else{
78017     assert( db->init.iDb==0 || db->init.busy );
78018     iDb = db->init.iDb;
78019     *pUnqual = pName1;
78020   }
78021   return iDb;
78022 }
78023
78024 /*
78025 ** This routine is used to check if the UTF-8 string zName is a legal
78026 ** unqualified name for a new schema object (table, index, view or
78027 ** trigger). All names are legal except those that begin with the string
78028 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
78029 ** is reserved for internal use.
78030 */
78031 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
78032   if( !pParse->db->init.busy && pParse->nested==0 
78033           && (pParse->db->flags & SQLITE_WriteSchema)==0
78034           && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
78035     sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
78036     return SQLITE_ERROR;
78037   }
78038   return SQLITE_OK;
78039 }
78040
78041 /*
78042 ** Begin constructing a new table representation in memory.  This is
78043 ** the first of several action routines that get called in response
78044 ** to a CREATE TABLE statement.  In particular, this routine is called
78045 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
78046 ** flag is true if the table should be stored in the auxiliary database
78047 ** file instead of in the main database file.  This is normally the case
78048 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
78049 ** CREATE and TABLE.
78050 **
78051 ** The new table record is initialized and put in pParse->pNewTable.
78052 ** As more of the CREATE TABLE statement is parsed, additional action
78053 ** routines will be called to add more information to this record.
78054 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
78055 ** is called to complete the construction of the new table record.
78056 */
78057 SQLITE_PRIVATE void sqlite3StartTable(
78058   Parse *pParse,   /* Parser context */
78059   Token *pName1,   /* First part of the name of the table or view */
78060   Token *pName2,   /* Second part of the name of the table or view */
78061   int isTemp,      /* True if this is a TEMP table */
78062   int isView,      /* True if this is a VIEW */
78063   int isVirtual,   /* True if this is a VIRTUAL table */
78064   int noErr        /* Do nothing if table already exists */
78065 ){
78066   Table *pTable;
78067   char *zName = 0; /* The name of the new table */
78068   sqlite3 *db = pParse->db;
78069   Vdbe *v;
78070   int iDb;         /* Database number to create the table in */
78071   Token *pName;    /* Unqualified name of the table to create */
78072
78073   /* The table or view name to create is passed to this routine via tokens
78074   ** pName1 and pName2. If the table name was fully qualified, for example:
78075   **
78076   ** CREATE TABLE xxx.yyy (...);
78077   ** 
78078   ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
78079   ** the table name is not fully qualified, i.e.:
78080   **
78081   ** CREATE TABLE yyy(...);
78082   **
78083   ** Then pName1 is set to "yyy" and pName2 is "".
78084   **
78085   ** The call below sets the pName pointer to point at the token (pName1 or
78086   ** pName2) that stores the unqualified table name. The variable iDb is
78087   ** set to the index of the database that the table or view is to be
78088   ** created in.
78089   */
78090   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
78091   if( iDb<0 ) return;
78092   if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
78093     /* If creating a temp table, the name may not be qualified. Unless 
78094     ** the database name is "temp" anyway.  */
78095     sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
78096     return;
78097   }
78098   if( !OMIT_TEMPDB && isTemp ) iDb = 1;
78099
78100   pParse->sNameToken = *pName;
78101   zName = sqlite3NameFromToken(db, pName);
78102   if( zName==0 ) return;
78103   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
78104     goto begin_table_error;
78105   }
78106   if( db->init.iDb==1 ) isTemp = 1;
78107 #ifndef SQLITE_OMIT_AUTHORIZATION
78108   assert( (isTemp & 1)==isTemp );
78109   {
78110     int code;
78111     char *zDb = db->aDb[iDb].zName;
78112     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
78113       goto begin_table_error;
78114     }
78115     if( isView ){
78116       if( !OMIT_TEMPDB && isTemp ){
78117         code = SQLITE_CREATE_TEMP_VIEW;
78118       }else{
78119         code = SQLITE_CREATE_VIEW;
78120       }
78121     }else{
78122       if( !OMIT_TEMPDB && isTemp ){
78123         code = SQLITE_CREATE_TEMP_TABLE;
78124       }else{
78125         code = SQLITE_CREATE_TABLE;
78126       }
78127     }
78128     if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
78129       goto begin_table_error;
78130     }
78131   }
78132 #endif
78133
78134   /* Make sure the new table name does not collide with an existing
78135   ** index or table name in the same database.  Issue an error message if
78136   ** it does. The exception is if the statement being parsed was passed
78137   ** to an sqlite3_declare_vtab() call. In that case only the column names
78138   ** and types will be used, so there is no need to test for namespace
78139   ** collisions.
78140   */
78141   if( !IN_DECLARE_VTAB ){
78142     char *zDb = db->aDb[iDb].zName;
78143     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
78144       goto begin_table_error;
78145     }
78146     pTable = sqlite3FindTable(db, zName, zDb);
78147     if( pTable ){
78148       if( !noErr ){
78149         sqlite3ErrorMsg(pParse, "table %T already exists", pName);
78150       }else{
78151         assert( !db->init.busy );
78152         sqlite3CodeVerifySchema(pParse, iDb);
78153       }
78154       goto begin_table_error;
78155     }
78156     if( sqlite3FindIndex(db, zName, zDb)!=0 ){
78157       sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
78158       goto begin_table_error;
78159     }
78160   }
78161
78162   pTable = sqlite3DbMallocZero(db, sizeof(Table));
78163   if( pTable==0 ){
78164     db->mallocFailed = 1;
78165     pParse->rc = SQLITE_NOMEM;
78166     pParse->nErr++;
78167     goto begin_table_error;
78168   }
78169   pTable->zName = zName;
78170   pTable->iPKey = -1;
78171   pTable->pSchema = db->aDb[iDb].pSchema;
78172   pTable->nRef = 1;
78173   pTable->nRowEst = 1000000;
78174   assert( pParse->pNewTable==0 );
78175   pParse->pNewTable = pTable;
78176
78177   /* If this is the magic sqlite_sequence table used by autoincrement,
78178   ** then record a pointer to this table in the main database structure
78179   ** so that INSERT can find the table easily.
78180   */
78181 #ifndef SQLITE_OMIT_AUTOINCREMENT
78182   if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
78183     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
78184     pTable->pSchema->pSeqTab = pTable;
78185   }
78186 #endif
78187
78188   /* Begin generating the code that will insert the table record into
78189   ** the SQLITE_MASTER table.  Note in particular that we must go ahead
78190   ** and allocate the record number for the table entry now.  Before any
78191   ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
78192   ** indices to be created and the table record must come before the 
78193   ** indices.  Hence, the record number for the table must be allocated
78194   ** now.
78195   */
78196   if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
78197     int j1;
78198     int fileFormat;
78199     int reg1, reg2, reg3;
78200     sqlite3BeginWriteOperation(pParse, 0, iDb);
78201
78202 #ifndef SQLITE_OMIT_VIRTUALTABLE
78203     if( isVirtual ){
78204       sqlite3VdbeAddOp0(v, OP_VBegin);
78205     }
78206 #endif
78207
78208     /* If the file format and encoding in the database have not been set, 
78209     ** set them now.
78210     */
78211     reg1 = pParse->regRowid = ++pParse->nMem;
78212     reg2 = pParse->regRoot = ++pParse->nMem;
78213     reg3 = ++pParse->nMem;
78214     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
78215     sqlite3VdbeUsesBtree(v, iDb);
78216     j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
78217     fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
78218                   1 : SQLITE_MAX_FILE_FORMAT;
78219     sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
78220     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
78221     sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
78222     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
78223     sqlite3VdbeJumpHere(v, j1);
78224
78225     /* This just creates a place-holder record in the sqlite_master table.
78226     ** The record created does not contain anything yet.  It will be replaced
78227     ** by the real entry in code generated at sqlite3EndTable().
78228     **
78229     ** The rowid for the new entry is left in register pParse->regRowid.
78230     ** The root page number of the new table is left in reg pParse->regRoot.
78231     ** The rowid and root page number values are needed by the code that
78232     ** sqlite3EndTable will generate.
78233     */
78234 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
78235     if( isView || isVirtual ){
78236       sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
78237     }else
78238 #endif
78239     {
78240       sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
78241     }
78242     sqlite3OpenMasterTable(pParse, iDb);
78243     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
78244     sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
78245     sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
78246     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
78247     sqlite3VdbeAddOp0(v, OP_Close);
78248   }
78249
78250   /* Normal (non-error) return. */
78251   return;
78252
78253   /* If an error occurs, we jump here */
78254 begin_table_error:
78255   sqlite3DbFree(db, zName);
78256   return;
78257 }
78258
78259 /*
78260 ** This macro is used to compare two strings in a case-insensitive manner.
78261 ** It is slightly faster than calling sqlite3StrICmp() directly, but
78262 ** produces larger code.
78263 **
78264 ** WARNING: This macro is not compatible with the strcmp() family. It
78265 ** returns true if the two strings are equal, otherwise false.
78266 */
78267 #define STRICMP(x, y) (\
78268 sqlite3UpperToLower[*(unsigned char *)(x)]==   \
78269 sqlite3UpperToLower[*(unsigned char *)(y)]     \
78270 && sqlite3StrICmp((x)+1,(y)+1)==0 )
78271
78272 /*
78273 ** Add a new column to the table currently being constructed.
78274 **
78275 ** The parser calls this routine once for each column declaration
78276 ** in a CREATE TABLE statement.  sqlite3StartTable() gets called
78277 ** first to get things going.  Then this routine is called for each
78278 ** column.
78279 */
78280 SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
78281   Table *p;
78282   int i;
78283   char *z;
78284   Column *pCol;
78285   sqlite3 *db = pParse->db;
78286   if( (p = pParse->pNewTable)==0 ) return;
78287 #if SQLITE_MAX_COLUMN
78288   if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
78289     sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
78290     return;
78291   }
78292 #endif
78293   z = sqlite3NameFromToken(db, pName);
78294   if( z==0 ) return;
78295   for(i=0; i<p->nCol; i++){
78296     if( STRICMP(z, p->aCol[i].zName) ){
78297       sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
78298       sqlite3DbFree(db, z);
78299       return;
78300     }
78301   }
78302   if( (p->nCol & 0x7)==0 ){
78303     Column *aNew;
78304     aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
78305     if( aNew==0 ){
78306       sqlite3DbFree(db, z);
78307       return;
78308     }
78309     p->aCol = aNew;
78310   }
78311   pCol = &p->aCol[p->nCol];
78312   memset(pCol, 0, sizeof(p->aCol[0]));
78313   pCol->zName = z;
78314  
78315   /* If there is no type specified, columns have the default affinity
78316   ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
78317   ** be called next to set pCol->affinity correctly.
78318   */
78319   pCol->affinity = SQLITE_AFF_NONE;
78320   p->nCol++;
78321 }
78322
78323 /*
78324 ** This routine is called by the parser while in the middle of
78325 ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
78326 ** been seen on a column.  This routine sets the notNull flag on
78327 ** the column currently under construction.
78328 */
78329 SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
78330   Table *p;
78331   p = pParse->pNewTable;
78332   if( p==0 || NEVER(p->nCol<1) ) return;
78333   p->aCol[p->nCol-1].notNull = (u8)onError;
78334 }
78335
78336 /*
78337 ** Scan the column type name zType (length nType) and return the
78338 ** associated affinity type.
78339 **
78340 ** This routine does a case-independent search of zType for the 
78341 ** substrings in the following table. If one of the substrings is
78342 ** found, the corresponding affinity is returned. If zType contains
78343 ** more than one of the substrings, entries toward the top of 
78344 ** the table take priority. For example, if zType is 'BLOBINT', 
78345 ** SQLITE_AFF_INTEGER is returned.
78346 **
78347 ** Substring     | Affinity
78348 ** --------------------------------
78349 ** 'INT'         | SQLITE_AFF_INTEGER
78350 ** 'CHAR'        | SQLITE_AFF_TEXT
78351 ** 'CLOB'        | SQLITE_AFF_TEXT
78352 ** 'TEXT'        | SQLITE_AFF_TEXT
78353 ** 'BLOB'        | SQLITE_AFF_NONE
78354 ** 'REAL'        | SQLITE_AFF_REAL
78355 ** 'FLOA'        | SQLITE_AFF_REAL
78356 ** 'DOUB'        | SQLITE_AFF_REAL
78357 **
78358 ** If none of the substrings in the above table are found,
78359 ** SQLITE_AFF_NUMERIC is returned.
78360 */
78361 SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn){
78362   u32 h = 0;
78363   char aff = SQLITE_AFF_NUMERIC;
78364
78365   if( zIn ) while( zIn[0] ){
78366     h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
78367     zIn++;
78368     if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
78369       aff = SQLITE_AFF_TEXT; 
78370     }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
78371       aff = SQLITE_AFF_TEXT;
78372     }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
78373       aff = SQLITE_AFF_TEXT;
78374     }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
78375         && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
78376       aff = SQLITE_AFF_NONE;
78377 #ifndef SQLITE_OMIT_FLOATING_POINT
78378     }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
78379         && aff==SQLITE_AFF_NUMERIC ){
78380       aff = SQLITE_AFF_REAL;
78381     }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
78382         && aff==SQLITE_AFF_NUMERIC ){
78383       aff = SQLITE_AFF_REAL;
78384     }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
78385         && aff==SQLITE_AFF_NUMERIC ){
78386       aff = SQLITE_AFF_REAL;
78387 #endif
78388     }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
78389       aff = SQLITE_AFF_INTEGER;
78390       break;
78391     }
78392   }
78393
78394   return aff;
78395 }
78396
78397 /*
78398 ** This routine is called by the parser while in the middle of
78399 ** parsing a CREATE TABLE statement.  The pFirst token is the first
78400 ** token in the sequence of tokens that describe the type of the
78401 ** column currently under construction.   pLast is the last token
78402 ** in the sequence.  Use this information to construct a string
78403 ** that contains the typename of the column and store that string
78404 ** in zType.
78405 */ 
78406 SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
78407   Table *p;
78408   Column *pCol;
78409
78410   p = pParse->pNewTable;
78411   if( p==0 || NEVER(p->nCol<1) ) return;
78412   pCol = &p->aCol[p->nCol-1];
78413   assert( pCol->zType==0 );
78414   pCol->zType = sqlite3NameFromToken(pParse->db, pType);
78415   pCol->affinity = sqlite3AffinityType(pCol->zType);
78416 }
78417
78418 /*
78419 ** The expression is the default value for the most recently added column
78420 ** of the table currently under construction.
78421 **
78422 ** Default value expressions must be constant.  Raise an exception if this
78423 ** is not the case.
78424 **
78425 ** This routine is called by the parser while in the middle of
78426 ** parsing a CREATE TABLE statement.
78427 */
78428 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
78429   Table *p;
78430   Column *pCol;
78431   sqlite3 *db = pParse->db;
78432   p = pParse->pNewTable;
78433   if( p!=0 ){
78434     pCol = &(p->aCol[p->nCol-1]);
78435     if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
78436       sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
78437           pCol->zName);
78438     }else{
78439       /* A copy of pExpr is used instead of the original, as pExpr contains
78440       ** tokens that point to volatile memory. The 'span' of the expression
78441       ** is required by pragma table_info.
78442       */
78443       sqlite3ExprDelete(db, pCol->pDflt);
78444       pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
78445       sqlite3DbFree(db, pCol->zDflt);
78446       pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
78447                                      (int)(pSpan->zEnd - pSpan->zStart));
78448     }
78449   }
78450   sqlite3ExprDelete(db, pSpan->pExpr);
78451 }
78452
78453 /*
78454 ** Designate the PRIMARY KEY for the table.  pList is a list of names 
78455 ** of columns that form the primary key.  If pList is NULL, then the
78456 ** most recently added column of the table is the primary key.
78457 **
78458 ** A table can have at most one primary key.  If the table already has
78459 ** a primary key (and this is the second primary key) then create an
78460 ** error.
78461 **
78462 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
78463 ** then we will try to use that column as the rowid.  Set the Table.iPKey
78464 ** field of the table under construction to be the index of the
78465 ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
78466 ** no INTEGER PRIMARY KEY.
78467 **
78468 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
78469 ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
78470 */
78471 SQLITE_PRIVATE void sqlite3AddPrimaryKey(
78472   Parse *pParse,    /* Parsing context */
78473   ExprList *pList,  /* List of field names to be indexed */
78474   int onError,      /* What to do with a uniqueness conflict */
78475   int autoInc,      /* True if the AUTOINCREMENT keyword is present */
78476   int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
78477 ){
78478   Table *pTab = pParse->pNewTable;
78479   char *zType = 0;
78480   int iCol = -1, i;
78481   if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
78482   if( pTab->tabFlags & TF_HasPrimaryKey ){
78483     sqlite3ErrorMsg(pParse, 
78484       "table \"%s\" has more than one primary key", pTab->zName);
78485     goto primary_key_exit;
78486   }
78487   pTab->tabFlags |= TF_HasPrimaryKey;
78488   if( pList==0 ){
78489     iCol = pTab->nCol - 1;
78490     pTab->aCol[iCol].isPrimKey = 1;
78491   }else{
78492     for(i=0; i<pList->nExpr; i++){
78493       for(iCol=0; iCol<pTab->nCol; iCol++){
78494         if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
78495           break;
78496         }
78497       }
78498       if( iCol<pTab->nCol ){
78499         pTab->aCol[iCol].isPrimKey = 1;
78500       }
78501     }
78502     if( pList->nExpr>1 ) iCol = -1;
78503   }
78504   if( iCol>=0 && iCol<pTab->nCol ){
78505     zType = pTab->aCol[iCol].zType;
78506   }
78507   if( zType && sqlite3StrICmp(zType, "INTEGER")==0
78508         && sortOrder==SQLITE_SO_ASC ){
78509     pTab->iPKey = iCol;
78510     pTab->keyConf = (u8)onError;
78511     assert( autoInc==0 || autoInc==1 );
78512     pTab->tabFlags |= autoInc*TF_Autoincrement;
78513   }else if( autoInc ){
78514 #ifndef SQLITE_OMIT_AUTOINCREMENT
78515     sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
78516        "INTEGER PRIMARY KEY");
78517 #endif
78518   }else{
78519     Index *p;
78520     p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
78521     if( p ){
78522       p->autoIndex = 2;
78523     }
78524     pList = 0;
78525   }
78526
78527 primary_key_exit:
78528   sqlite3ExprListDelete(pParse->db, pList);
78529   return;
78530 }
78531
78532 /*
78533 ** Add a new CHECK constraint to the table currently under construction.
78534 */
78535 SQLITE_PRIVATE void sqlite3AddCheckConstraint(
78536   Parse *pParse,    /* Parsing context */
78537   Expr *pCheckExpr  /* The check expression */
78538 ){
78539   sqlite3 *db = pParse->db;
78540 #ifndef SQLITE_OMIT_CHECK
78541   Table *pTab = pParse->pNewTable;
78542   if( pTab && !IN_DECLARE_VTAB ){
78543     pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, pCheckExpr);
78544   }else
78545 #endif
78546   {
78547     sqlite3ExprDelete(db, pCheckExpr);
78548   }
78549 }
78550
78551 /*
78552 ** Set the collation function of the most recently parsed table column
78553 ** to the CollSeq given.
78554 */
78555 SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
78556   Table *p;
78557   int i;
78558   char *zColl;              /* Dequoted name of collation sequence */
78559   sqlite3 *db;
78560
78561   if( (p = pParse->pNewTable)==0 ) return;
78562   i = p->nCol-1;
78563   db = pParse->db;
78564   zColl = sqlite3NameFromToken(db, pToken);
78565   if( !zColl ) return;
78566
78567   if( sqlite3LocateCollSeq(pParse, zColl) ){
78568     Index *pIdx;
78569     p->aCol[i].zColl = zColl;
78570   
78571     /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
78572     ** then an index may have been created on this column before the
78573     ** collation type was added. Correct this if it is the case.
78574     */
78575     for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
78576       assert( pIdx->nColumn==1 );
78577       if( pIdx->aiColumn[0]==i ){
78578         pIdx->azColl[0] = p->aCol[i].zColl;
78579       }
78580     }
78581   }else{
78582     sqlite3DbFree(db, zColl);
78583   }
78584 }
78585
78586 /*
78587 ** This function returns the collation sequence for database native text
78588 ** encoding identified by the string zName, length nName.
78589 **
78590 ** If the requested collation sequence is not available, or not available
78591 ** in the database native encoding, the collation factory is invoked to
78592 ** request it. If the collation factory does not supply such a sequence,
78593 ** and the sequence is available in another text encoding, then that is
78594 ** returned instead.
78595 **
78596 ** If no versions of the requested collations sequence are available, or
78597 ** another error occurs, NULL is returned and an error message written into
78598 ** pParse.
78599 **
78600 ** This routine is a wrapper around sqlite3FindCollSeq().  This routine
78601 ** invokes the collation factory if the named collation cannot be found
78602 ** and generates an error message.
78603 **
78604 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
78605 */
78606 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
78607   sqlite3 *db = pParse->db;
78608   u8 enc = ENC(db);
78609   u8 initbusy = db->init.busy;
78610   CollSeq *pColl;
78611
78612   pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
78613   if( !initbusy && (!pColl || !pColl->xCmp) ){
78614     pColl = sqlite3GetCollSeq(db, enc, pColl, zName);
78615     if( !pColl ){
78616       sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
78617     }
78618   }
78619
78620   return pColl;
78621 }
78622
78623
78624 /*
78625 ** Generate code that will increment the schema cookie.
78626 **
78627 ** The schema cookie is used to determine when the schema for the
78628 ** database changes.  After each schema change, the cookie value
78629 ** changes.  When a process first reads the schema it records the
78630 ** cookie.  Thereafter, whenever it goes to access the database,
78631 ** it checks the cookie to make sure the schema has not changed
78632 ** since it was last read.
78633 **
78634 ** This plan is not completely bullet-proof.  It is possible for
78635 ** the schema to change multiple times and for the cookie to be
78636 ** set back to prior value.  But schema changes are infrequent
78637 ** and the probability of hitting the same cookie value is only
78638 ** 1 chance in 2^32.  So we're safe enough.
78639 */
78640 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
78641   int r1 = sqlite3GetTempReg(pParse);
78642   sqlite3 *db = pParse->db;
78643   Vdbe *v = pParse->pVdbe;
78644   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
78645   sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
78646   sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
78647   sqlite3ReleaseTempReg(pParse, r1);
78648 }
78649
78650 /*
78651 ** Measure the number of characters needed to output the given
78652 ** identifier.  The number returned includes any quotes used
78653 ** but does not include the null terminator.
78654 **
78655 ** The estimate is conservative.  It might be larger that what is
78656 ** really needed.
78657 */
78658 static int identLength(const char *z){
78659   int n;
78660   for(n=0; *z; n++, z++){
78661     if( *z=='"' ){ n++; }
78662   }
78663   return n + 2;
78664 }
78665
78666 /*
78667 ** The first parameter is a pointer to an output buffer. The second 
78668 ** parameter is a pointer to an integer that contains the offset at
78669 ** which to write into the output buffer. This function copies the
78670 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
78671 ** to the specified offset in the buffer and updates *pIdx to refer
78672 ** to the first byte after the last byte written before returning.
78673 ** 
78674 ** If the string zSignedIdent consists entirely of alpha-numeric
78675 ** characters, does not begin with a digit and is not an SQL keyword,
78676 ** then it is copied to the output buffer exactly as it is. Otherwise,
78677 ** it is quoted using double-quotes.
78678 */
78679 static void identPut(char *z, int *pIdx, char *zSignedIdent){
78680   unsigned char *zIdent = (unsigned char*)zSignedIdent;
78681   int i, j, needQuote;
78682   i = *pIdx;
78683
78684   for(j=0; zIdent[j]; j++){
78685     if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
78686   }
78687   needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
78688   if( !needQuote ){
78689     needQuote = zIdent[j];
78690   }
78691
78692   if( needQuote ) z[i++] = '"';
78693   for(j=0; zIdent[j]; j++){
78694     z[i++] = zIdent[j];
78695     if( zIdent[j]=='"' ) z[i++] = '"';
78696   }
78697   if( needQuote ) z[i++] = '"';
78698   z[i] = 0;
78699   *pIdx = i;
78700 }
78701
78702 /*
78703 ** Generate a CREATE TABLE statement appropriate for the given
78704 ** table.  Memory to hold the text of the statement is obtained
78705 ** from sqliteMalloc() and must be freed by the calling function.
78706 */
78707 static char *createTableStmt(sqlite3 *db, Table *p){
78708   int i, k, n;
78709   char *zStmt;
78710   char *zSep, *zSep2, *zEnd;
78711   Column *pCol;
78712   n = 0;
78713   for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
78714     n += identLength(pCol->zName) + 5;
78715   }
78716   n += identLength(p->zName);
78717   if( n<50 ){ 
78718     zSep = "";
78719     zSep2 = ",";
78720     zEnd = ")";
78721   }else{
78722     zSep = "\n  ";
78723     zSep2 = ",\n  ";
78724     zEnd = "\n)";
78725   }
78726   n += 35 + 6*p->nCol;
78727   zStmt = sqlite3DbMallocRaw(0, n);
78728   if( zStmt==0 ){
78729     db->mallocFailed = 1;
78730     return 0;
78731   }
78732   sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
78733   k = sqlite3Strlen30(zStmt);
78734   identPut(zStmt, &k, p->zName);
78735   zStmt[k++] = '(';
78736   for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
78737     static const char * const azType[] = {
78738         /* SQLITE_AFF_TEXT    */ " TEXT",
78739         /* SQLITE_AFF_NONE    */ "",
78740         /* SQLITE_AFF_NUMERIC */ " NUM",
78741         /* SQLITE_AFF_INTEGER */ " INT",
78742         /* SQLITE_AFF_REAL    */ " REAL"
78743     };
78744     int len;
78745     const char *zType;
78746
78747     sqlite3_snprintf(n-k, &zStmt[k], zSep);
78748     k += sqlite3Strlen30(&zStmt[k]);
78749     zSep = zSep2;
78750     identPut(zStmt, &k, pCol->zName);
78751     assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
78752     assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) );
78753     testcase( pCol->affinity==SQLITE_AFF_TEXT );
78754     testcase( pCol->affinity==SQLITE_AFF_NONE );
78755     testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
78756     testcase( pCol->affinity==SQLITE_AFF_INTEGER );
78757     testcase( pCol->affinity==SQLITE_AFF_REAL );
78758     
78759     zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
78760     len = sqlite3Strlen30(zType);
78761     assert( pCol->affinity==SQLITE_AFF_NONE 
78762             || pCol->affinity==sqlite3AffinityType(zType) );
78763     memcpy(&zStmt[k], zType, len);
78764     k += len;
78765     assert( k<=n );
78766   }
78767   sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
78768   return zStmt;
78769 }
78770
78771 /*
78772 ** This routine is called to report the final ")" that terminates
78773 ** a CREATE TABLE statement.
78774 **
78775 ** The table structure that other action routines have been building
78776 ** is added to the internal hash tables, assuming no errors have
78777 ** occurred.
78778 **
78779 ** An entry for the table is made in the master table on disk, unless
78780 ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
78781 ** it means we are reading the sqlite_master table because we just
78782 ** connected to the database or because the sqlite_master table has
78783 ** recently changed, so the entry for this table already exists in
78784 ** the sqlite_master table.  We do not want to create it again.
78785 **
78786 ** If the pSelect argument is not NULL, it means that this routine
78787 ** was called to create a table generated from a 
78788 ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
78789 ** the new table will match the result set of the SELECT.
78790 */
78791 SQLITE_PRIVATE void sqlite3EndTable(
78792   Parse *pParse,          /* Parse context */
78793   Token *pCons,           /* The ',' token after the last column defn. */
78794   Token *pEnd,            /* The final ')' token in the CREATE TABLE */
78795   Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
78796 ){
78797   Table *p;
78798   sqlite3 *db = pParse->db;
78799   int iDb;
78800
78801   if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
78802     return;
78803   }
78804   p = pParse->pNewTable;
78805   if( p==0 ) return;
78806
78807   assert( !db->init.busy || !pSelect );
78808
78809   iDb = sqlite3SchemaToIndex(db, p->pSchema);
78810
78811 #ifndef SQLITE_OMIT_CHECK
78812   /* Resolve names in all CHECK constraint expressions.
78813   */
78814   if( p->pCheck ){
78815     SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
78816     NameContext sNC;                /* Name context for pParse->pNewTable */
78817
78818     memset(&sNC, 0, sizeof(sNC));
78819     memset(&sSrc, 0, sizeof(sSrc));
78820     sSrc.nSrc = 1;
78821     sSrc.a[0].zName = p->zName;
78822     sSrc.a[0].pTab = p;
78823     sSrc.a[0].iCursor = -1;
78824     sNC.pParse = pParse;
78825     sNC.pSrcList = &sSrc;
78826     sNC.isCheck = 1;
78827     if( sqlite3ResolveExprNames(&sNC, p->pCheck) ){
78828       return;
78829     }
78830   }
78831 #endif /* !defined(SQLITE_OMIT_CHECK) */
78832
78833   /* If the db->init.busy is 1 it means we are reading the SQL off the
78834   ** "sqlite_master" or "sqlite_temp_master" table on the disk.
78835   ** So do not write to the disk again.  Extract the root page number
78836   ** for the table from the db->init.newTnum field.  (The page number
78837   ** should have been put there by the sqliteOpenCb routine.)
78838   */
78839   if( db->init.busy ){
78840     p->tnum = db->init.newTnum;
78841   }
78842
78843   /* If not initializing, then create a record for the new table
78844   ** in the SQLITE_MASTER table of the database.
78845   **
78846   ** If this is a TEMPORARY table, write the entry into the auxiliary
78847   ** file instead of into the main database file.
78848   */
78849   if( !db->init.busy ){
78850     int n;
78851     Vdbe *v;
78852     char *zType;    /* "view" or "table" */
78853     char *zType2;   /* "VIEW" or "TABLE" */
78854     char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
78855
78856     v = sqlite3GetVdbe(pParse);
78857     if( NEVER(v==0) ) return;
78858
78859     sqlite3VdbeAddOp1(v, OP_Close, 0);
78860
78861     /* 
78862     ** Initialize zType for the new view or table.
78863     */
78864     if( p->pSelect==0 ){
78865       /* A regular table */
78866       zType = "table";
78867       zType2 = "TABLE";
78868 #ifndef SQLITE_OMIT_VIEW
78869     }else{
78870       /* A view */
78871       zType = "view";
78872       zType2 = "VIEW";
78873 #endif
78874     }
78875
78876     /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
78877     ** statement to populate the new table. The root-page number for the
78878     ** new table is in register pParse->regRoot.
78879     **
78880     ** Once the SELECT has been coded by sqlite3Select(), it is in a
78881     ** suitable state to query for the column names and types to be used
78882     ** by the new table.
78883     **
78884     ** A shared-cache write-lock is not required to write to the new table,
78885     ** as a schema-lock must have already been obtained to create it. Since
78886     ** a schema-lock excludes all other database users, the write-lock would
78887     ** be redundant.
78888     */
78889     if( pSelect ){
78890       SelectDest dest;
78891       Table *pSelTab;
78892
78893       assert(pParse->nTab==1);
78894       sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
78895       sqlite3VdbeChangeP5(v, 1);
78896       pParse->nTab = 2;
78897       sqlite3SelectDestInit(&dest, SRT_Table, 1);
78898       sqlite3Select(pParse, pSelect, &dest);
78899       sqlite3VdbeAddOp1(v, OP_Close, 1);
78900       if( pParse->nErr==0 ){
78901         pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
78902         if( pSelTab==0 ) return;
78903         assert( p->aCol==0 );
78904         p->nCol = pSelTab->nCol;
78905         p->aCol = pSelTab->aCol;
78906         pSelTab->nCol = 0;
78907         pSelTab->aCol = 0;
78908         sqlite3DeleteTable(db, pSelTab);
78909       }
78910     }
78911
78912     /* Compute the complete text of the CREATE statement */
78913     if( pSelect ){
78914       zStmt = createTableStmt(db, p);
78915     }else{
78916       n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
78917       zStmt = sqlite3MPrintf(db, 
78918           "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
78919       );
78920     }
78921
78922     /* A slot for the record has already been allocated in the 
78923     ** SQLITE_MASTER table.  We just need to update that slot with all
78924     ** the information we've collected.
78925     */
78926     sqlite3NestedParse(pParse,
78927       "UPDATE %Q.%s "
78928          "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
78929        "WHERE rowid=#%d",
78930       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
78931       zType,
78932       p->zName,
78933       p->zName,
78934       pParse->regRoot,
78935       zStmt,
78936       pParse->regRowid
78937     );
78938     sqlite3DbFree(db, zStmt);
78939     sqlite3ChangeCookie(pParse, iDb);
78940
78941 #ifndef SQLITE_OMIT_AUTOINCREMENT
78942     /* Check to see if we need to create an sqlite_sequence table for
78943     ** keeping track of autoincrement keys.
78944     */
78945     if( p->tabFlags & TF_Autoincrement ){
78946       Db *pDb = &db->aDb[iDb];
78947       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
78948       if( pDb->pSchema->pSeqTab==0 ){
78949         sqlite3NestedParse(pParse,
78950           "CREATE TABLE %Q.sqlite_sequence(name,seq)",
78951           pDb->zName
78952         );
78953       }
78954     }
78955 #endif
78956
78957     /* Reparse everything to update our internal data structures */
78958     sqlite3VdbeAddParseSchemaOp(v, iDb,
78959                sqlite3MPrintf(db, "tbl_name='%q'", p->zName));
78960   }
78961
78962
78963   /* Add the table to the in-memory representation of the database.
78964   */
78965   if( db->init.busy ){
78966     Table *pOld;
78967     Schema *pSchema = p->pSchema;
78968     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
78969     pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
78970                              sqlite3Strlen30(p->zName),p);
78971     if( pOld ){
78972       assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
78973       db->mallocFailed = 1;
78974       return;
78975     }
78976     pParse->pNewTable = 0;
78977     db->nTable++;
78978     db->flags |= SQLITE_InternChanges;
78979
78980 #ifndef SQLITE_OMIT_ALTERTABLE
78981     if( !p->pSelect ){
78982       const char *zName = (const char *)pParse->sNameToken.z;
78983       int nName;
78984       assert( !pSelect && pCons && pEnd );
78985       if( pCons->z==0 ){
78986         pCons = pEnd;
78987       }
78988       nName = (int)((const char *)pCons->z - zName);
78989       p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
78990     }
78991 #endif
78992   }
78993 }
78994
78995 #ifndef SQLITE_OMIT_VIEW
78996 /*
78997 ** The parser calls this routine in order to create a new VIEW
78998 */
78999 SQLITE_PRIVATE void sqlite3CreateView(
79000   Parse *pParse,     /* The parsing context */
79001   Token *pBegin,     /* The CREATE token that begins the statement */
79002   Token *pName1,     /* The token that holds the name of the view */
79003   Token *pName2,     /* The token that holds the name of the view */
79004   Select *pSelect,   /* A SELECT statement that will become the new view */
79005   int isTemp,        /* TRUE for a TEMPORARY view */
79006   int noErr          /* Suppress error messages if VIEW already exists */
79007 ){
79008   Table *p;
79009   int n;
79010   const char *z;
79011   Token sEnd;
79012   DbFixer sFix;
79013   Token *pName;
79014   int iDb;
79015   sqlite3 *db = pParse->db;
79016
79017   if( pParse->nVar>0 ){
79018     sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
79019     sqlite3SelectDelete(db, pSelect);
79020     return;
79021   }
79022   sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
79023   p = pParse->pNewTable;
79024   if( p==0 || pParse->nErr ){
79025     sqlite3SelectDelete(db, pSelect);
79026     return;
79027   }
79028   sqlite3TwoPartName(pParse, pName1, pName2, &pName);
79029   iDb = sqlite3SchemaToIndex(db, p->pSchema);
79030   if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
79031     && sqlite3FixSelect(&sFix, pSelect)
79032   ){
79033     sqlite3SelectDelete(db, pSelect);
79034     return;
79035   }
79036
79037   /* Make a copy of the entire SELECT statement that defines the view.
79038   ** This will force all the Expr.token.z values to be dynamically
79039   ** allocated rather than point to the input string - which means that
79040   ** they will persist after the current sqlite3_exec() call returns.
79041   */
79042   p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
79043   sqlite3SelectDelete(db, pSelect);
79044   if( db->mallocFailed ){
79045     return;
79046   }
79047   if( !db->init.busy ){
79048     sqlite3ViewGetColumnNames(pParse, p);
79049   }
79050
79051   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
79052   ** the end.
79053   */
79054   sEnd = pParse->sLastToken;
79055   if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
79056     sEnd.z += sEnd.n;
79057   }
79058   sEnd.n = 0;
79059   n = (int)(sEnd.z - pBegin->z);
79060   z = pBegin->z;
79061   while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
79062   sEnd.z = &z[n-1];
79063   sEnd.n = 1;
79064
79065   /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
79066   sqlite3EndTable(pParse, 0, &sEnd, 0);
79067   return;
79068 }
79069 #endif /* SQLITE_OMIT_VIEW */
79070
79071 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
79072 /*
79073 ** The Table structure pTable is really a VIEW.  Fill in the names of
79074 ** the columns of the view in the pTable structure.  Return the number
79075 ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
79076 */
79077 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
79078   Table *pSelTab;   /* A fake table from which we get the result set */
79079   Select *pSel;     /* Copy of the SELECT that implements the view */
79080   int nErr = 0;     /* Number of errors encountered */
79081   int n;            /* Temporarily holds the number of cursors assigned */
79082   sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
79083   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
79084
79085   assert( pTable );
79086
79087 #ifndef SQLITE_OMIT_VIRTUALTABLE
79088   if( sqlite3VtabCallConnect(pParse, pTable) ){
79089     return SQLITE_ERROR;
79090   }
79091   if( IsVirtual(pTable) ) return 0;
79092 #endif
79093
79094 #ifndef SQLITE_OMIT_VIEW
79095   /* A positive nCol means the columns names for this view are
79096   ** already known.
79097   */
79098   if( pTable->nCol>0 ) return 0;
79099
79100   /* A negative nCol is a special marker meaning that we are currently
79101   ** trying to compute the column names.  If we enter this routine with
79102   ** a negative nCol, it means two or more views form a loop, like this:
79103   **
79104   **     CREATE VIEW one AS SELECT * FROM two;
79105   **     CREATE VIEW two AS SELECT * FROM one;
79106   **
79107   ** Actually, the error above is now caught prior to reaching this point.
79108   ** But the following test is still important as it does come up
79109   ** in the following:
79110   ** 
79111   **     CREATE TABLE main.ex1(a);
79112   **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
79113   **     SELECT * FROM temp.ex1;
79114   */
79115   if( pTable->nCol<0 ){
79116     sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
79117     return 1;
79118   }
79119   assert( pTable->nCol>=0 );
79120
79121   /* If we get this far, it means we need to compute the table names.
79122   ** Note that the call to sqlite3ResultSetOfSelect() will expand any
79123   ** "*" elements in the results set of the view and will assign cursors
79124   ** to the elements of the FROM clause.  But we do not want these changes
79125   ** to be permanent.  So the computation is done on a copy of the SELECT
79126   ** statement that defines the view.
79127   */
79128   assert( pTable->pSelect );
79129   pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
79130   if( pSel ){
79131     u8 enableLookaside = db->lookaside.bEnabled;
79132     n = pParse->nTab;
79133     sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
79134     pTable->nCol = -1;
79135     db->lookaside.bEnabled = 0;
79136 #ifndef SQLITE_OMIT_AUTHORIZATION
79137     xAuth = db->xAuth;
79138     db->xAuth = 0;
79139     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
79140     db->xAuth = xAuth;
79141 #else
79142     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
79143 #endif
79144     db->lookaside.bEnabled = enableLookaside;
79145     pParse->nTab = n;
79146     if( pSelTab ){
79147       assert( pTable->aCol==0 );
79148       pTable->nCol = pSelTab->nCol;
79149       pTable->aCol = pSelTab->aCol;
79150       pSelTab->nCol = 0;
79151       pSelTab->aCol = 0;
79152       sqlite3DeleteTable(db, pSelTab);
79153       assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
79154       pTable->pSchema->flags |= DB_UnresetViews;
79155     }else{
79156       pTable->nCol = 0;
79157       nErr++;
79158     }
79159     sqlite3SelectDelete(db, pSel);
79160   } else {
79161     nErr++;
79162   }
79163 #endif /* SQLITE_OMIT_VIEW */
79164   return nErr;  
79165 }
79166 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
79167
79168 #ifndef SQLITE_OMIT_VIEW
79169 /*
79170 ** Clear the column names from every VIEW in database idx.
79171 */
79172 static void sqliteViewResetAll(sqlite3 *db, int idx){
79173   HashElem *i;
79174   assert( sqlite3SchemaMutexHeld(db, idx, 0) );
79175   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
79176   for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
79177     Table *pTab = sqliteHashData(i);
79178     if( pTab->pSelect ){
79179       sqliteDeleteColumnNames(db, pTab);
79180       pTab->aCol = 0;
79181       pTab->nCol = 0;
79182     }
79183   }
79184   DbClearProperty(db, idx, DB_UnresetViews);
79185 }
79186 #else
79187 # define sqliteViewResetAll(A,B)
79188 #endif /* SQLITE_OMIT_VIEW */
79189
79190 /*
79191 ** This function is called by the VDBE to adjust the internal schema
79192 ** used by SQLite when the btree layer moves a table root page. The
79193 ** root-page of a table or index in database iDb has changed from iFrom
79194 ** to iTo.
79195 **
79196 ** Ticket #1728:  The symbol table might still contain information
79197 ** on tables and/or indices that are the process of being deleted.
79198 ** If you are unlucky, one of those deleted indices or tables might
79199 ** have the same rootpage number as the real table or index that is
79200 ** being moved.  So we cannot stop searching after the first match 
79201 ** because the first match might be for one of the deleted indices
79202 ** or tables and not the table/index that is actually being moved.
79203 ** We must continue looping until all tables and indices with
79204 ** rootpage==iFrom have been converted to have a rootpage of iTo
79205 ** in order to be certain that we got the right one.
79206 */
79207 #ifndef SQLITE_OMIT_AUTOVACUUM
79208 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
79209   HashElem *pElem;
79210   Hash *pHash;
79211   Db *pDb;
79212
79213   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
79214   pDb = &db->aDb[iDb];
79215   pHash = &pDb->pSchema->tblHash;
79216   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
79217     Table *pTab = sqliteHashData(pElem);
79218     if( pTab->tnum==iFrom ){
79219       pTab->tnum = iTo;
79220     }
79221   }
79222   pHash = &pDb->pSchema->idxHash;
79223   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
79224     Index *pIdx = sqliteHashData(pElem);
79225     if( pIdx->tnum==iFrom ){
79226       pIdx->tnum = iTo;
79227     }
79228   }
79229 }
79230 #endif
79231
79232 /*
79233 ** Write code to erase the table with root-page iTable from database iDb.
79234 ** Also write code to modify the sqlite_master table and internal schema
79235 ** if a root-page of another table is moved by the btree-layer whilst
79236 ** erasing iTable (this can happen with an auto-vacuum database).
79237 */ 
79238 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
79239   Vdbe *v = sqlite3GetVdbe(pParse);
79240   int r1 = sqlite3GetTempReg(pParse);
79241   sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
79242   sqlite3MayAbort(pParse);
79243 #ifndef SQLITE_OMIT_AUTOVACUUM
79244   /* OP_Destroy stores an in integer r1. If this integer
79245   ** is non-zero, then it is the root page number of a table moved to
79246   ** location iTable. The following code modifies the sqlite_master table to
79247   ** reflect this.
79248   **
79249   ** The "#NNN" in the SQL is a special constant that means whatever value
79250   ** is in register NNN.  See grammar rules associated with the TK_REGISTER
79251   ** token for additional information.
79252   */
79253   sqlite3NestedParse(pParse, 
79254      "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
79255      pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
79256 #endif
79257   sqlite3ReleaseTempReg(pParse, r1);
79258 }
79259
79260 /*
79261 ** Write VDBE code to erase table pTab and all associated indices on disk.
79262 ** Code to update the sqlite_master tables and internal schema definitions
79263 ** in case a root-page belonging to another table is moved by the btree layer
79264 ** is also added (this can happen with an auto-vacuum database).
79265 */
79266 static void destroyTable(Parse *pParse, Table *pTab){
79267 #ifdef SQLITE_OMIT_AUTOVACUUM
79268   Index *pIdx;
79269   int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
79270   destroyRootPage(pParse, pTab->tnum, iDb);
79271   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
79272     destroyRootPage(pParse, pIdx->tnum, iDb);
79273   }
79274 #else
79275   /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
79276   ** is not defined), then it is important to call OP_Destroy on the
79277   ** table and index root-pages in order, starting with the numerically 
79278   ** largest root-page number. This guarantees that none of the root-pages
79279   ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
79280   ** following were coded:
79281   **
79282   ** OP_Destroy 4 0
79283   ** ...
79284   ** OP_Destroy 5 0
79285   **
79286   ** and root page 5 happened to be the largest root-page number in the
79287   ** database, then root page 5 would be moved to page 4 by the 
79288   ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
79289   ** a free-list page.
79290   */
79291   int iTab = pTab->tnum;
79292   int iDestroyed = 0;
79293
79294   while( 1 ){
79295     Index *pIdx;
79296     int iLargest = 0;
79297
79298     if( iDestroyed==0 || iTab<iDestroyed ){
79299       iLargest = iTab;
79300     }
79301     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
79302       int iIdx = pIdx->tnum;
79303       assert( pIdx->pSchema==pTab->pSchema );
79304       if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
79305         iLargest = iIdx;
79306       }
79307     }
79308     if( iLargest==0 ){
79309       return;
79310     }else{
79311       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
79312       destroyRootPage(pParse, iLargest, iDb);
79313       iDestroyed = iLargest;
79314     }
79315   }
79316 #endif
79317 }
79318
79319 /*
79320 ** This routine is called to do the work of a DROP TABLE statement.
79321 ** pName is the name of the table to be dropped.
79322 */
79323 SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
79324   Table *pTab;
79325   Vdbe *v;
79326   sqlite3 *db = pParse->db;
79327   int iDb;
79328
79329   if( db->mallocFailed ){
79330     goto exit_drop_table;
79331   }
79332   assert( pParse->nErr==0 );
79333   assert( pName->nSrc==1 );
79334   if( noErr ) db->suppressErr++;
79335   pTab = sqlite3LocateTable(pParse, isView, 
79336                             pName->a[0].zName, pName->a[0].zDatabase);
79337   if( noErr ) db->suppressErr--;
79338
79339   if( pTab==0 ){
79340     if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
79341     goto exit_drop_table;
79342   }
79343   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
79344   assert( iDb>=0 && iDb<db->nDb );
79345
79346   /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
79347   ** it is initialized.
79348   */
79349   if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
79350     goto exit_drop_table;
79351   }
79352 #ifndef SQLITE_OMIT_AUTHORIZATION
79353   {
79354     int code;
79355     const char *zTab = SCHEMA_TABLE(iDb);
79356     const char *zDb = db->aDb[iDb].zName;
79357     const char *zArg2 = 0;
79358     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
79359       goto exit_drop_table;
79360     }
79361     if( isView ){
79362       if( !OMIT_TEMPDB && iDb==1 ){
79363         code = SQLITE_DROP_TEMP_VIEW;
79364       }else{
79365         code = SQLITE_DROP_VIEW;
79366       }
79367 #ifndef SQLITE_OMIT_VIRTUALTABLE
79368     }else if( IsVirtual(pTab) ){
79369       code = SQLITE_DROP_VTABLE;
79370       zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
79371 #endif
79372     }else{
79373       if( !OMIT_TEMPDB && iDb==1 ){
79374         code = SQLITE_DROP_TEMP_TABLE;
79375       }else{
79376         code = SQLITE_DROP_TABLE;
79377       }
79378     }
79379     if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
79380       goto exit_drop_table;
79381     }
79382     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
79383       goto exit_drop_table;
79384     }
79385   }
79386 #endif
79387   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
79388     sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
79389     goto exit_drop_table;
79390   }
79391
79392 #ifndef SQLITE_OMIT_VIEW
79393   /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
79394   ** on a table.
79395   */
79396   if( isView && pTab->pSelect==0 ){
79397     sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
79398     goto exit_drop_table;
79399   }
79400   if( !isView && pTab->pSelect ){
79401     sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
79402     goto exit_drop_table;
79403   }
79404 #endif
79405
79406   /* Generate code to remove the table from the master table
79407   ** on disk.
79408   */
79409   v = sqlite3GetVdbe(pParse);
79410   if( v ){
79411     Trigger *pTrigger;
79412     Db *pDb = &db->aDb[iDb];
79413     sqlite3BeginWriteOperation(pParse, 1, iDb);
79414
79415 #ifndef SQLITE_OMIT_VIRTUALTABLE
79416     if( IsVirtual(pTab) ){
79417       sqlite3VdbeAddOp0(v, OP_VBegin);
79418     }
79419 #endif
79420     sqlite3FkDropTable(pParse, pName, pTab);
79421
79422     /* Drop all triggers associated with the table being dropped. Code
79423     ** is generated to remove entries from sqlite_master and/or
79424     ** sqlite_temp_master if required.
79425     */
79426     pTrigger = sqlite3TriggerList(pParse, pTab);
79427     while( pTrigger ){
79428       assert( pTrigger->pSchema==pTab->pSchema || 
79429           pTrigger->pSchema==db->aDb[1].pSchema );
79430       sqlite3DropTriggerPtr(pParse, pTrigger);
79431       pTrigger = pTrigger->pNext;
79432     }
79433
79434 #ifndef SQLITE_OMIT_AUTOINCREMENT
79435     /* Remove any entries of the sqlite_sequence table associated with
79436     ** the table being dropped. This is done before the table is dropped
79437     ** at the btree level, in case the sqlite_sequence table needs to
79438     ** move as a result of the drop (can happen in auto-vacuum mode).
79439     */
79440     if( pTab->tabFlags & TF_Autoincrement ){
79441       sqlite3NestedParse(pParse,
79442         "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
79443         pDb->zName, pTab->zName
79444       );
79445     }
79446 #endif
79447
79448     /* Drop all SQLITE_MASTER table and index entries that refer to the
79449     ** table. The program name loops through the master table and deletes
79450     ** every row that refers to a table of the same name as the one being
79451     ** dropped. Triggers are handled seperately because a trigger can be
79452     ** created in the temp database that refers to a table in another
79453     ** database.
79454     */
79455     sqlite3NestedParse(pParse, 
79456         "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
79457         pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
79458
79459     /* Drop any statistics from the sqlite_stat1 table, if it exists */
79460     if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
79461       sqlite3NestedParse(pParse,
79462         "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb->zName, pTab->zName
79463       );
79464     }
79465
79466     if( !isView && !IsVirtual(pTab) ){
79467       destroyTable(pParse, pTab);
79468     }
79469
79470     /* Remove the table entry from SQLite's internal schema and modify
79471     ** the schema cookie.
79472     */
79473     if( IsVirtual(pTab) ){
79474       sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
79475     }
79476     sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
79477     sqlite3ChangeCookie(pParse, iDb);
79478   }
79479   sqliteViewResetAll(db, iDb);
79480
79481 exit_drop_table:
79482   sqlite3SrcListDelete(db, pName);
79483 }
79484
79485 /*
79486 ** This routine is called to create a new foreign key on the table
79487 ** currently under construction.  pFromCol determines which columns
79488 ** in the current table point to the foreign key.  If pFromCol==0 then
79489 ** connect the key to the last column inserted.  pTo is the name of
79490 ** the table referred to.  pToCol is a list of tables in the other
79491 ** pTo table that the foreign key points to.  flags contains all
79492 ** information about the conflict resolution algorithms specified
79493 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
79494 **
79495 ** An FKey structure is created and added to the table currently
79496 ** under construction in the pParse->pNewTable field.
79497 **
79498 ** The foreign key is set for IMMEDIATE processing.  A subsequent call
79499 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
79500 */
79501 SQLITE_PRIVATE void sqlite3CreateForeignKey(
79502   Parse *pParse,       /* Parsing context */
79503   ExprList *pFromCol,  /* Columns in this table that point to other table */
79504   Token *pTo,          /* Name of the other table */
79505   ExprList *pToCol,    /* Columns in the other table */
79506   int flags            /* Conflict resolution algorithms. */
79507 ){
79508   sqlite3 *db = pParse->db;
79509 #ifndef SQLITE_OMIT_FOREIGN_KEY
79510   FKey *pFKey = 0;
79511   FKey *pNextTo;
79512   Table *p = pParse->pNewTable;
79513   int nByte;
79514   int i;
79515   int nCol;
79516   char *z;
79517
79518   assert( pTo!=0 );
79519   if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
79520   if( pFromCol==0 ){
79521     int iCol = p->nCol-1;
79522     if( NEVER(iCol<0) ) goto fk_end;
79523     if( pToCol && pToCol->nExpr!=1 ){
79524       sqlite3ErrorMsg(pParse, "foreign key on %s"
79525          " should reference only one column of table %T",
79526          p->aCol[iCol].zName, pTo);
79527       goto fk_end;
79528     }
79529     nCol = 1;
79530   }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
79531     sqlite3ErrorMsg(pParse,
79532         "number of columns in foreign key does not match the number of "
79533         "columns in the referenced table");
79534     goto fk_end;
79535   }else{
79536     nCol = pFromCol->nExpr;
79537   }
79538   nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
79539   if( pToCol ){
79540     for(i=0; i<pToCol->nExpr; i++){
79541       nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
79542     }
79543   }
79544   pFKey = sqlite3DbMallocZero(db, nByte );
79545   if( pFKey==0 ){
79546     goto fk_end;
79547   }
79548   pFKey->pFrom = p;
79549   pFKey->pNextFrom = p->pFKey;
79550   z = (char*)&pFKey->aCol[nCol];
79551   pFKey->zTo = z;
79552   memcpy(z, pTo->z, pTo->n);
79553   z[pTo->n] = 0;
79554   sqlite3Dequote(z);
79555   z += pTo->n+1;
79556   pFKey->nCol = nCol;
79557   if( pFromCol==0 ){
79558     pFKey->aCol[0].iFrom = p->nCol-1;
79559   }else{
79560     for(i=0; i<nCol; i++){
79561       int j;
79562       for(j=0; j<p->nCol; j++){
79563         if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
79564           pFKey->aCol[i].iFrom = j;
79565           break;
79566         }
79567       }
79568       if( j>=p->nCol ){
79569         sqlite3ErrorMsg(pParse, 
79570           "unknown column \"%s\" in foreign key definition", 
79571           pFromCol->a[i].zName);
79572         goto fk_end;
79573       }
79574     }
79575   }
79576   if( pToCol ){
79577     for(i=0; i<nCol; i++){
79578       int n = sqlite3Strlen30(pToCol->a[i].zName);
79579       pFKey->aCol[i].zCol = z;
79580       memcpy(z, pToCol->a[i].zName, n);
79581       z[n] = 0;
79582       z += n+1;
79583     }
79584   }
79585   pFKey->isDeferred = 0;
79586   pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
79587   pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
79588
79589   assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
79590   pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash, 
79591       pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
79592   );
79593   if( pNextTo==pFKey ){
79594     db->mallocFailed = 1;
79595     goto fk_end;
79596   }
79597   if( pNextTo ){
79598     assert( pNextTo->pPrevTo==0 );
79599     pFKey->pNextTo = pNextTo;
79600     pNextTo->pPrevTo = pFKey;
79601   }
79602
79603   /* Link the foreign key to the table as the last step.
79604   */
79605   p->pFKey = pFKey;
79606   pFKey = 0;
79607
79608 fk_end:
79609   sqlite3DbFree(db, pFKey);
79610 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
79611   sqlite3ExprListDelete(db, pFromCol);
79612   sqlite3ExprListDelete(db, pToCol);
79613 }
79614
79615 /*
79616 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
79617 ** clause is seen as part of a foreign key definition.  The isDeferred
79618 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
79619 ** The behavior of the most recently created foreign key is adjusted
79620 ** accordingly.
79621 */
79622 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
79623 #ifndef SQLITE_OMIT_FOREIGN_KEY
79624   Table *pTab;
79625   FKey *pFKey;
79626   if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
79627   assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
79628   pFKey->isDeferred = (u8)isDeferred;
79629 #endif
79630 }
79631
79632 /*
79633 ** Generate code that will erase and refill index *pIdx.  This is
79634 ** used to initialize a newly created index or to recompute the
79635 ** content of an index in response to a REINDEX command.
79636 **
79637 ** if memRootPage is not negative, it means that the index is newly
79638 ** created.  The register specified by memRootPage contains the
79639 ** root page number of the index.  If memRootPage is negative, then
79640 ** the index already exists and must be cleared before being refilled and
79641 ** the root page number of the index is taken from pIndex->tnum.
79642 */
79643 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
79644   Table *pTab = pIndex->pTable;  /* The table that is indexed */
79645   int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
79646   int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
79647   int addr1;                     /* Address of top of loop */
79648   int tnum;                      /* Root page of index */
79649   Vdbe *v;                       /* Generate code into this virtual machine */
79650   KeyInfo *pKey;                 /* KeyInfo for index */
79651   int regIdxKey;                 /* Registers containing the index key */
79652   int regRecord;                 /* Register holding assemblied index record */
79653   sqlite3 *db = pParse->db;      /* The database connection */
79654   int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
79655
79656 #ifndef SQLITE_OMIT_AUTHORIZATION
79657   if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
79658       db->aDb[iDb].zName ) ){
79659     return;
79660   }
79661 #endif
79662
79663   /* Require a write-lock on the table to perform this operation */
79664   sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
79665
79666   v = sqlite3GetVdbe(pParse);
79667   if( v==0 ) return;
79668   if( memRootPage>=0 ){
79669     tnum = memRootPage;
79670   }else{
79671     tnum = pIndex->tnum;
79672     sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
79673   }
79674   pKey = sqlite3IndexKeyinfo(pParse, pIndex);
79675   sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, 
79676                     (char *)pKey, P4_KEYINFO_HANDOFF);
79677   if( memRootPage>=0 ){
79678     sqlite3VdbeChangeP5(v, 1);
79679   }
79680   sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
79681   addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
79682   regRecord = sqlite3GetTempReg(pParse);
79683   regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
79684   if( pIndex->onError!=OE_None ){
79685     const int regRowid = regIdxKey + pIndex->nColumn;
79686     const int j2 = sqlite3VdbeCurrentAddr(v) + 2;
79687     void * const pRegKey = SQLITE_INT_TO_PTR(regIdxKey);
79688
79689     /* The registers accessed by the OP_IsUnique opcode were allocated
79690     ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()
79691     ** call above. Just before that function was freed they were released
79692     ** (made available to the compiler for reuse) using 
79693     ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique
79694     ** opcode use the values stored within seems dangerous. However, since
79695     ** we can be sure that no other temp registers have been allocated
79696     ** since sqlite3ReleaseTempRange() was called, it is safe to do so.
79697     */
79698     sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);
79699     sqlite3HaltConstraint(
79700         pParse, OE_Abort, "indexed columns are not unique", P4_STATIC);
79701   }
79702   sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
79703   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
79704   sqlite3ReleaseTempReg(pParse, regRecord);
79705   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
79706   sqlite3VdbeJumpHere(v, addr1);
79707   sqlite3VdbeAddOp1(v, OP_Close, iTab);
79708   sqlite3VdbeAddOp1(v, OP_Close, iIdx);
79709 }
79710
79711 /*
79712 ** Create a new index for an SQL table.  pName1.pName2 is the name of the index 
79713 ** and pTblList is the name of the table that is to be indexed.  Both will 
79714 ** be NULL for a primary key or an index that is created to satisfy a
79715 ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
79716 ** as the table to be indexed.  pParse->pNewTable is a table that is
79717 ** currently being constructed by a CREATE TABLE statement.
79718 **
79719 ** pList is a list of columns to be indexed.  pList will be NULL if this
79720 ** is a primary key or unique-constraint on the most recent column added
79721 ** to the table currently under construction.  
79722 **
79723 ** If the index is created successfully, return a pointer to the new Index
79724 ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
79725 ** as the tables primary key (Index.autoIndex==2).
79726 */
79727 SQLITE_PRIVATE Index *sqlite3CreateIndex(
79728   Parse *pParse,     /* All information about this parse */
79729   Token *pName1,     /* First part of index name. May be NULL */
79730   Token *pName2,     /* Second part of index name. May be NULL */
79731   SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
79732   ExprList *pList,   /* A list of columns to be indexed */
79733   int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
79734   Token *pStart,     /* The CREATE token that begins this statement */
79735   Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
79736   int sortOrder,     /* Sort order of primary key when pList==NULL */
79737   int ifNotExist     /* Omit error if index already exists */
79738 ){
79739   Index *pRet = 0;     /* Pointer to return */
79740   Table *pTab = 0;     /* Table to be indexed */
79741   Index *pIndex = 0;   /* The index to be created */
79742   char *zName = 0;     /* Name of the index */
79743   int nName;           /* Number of characters in zName */
79744   int i, j;
79745   Token nullId;        /* Fake token for an empty ID list */
79746   DbFixer sFix;        /* For assigning database names to pTable */
79747   int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
79748   sqlite3 *db = pParse->db;
79749   Db *pDb;             /* The specific table containing the indexed database */
79750   int iDb;             /* Index of the database that is being written */
79751   Token *pName = 0;    /* Unqualified name of the index to create */
79752   struct ExprList_item *pListItem; /* For looping over pList */
79753   int nCol;
79754   int nExtra = 0;
79755   char *zExtra;
79756
79757   assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
79758   assert( pParse->nErr==0 );      /* Never called with prior errors */
79759   if( db->mallocFailed || IN_DECLARE_VTAB ){
79760     goto exit_create_index;
79761   }
79762   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
79763     goto exit_create_index;
79764   }
79765
79766   /*
79767   ** Find the table that is to be indexed.  Return early if not found.
79768   */
79769   if( pTblName!=0 ){
79770
79771     /* Use the two-part index name to determine the database 
79772     ** to search for the table. 'Fix' the table name to this db
79773     ** before looking up the table.
79774     */
79775     assert( pName1 && pName2 );
79776     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
79777     if( iDb<0 ) goto exit_create_index;
79778
79779 #ifndef SQLITE_OMIT_TEMPDB
79780     /* If the index name was unqualified, check if the the table
79781     ** is a temp table. If so, set the database to 1. Do not do this
79782     ** if initialising a database schema.
79783     */
79784     if( !db->init.busy ){
79785       pTab = sqlite3SrcListLookup(pParse, pTblName);
79786       if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
79787         iDb = 1;
79788       }
79789     }
79790 #endif
79791
79792     if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
79793         sqlite3FixSrcList(&sFix, pTblName)
79794     ){
79795       /* Because the parser constructs pTblName from a single identifier,
79796       ** sqlite3FixSrcList can never fail. */
79797       assert(0);
79798     }
79799     pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName, 
79800         pTblName->a[0].zDatabase);
79801     if( !pTab || db->mallocFailed ) goto exit_create_index;
79802     assert( db->aDb[iDb].pSchema==pTab->pSchema );
79803   }else{
79804     assert( pName==0 );
79805     pTab = pParse->pNewTable;
79806     if( !pTab ) goto exit_create_index;
79807     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
79808   }
79809   pDb = &db->aDb[iDb];
79810
79811   assert( pTab!=0 );
79812   assert( pParse->nErr==0 );
79813   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 
79814        && memcmp(&pTab->zName[7],"altertab_",9)!=0 ){
79815     sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
79816     goto exit_create_index;
79817   }
79818 #ifndef SQLITE_OMIT_VIEW
79819   if( pTab->pSelect ){
79820     sqlite3ErrorMsg(pParse, "views may not be indexed");
79821     goto exit_create_index;
79822   }
79823 #endif
79824 #ifndef SQLITE_OMIT_VIRTUALTABLE
79825   if( IsVirtual(pTab) ){
79826     sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
79827     goto exit_create_index;
79828   }
79829 #endif
79830
79831   /*
79832   ** Find the name of the index.  Make sure there is not already another
79833   ** index or table with the same name.  
79834   **
79835   ** Exception:  If we are reading the names of permanent indices from the
79836   ** sqlite_master table (because some other process changed the schema) and
79837   ** one of the index names collides with the name of a temporary table or
79838   ** index, then we will continue to process this index.
79839   **
79840   ** If pName==0 it means that we are
79841   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
79842   ** own name.
79843   */
79844   if( pName ){
79845     zName = sqlite3NameFromToken(db, pName);
79846     if( zName==0 ) goto exit_create_index;
79847     if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
79848       goto exit_create_index;
79849     }
79850     if( !db->init.busy ){
79851       if( sqlite3FindTable(db, zName, 0)!=0 ){
79852         sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
79853         goto exit_create_index;
79854       }
79855     }
79856     if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
79857       if( !ifNotExist ){
79858         sqlite3ErrorMsg(pParse, "index %s already exists", zName);
79859       }else{
79860         assert( !db->init.busy );
79861         sqlite3CodeVerifySchema(pParse, iDb);
79862       }
79863       goto exit_create_index;
79864     }
79865   }else{
79866     int n;
79867     Index *pLoop;
79868     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
79869     zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
79870     if( zName==0 ){
79871       goto exit_create_index;
79872     }
79873   }
79874
79875   /* Check for authorization to create an index.
79876   */
79877 #ifndef SQLITE_OMIT_AUTHORIZATION
79878   {
79879     const char *zDb = pDb->zName;
79880     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
79881       goto exit_create_index;
79882     }
79883     i = SQLITE_CREATE_INDEX;
79884     if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
79885     if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
79886       goto exit_create_index;
79887     }
79888   }
79889 #endif
79890
79891   /* If pList==0, it means this routine was called to make a primary
79892   ** key out of the last column added to the table under construction.
79893   ** So create a fake list to simulate this.
79894   */
79895   if( pList==0 ){
79896     nullId.z = pTab->aCol[pTab->nCol-1].zName;
79897     nullId.n = sqlite3Strlen30((char*)nullId.z);
79898     pList = sqlite3ExprListAppend(pParse, 0, 0);
79899     if( pList==0 ) goto exit_create_index;
79900     sqlite3ExprListSetName(pParse, pList, &nullId, 0);
79901     pList->a[0].sortOrder = (u8)sortOrder;
79902   }
79903
79904   /* Figure out how many bytes of space are required to store explicitly
79905   ** specified collation sequence names.
79906   */
79907   for(i=0; i<pList->nExpr; i++){
79908     Expr *pExpr = pList->a[i].pExpr;
79909     if( pExpr ){
79910       CollSeq *pColl = pExpr->pColl;
79911       /* Either pColl!=0 or there was an OOM failure.  But if an OOM
79912       ** failure we have quit before reaching this point. */
79913       if( ALWAYS(pColl) ){
79914         nExtra += (1 + sqlite3Strlen30(pColl->zName));
79915       }
79916     }
79917   }
79918
79919   /* 
79920   ** Allocate the index structure. 
79921   */
79922   nName = sqlite3Strlen30(zName);
79923   nCol = pList->nExpr;
79924   pIndex = sqlite3DbMallocZero(db, 
79925       sizeof(Index) +              /* Index structure  */
79926       sizeof(int)*nCol +           /* Index.aiColumn   */
79927       sizeof(int)*(nCol+1) +       /* Index.aiRowEst   */
79928       sizeof(char *)*nCol +        /* Index.azColl     */
79929       sizeof(u8)*nCol +            /* Index.aSortOrder */
79930       nName + 1 +                  /* Index.zName      */
79931       nExtra                       /* Collation sequence names */
79932   );
79933   if( db->mallocFailed ){
79934     goto exit_create_index;
79935   }
79936   pIndex->azColl = (char**)(&pIndex[1]);
79937   pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
79938   pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
79939   pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
79940   pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
79941   zExtra = (char *)(&pIndex->zName[nName+1]);
79942   memcpy(pIndex->zName, zName, nName+1);
79943   pIndex->pTable = pTab;
79944   pIndex->nColumn = pList->nExpr;
79945   pIndex->onError = (u8)onError;
79946   pIndex->autoIndex = (u8)(pName==0);
79947   pIndex->pSchema = db->aDb[iDb].pSchema;
79948   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
79949
79950   /* Check to see if we should honor DESC requests on index columns
79951   */
79952   if( pDb->pSchema->file_format>=4 ){
79953     sortOrderMask = -1;   /* Honor DESC */
79954   }else{
79955     sortOrderMask = 0;    /* Ignore DESC */
79956   }
79957
79958   /* Scan the names of the columns of the table to be indexed and
79959   ** load the column indices into the Index structure.  Report an error
79960   ** if any column is not found.
79961   **
79962   ** TODO:  Add a test to make sure that the same column is not named
79963   ** more than once within the same index.  Only the first instance of
79964   ** the column will ever be used by the optimizer.  Note that using the
79965   ** same column more than once cannot be an error because that would 
79966   ** break backwards compatibility - it needs to be a warning.
79967   */
79968   for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
79969     const char *zColName = pListItem->zName;
79970     Column *pTabCol;
79971     int requestedSortOrder;
79972     char *zColl;                   /* Collation sequence name */
79973
79974     for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
79975       if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
79976     }
79977     if( j>=pTab->nCol ){
79978       sqlite3ErrorMsg(pParse, "table %s has no column named %s",
79979         pTab->zName, zColName);
79980       pParse->checkSchema = 1;
79981       goto exit_create_index;
79982     }
79983     pIndex->aiColumn[i] = j;
79984     /* Justification of the ALWAYS(pListItem->pExpr->pColl):  Because of
79985     ** the way the "idxlist" non-terminal is constructed by the parser,
79986     ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl
79987     ** must exist or else there must have been an OOM error.  But if there
79988     ** was an OOM error, we would never reach this point. */
79989     if( pListItem->pExpr && ALWAYS(pListItem->pExpr->pColl) ){
79990       int nColl;
79991       zColl = pListItem->pExpr->pColl->zName;
79992       nColl = sqlite3Strlen30(zColl) + 1;
79993       assert( nExtra>=nColl );
79994       memcpy(zExtra, zColl, nColl);
79995       zColl = zExtra;
79996       zExtra += nColl;
79997       nExtra -= nColl;
79998     }else{
79999       zColl = pTab->aCol[j].zColl;
80000       if( !zColl ){
80001         zColl = db->pDfltColl->zName;
80002       }
80003     }
80004     if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
80005       goto exit_create_index;
80006     }
80007     pIndex->azColl[i] = zColl;
80008     requestedSortOrder = pListItem->sortOrder & sortOrderMask;
80009     pIndex->aSortOrder[i] = (u8)requestedSortOrder;
80010   }
80011   sqlite3DefaultRowEst(pIndex);
80012
80013   if( pTab==pParse->pNewTable ){
80014     /* This routine has been called to create an automatic index as a
80015     ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
80016     ** a PRIMARY KEY or UNIQUE clause following the column definitions.
80017     ** i.e. one of:
80018     **
80019     ** CREATE TABLE t(x PRIMARY KEY, y);
80020     ** CREATE TABLE t(x, y, UNIQUE(x, y));
80021     **
80022     ** Either way, check to see if the table already has such an index. If
80023     ** so, don't bother creating this one. This only applies to
80024     ** automatically created indices. Users can do as they wish with
80025     ** explicit indices.
80026     **
80027     ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
80028     ** (and thus suppressing the second one) even if they have different
80029     ** sort orders.
80030     **
80031     ** If there are different collating sequences or if the columns of
80032     ** the constraint occur in different orders, then the constraints are
80033     ** considered distinct and both result in separate indices.
80034     */
80035     Index *pIdx;
80036     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
80037       int k;
80038       assert( pIdx->onError!=OE_None );
80039       assert( pIdx->autoIndex );
80040       assert( pIndex->onError!=OE_None );
80041
80042       if( pIdx->nColumn!=pIndex->nColumn ) continue;
80043       for(k=0; k<pIdx->nColumn; k++){
80044         const char *z1;
80045         const char *z2;
80046         if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
80047         z1 = pIdx->azColl[k];
80048         z2 = pIndex->azColl[k];
80049         if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
80050       }
80051       if( k==pIdx->nColumn ){
80052         if( pIdx->onError!=pIndex->onError ){
80053           /* This constraint creates the same index as a previous
80054           ** constraint specified somewhere in the CREATE TABLE statement.
80055           ** However the ON CONFLICT clauses are different. If both this 
80056           ** constraint and the previous equivalent constraint have explicit
80057           ** ON CONFLICT clauses this is an error. Otherwise, use the
80058           ** explicitly specified behaviour for the index.
80059           */
80060           if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
80061             sqlite3ErrorMsg(pParse, 
80062                 "conflicting ON CONFLICT clauses specified", 0);
80063           }
80064           if( pIdx->onError==OE_Default ){
80065             pIdx->onError = pIndex->onError;
80066           }
80067         }
80068         goto exit_create_index;
80069       }
80070     }
80071   }
80072
80073   /* Link the new Index structure to its table and to the other
80074   ** in-memory database structures. 
80075   */
80076   if( db->init.busy ){
80077     Index *p;
80078     assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
80079     p = sqlite3HashInsert(&pIndex->pSchema->idxHash, 
80080                           pIndex->zName, sqlite3Strlen30(pIndex->zName),
80081                           pIndex);
80082     if( p ){
80083       assert( p==pIndex );  /* Malloc must have failed */
80084       db->mallocFailed = 1;
80085       goto exit_create_index;
80086     }
80087     db->flags |= SQLITE_InternChanges;
80088     if( pTblName!=0 ){
80089       pIndex->tnum = db->init.newTnum;
80090     }
80091   }
80092
80093   /* If the db->init.busy is 0 then create the index on disk.  This
80094   ** involves writing the index into the master table and filling in the
80095   ** index with the current table contents.
80096   **
80097   ** The db->init.busy is 0 when the user first enters a CREATE INDEX 
80098   ** command.  db->init.busy is 1 when a database is opened and 
80099   ** CREATE INDEX statements are read out of the master table.  In
80100   ** the latter case the index already exists on disk, which is why
80101   ** we don't want to recreate it.
80102   **
80103   ** If pTblName==0 it means this index is generated as a primary key
80104   ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
80105   ** has just been created, it contains no data and the index initialization
80106   ** step can be skipped.
80107   */
80108   else{ /* if( db->init.busy==0 ) */
80109     Vdbe *v;
80110     char *zStmt;
80111     int iMem = ++pParse->nMem;
80112
80113     v = sqlite3GetVdbe(pParse);
80114     if( v==0 ) goto exit_create_index;
80115
80116
80117     /* Create the rootpage for the index
80118     */
80119     sqlite3BeginWriteOperation(pParse, 1, iDb);
80120     sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
80121
80122     /* Gather the complete text of the CREATE INDEX statement into
80123     ** the zStmt variable
80124     */
80125     if( pStart ){
80126       assert( pEnd!=0 );
80127       /* A named index with an explicit CREATE INDEX statement */
80128       zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
80129         onError==OE_None ? "" : " UNIQUE",
80130         pEnd->z - pName->z + 1,
80131         pName->z);
80132     }else{
80133       /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
80134       /* zStmt = sqlite3MPrintf(""); */
80135       zStmt = 0;
80136     }
80137
80138     /* Add an entry in sqlite_master for this index
80139     */
80140     sqlite3NestedParse(pParse, 
80141         "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
80142         db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
80143         pIndex->zName,
80144         pTab->zName,
80145         iMem,
80146         zStmt
80147     );
80148     sqlite3DbFree(db, zStmt);
80149
80150     /* Fill the index with data and reparse the schema. Code an OP_Expire
80151     ** to invalidate all pre-compiled statements.
80152     */
80153     if( pTblName ){
80154       sqlite3RefillIndex(pParse, pIndex, iMem);
80155       sqlite3ChangeCookie(pParse, iDb);
80156       sqlite3VdbeAddParseSchemaOp(v, iDb,
80157          sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
80158       sqlite3VdbeAddOp1(v, OP_Expire, 0);
80159     }
80160   }
80161
80162   /* When adding an index to the list of indices for a table, make
80163   ** sure all indices labeled OE_Replace come after all those labeled
80164   ** OE_Ignore.  This is necessary for the correct constraint check
80165   ** processing (in sqlite3GenerateConstraintChecks()) as part of
80166   ** UPDATE and INSERT statements.  
80167   */
80168   if( db->init.busy || pTblName==0 ){
80169     if( onError!=OE_Replace || pTab->pIndex==0
80170          || pTab->pIndex->onError==OE_Replace){
80171       pIndex->pNext = pTab->pIndex;
80172       pTab->pIndex = pIndex;
80173     }else{
80174       Index *pOther = pTab->pIndex;
80175       while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
80176         pOther = pOther->pNext;
80177       }
80178       pIndex->pNext = pOther->pNext;
80179       pOther->pNext = pIndex;
80180     }
80181     pRet = pIndex;
80182     pIndex = 0;
80183   }
80184
80185   /* Clean up before exiting */
80186 exit_create_index:
80187   if( pIndex ){
80188     sqlite3DbFree(db, pIndex->zColAff);
80189     sqlite3DbFree(db, pIndex);
80190   }
80191   sqlite3ExprListDelete(db, pList);
80192   sqlite3SrcListDelete(db, pTblName);
80193   sqlite3DbFree(db, zName);
80194   return pRet;
80195 }
80196
80197 /*
80198 ** Fill the Index.aiRowEst[] array with default information - information
80199 ** to be used when we have not run the ANALYZE command.
80200 **
80201 ** aiRowEst[0] is suppose to contain the number of elements in the index.
80202 ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
80203 ** number of rows in the table that match any particular value of the
80204 ** first column of the index.  aiRowEst[2] is an estimate of the number
80205 ** of rows that match any particular combiniation of the first 2 columns
80206 ** of the index.  And so forth.  It must always be the case that
80207 *
80208 **           aiRowEst[N]<=aiRowEst[N-1]
80209 **           aiRowEst[N]>=1
80210 **
80211 ** Apart from that, we have little to go on besides intuition as to
80212 ** how aiRowEst[] should be initialized.  The numbers generated here
80213 ** are based on typical values found in actual indices.
80214 */
80215 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
80216   unsigned *a = pIdx->aiRowEst;
80217   int i;
80218   unsigned n;
80219   assert( a!=0 );
80220   a[0] = pIdx->pTable->nRowEst;
80221   if( a[0]<10 ) a[0] = 10;
80222   n = 10;
80223   for(i=1; i<=pIdx->nColumn; i++){
80224     a[i] = n;
80225     if( n>5 ) n--;
80226   }
80227   if( pIdx->onError!=OE_None ){
80228     a[pIdx->nColumn] = 1;
80229   }
80230 }
80231
80232 /*
80233 ** This routine will drop an existing named index.  This routine
80234 ** implements the DROP INDEX statement.
80235 */
80236 SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
80237   Index *pIndex;
80238   Vdbe *v;
80239   sqlite3 *db = pParse->db;
80240   int iDb;
80241
80242   assert( pParse->nErr==0 );   /* Never called with prior errors */
80243   if( db->mallocFailed ){
80244     goto exit_drop_index;
80245   }
80246   assert( pName->nSrc==1 );
80247   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
80248     goto exit_drop_index;
80249   }
80250   pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
80251   if( pIndex==0 ){
80252     if( !ifExists ){
80253       sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
80254     }else{
80255       sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
80256     }
80257     pParse->checkSchema = 1;
80258     goto exit_drop_index;
80259   }
80260   if( pIndex->autoIndex ){
80261     sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
80262       "or PRIMARY KEY constraint cannot be dropped", 0);
80263     goto exit_drop_index;
80264   }
80265   iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
80266 #ifndef SQLITE_OMIT_AUTHORIZATION
80267   {
80268     int code = SQLITE_DROP_INDEX;
80269     Table *pTab = pIndex->pTable;
80270     const char *zDb = db->aDb[iDb].zName;
80271     const char *zTab = SCHEMA_TABLE(iDb);
80272     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
80273       goto exit_drop_index;
80274     }
80275     if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
80276     if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
80277       goto exit_drop_index;
80278     }
80279   }
80280 #endif
80281
80282   /* Generate code to remove the index and from the master table */
80283   v = sqlite3GetVdbe(pParse);
80284   if( v ){
80285     sqlite3BeginWriteOperation(pParse, 1, iDb);
80286     sqlite3NestedParse(pParse,
80287        "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
80288        db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
80289        pIndex->zName
80290     );
80291     if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
80292       sqlite3NestedParse(pParse,
80293         "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q",
80294         db->aDb[iDb].zName, pIndex->zName
80295       );
80296     }
80297     sqlite3ChangeCookie(pParse, iDb);
80298     destroyRootPage(pParse, pIndex->tnum, iDb);
80299     sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
80300   }
80301
80302 exit_drop_index:
80303   sqlite3SrcListDelete(db, pName);
80304 }
80305
80306 /*
80307 ** pArray is a pointer to an array of objects.  Each object in the
80308 ** array is szEntry bytes in size.  This routine allocates a new
80309 ** object on the end of the array.
80310 **
80311 ** *pnEntry is the number of entries already in use.  *pnAlloc is
80312 ** the previously allocated size of the array.  initSize is the
80313 ** suggested initial array size allocation.
80314 **
80315 ** The index of the new entry is returned in *pIdx.
80316 **
80317 ** This routine returns a pointer to the array of objects.  This
80318 ** might be the same as the pArray parameter or it might be a different
80319 ** pointer if the array was resized.
80320 */
80321 SQLITE_PRIVATE void *sqlite3ArrayAllocate(
80322   sqlite3 *db,      /* Connection to notify of malloc failures */
80323   void *pArray,     /* Array of objects.  Might be reallocated */
80324   int szEntry,      /* Size of each object in the array */
80325   int initSize,     /* Suggested initial allocation, in elements */
80326   int *pnEntry,     /* Number of objects currently in use */
80327   int *pnAlloc,     /* Current size of the allocation, in elements */
80328   int *pIdx         /* Write the index of a new slot here */
80329 ){
80330   char *z;
80331   if( *pnEntry >= *pnAlloc ){
80332     void *pNew;
80333     int newSize;
80334     newSize = (*pnAlloc)*2 + initSize;
80335     pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
80336     if( pNew==0 ){
80337       *pIdx = -1;
80338       return pArray;
80339     }
80340     *pnAlloc = sqlite3DbMallocSize(db, pNew)/szEntry;
80341     pArray = pNew;
80342   }
80343   z = (char*)pArray;
80344   memset(&z[*pnEntry * szEntry], 0, szEntry);
80345   *pIdx = *pnEntry;
80346   ++*pnEntry;
80347   return pArray;
80348 }
80349
80350 /*
80351 ** Append a new element to the given IdList.  Create a new IdList if
80352 ** need be.
80353 **
80354 ** A new IdList is returned, or NULL if malloc() fails.
80355 */
80356 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
80357   int i;
80358   if( pList==0 ){
80359     pList = sqlite3DbMallocZero(db, sizeof(IdList) );
80360     if( pList==0 ) return 0;
80361     pList->nAlloc = 0;
80362   }
80363   pList->a = sqlite3ArrayAllocate(
80364       db,
80365       pList->a,
80366       sizeof(pList->a[0]),
80367       5,
80368       &pList->nId,
80369       &pList->nAlloc,
80370       &i
80371   );
80372   if( i<0 ){
80373     sqlite3IdListDelete(db, pList);
80374     return 0;
80375   }
80376   pList->a[i].zName = sqlite3NameFromToken(db, pToken);
80377   return pList;
80378 }
80379
80380 /*
80381 ** Delete an IdList.
80382 */
80383 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
80384   int i;
80385   if( pList==0 ) return;
80386   for(i=0; i<pList->nId; i++){
80387     sqlite3DbFree(db, pList->a[i].zName);
80388   }
80389   sqlite3DbFree(db, pList->a);
80390   sqlite3DbFree(db, pList);
80391 }
80392
80393 /*
80394 ** Return the index in pList of the identifier named zId.  Return -1
80395 ** if not found.
80396 */
80397 SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
80398   int i;
80399   if( pList==0 ) return -1;
80400   for(i=0; i<pList->nId; i++){
80401     if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
80402   }
80403   return -1;
80404 }
80405
80406 /*
80407 ** Expand the space allocated for the given SrcList object by
80408 ** creating nExtra new slots beginning at iStart.  iStart is zero based.
80409 ** New slots are zeroed.
80410 **
80411 ** For example, suppose a SrcList initially contains two entries: A,B.
80412 ** To append 3 new entries onto the end, do this:
80413 **
80414 **    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
80415 **
80416 ** After the call above it would contain:  A, B, nil, nil, nil.
80417 ** If the iStart argument had been 1 instead of 2, then the result
80418 ** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
80419 ** the iStart value would be 0.  The result then would
80420 ** be: nil, nil, nil, A, B.
80421 **
80422 ** If a memory allocation fails the SrcList is unchanged.  The
80423 ** db->mallocFailed flag will be set to true.
80424 */
80425 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
80426   sqlite3 *db,       /* Database connection to notify of OOM errors */
80427   SrcList *pSrc,     /* The SrcList to be enlarged */
80428   int nExtra,        /* Number of new slots to add to pSrc->a[] */
80429   int iStart         /* Index in pSrc->a[] of first new slot */
80430 ){
80431   int i;
80432
80433   /* Sanity checking on calling parameters */
80434   assert( iStart>=0 );
80435   assert( nExtra>=1 );
80436   assert( pSrc!=0 );
80437   assert( iStart<=pSrc->nSrc );
80438
80439   /* Allocate additional space if needed */
80440   if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
80441     SrcList *pNew;
80442     int nAlloc = pSrc->nSrc+nExtra;
80443     int nGot;
80444     pNew = sqlite3DbRealloc(db, pSrc,
80445                sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
80446     if( pNew==0 ){
80447       assert( db->mallocFailed );
80448       return pSrc;
80449     }
80450     pSrc = pNew;
80451     nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
80452     pSrc->nAlloc = (u16)nGot;
80453   }
80454
80455   /* Move existing slots that come after the newly inserted slots
80456   ** out of the way */
80457   for(i=pSrc->nSrc-1; i>=iStart; i--){
80458     pSrc->a[i+nExtra] = pSrc->a[i];
80459   }
80460   pSrc->nSrc += (i16)nExtra;
80461
80462   /* Zero the newly allocated slots */
80463   memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
80464   for(i=iStart; i<iStart+nExtra; i++){
80465     pSrc->a[i].iCursor = -1;
80466   }
80467
80468   /* Return a pointer to the enlarged SrcList */
80469   return pSrc;
80470 }
80471
80472
80473 /*
80474 ** Append a new table name to the given SrcList.  Create a new SrcList if
80475 ** need be.  A new entry is created in the SrcList even if pTable is NULL.
80476 **
80477 ** A SrcList is returned, or NULL if there is an OOM error.  The returned
80478 ** SrcList might be the same as the SrcList that was input or it might be
80479 ** a new one.  If an OOM error does occurs, then the prior value of pList
80480 ** that is input to this routine is automatically freed.
80481 **
80482 ** If pDatabase is not null, it means that the table has an optional
80483 ** database name prefix.  Like this:  "database.table".  The pDatabase
80484 ** points to the table name and the pTable points to the database name.
80485 ** The SrcList.a[].zName field is filled with the table name which might
80486 ** come from pTable (if pDatabase is NULL) or from pDatabase.  
80487 ** SrcList.a[].zDatabase is filled with the database name from pTable,
80488 ** or with NULL if no database is specified.
80489 **
80490 ** In other words, if call like this:
80491 **
80492 **         sqlite3SrcListAppend(D,A,B,0);
80493 **
80494 ** Then B is a table name and the database name is unspecified.  If called
80495 ** like this:
80496 **
80497 **         sqlite3SrcListAppend(D,A,B,C);
80498 **
80499 ** Then C is the table name and B is the database name.  If C is defined
80500 ** then so is B.  In other words, we never have a case where:
80501 **
80502 **         sqlite3SrcListAppend(D,A,0,C);
80503 **
80504 ** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
80505 ** before being added to the SrcList.
80506 */
80507 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
80508   sqlite3 *db,        /* Connection to notify of malloc failures */
80509   SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
80510   Token *pTable,      /* Table to append */
80511   Token *pDatabase    /* Database of the table */
80512 ){
80513   struct SrcList_item *pItem;
80514   assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
80515   if( pList==0 ){
80516     pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
80517     if( pList==0 ) return 0;
80518     pList->nAlloc = 1;
80519   }
80520   pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
80521   if( db->mallocFailed ){
80522     sqlite3SrcListDelete(db, pList);
80523     return 0;
80524   }
80525   pItem = &pList->a[pList->nSrc-1];
80526   if( pDatabase && pDatabase->z==0 ){
80527     pDatabase = 0;
80528   }
80529   if( pDatabase ){
80530     Token *pTemp = pDatabase;
80531     pDatabase = pTable;
80532     pTable = pTemp;
80533   }
80534   pItem->zName = sqlite3NameFromToken(db, pTable);
80535   pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
80536   return pList;
80537 }
80538
80539 /*
80540 ** Assign VdbeCursor index numbers to all tables in a SrcList
80541 */
80542 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
80543   int i;
80544   struct SrcList_item *pItem;
80545   assert(pList || pParse->db->mallocFailed );
80546   if( pList ){
80547     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
80548       if( pItem->iCursor>=0 ) break;
80549       pItem->iCursor = pParse->nTab++;
80550       if( pItem->pSelect ){
80551         sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
80552       }
80553     }
80554   }
80555 }
80556
80557 /*
80558 ** Delete an entire SrcList including all its substructure.
80559 */
80560 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
80561   int i;
80562   struct SrcList_item *pItem;
80563   if( pList==0 ) return;
80564   for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
80565     sqlite3DbFree(db, pItem->zDatabase);
80566     sqlite3DbFree(db, pItem->zName);
80567     sqlite3DbFree(db, pItem->zAlias);
80568     sqlite3DbFree(db, pItem->zIndex);
80569     sqlite3DeleteTable(db, pItem->pTab);
80570     sqlite3SelectDelete(db, pItem->pSelect);
80571     sqlite3ExprDelete(db, pItem->pOn);
80572     sqlite3IdListDelete(db, pItem->pUsing);
80573   }
80574   sqlite3DbFree(db, pList);
80575 }
80576
80577 /*
80578 ** This routine is called by the parser to add a new term to the
80579 ** end of a growing FROM clause.  The "p" parameter is the part of
80580 ** the FROM clause that has already been constructed.  "p" is NULL
80581 ** if this is the first term of the FROM clause.  pTable and pDatabase
80582 ** are the name of the table and database named in the FROM clause term.
80583 ** pDatabase is NULL if the database name qualifier is missing - the
80584 ** usual case.  If the term has a alias, then pAlias points to the
80585 ** alias token.  If the term is a subquery, then pSubquery is the
80586 ** SELECT statement that the subquery encodes.  The pTable and
80587 ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
80588 ** parameters are the content of the ON and USING clauses.
80589 **
80590 ** Return a new SrcList which encodes is the FROM with the new
80591 ** term added.
80592 */
80593 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
80594   Parse *pParse,          /* Parsing context */
80595   SrcList *p,             /* The left part of the FROM clause already seen */
80596   Token *pTable,          /* Name of the table to add to the FROM clause */
80597   Token *pDatabase,       /* Name of the database containing pTable */
80598   Token *pAlias,          /* The right-hand side of the AS subexpression */
80599   Select *pSubquery,      /* A subquery used in place of a table name */
80600   Expr *pOn,              /* The ON clause of a join */
80601   IdList *pUsing          /* The USING clause of a join */
80602 ){
80603   struct SrcList_item *pItem;
80604   sqlite3 *db = pParse->db;
80605   if( !p && (pOn || pUsing) ){
80606     sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s", 
80607       (pOn ? "ON" : "USING")
80608     );
80609     goto append_from_error;
80610   }
80611   p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
80612   if( p==0 || NEVER(p->nSrc==0) ){
80613     goto append_from_error;
80614   }
80615   pItem = &p->a[p->nSrc-1];
80616   assert( pAlias!=0 );
80617   if( pAlias->n ){
80618     pItem->zAlias = sqlite3NameFromToken(db, pAlias);
80619   }
80620   pItem->pSelect = pSubquery;
80621   pItem->pOn = pOn;
80622   pItem->pUsing = pUsing;
80623   return p;
80624
80625  append_from_error:
80626   assert( p==0 );
80627   sqlite3ExprDelete(db, pOn);
80628   sqlite3IdListDelete(db, pUsing);
80629   sqlite3SelectDelete(db, pSubquery);
80630   return 0;
80631 }
80632
80633 /*
80634 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added 
80635 ** element of the source-list passed as the second argument.
80636 */
80637 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
80638   assert( pIndexedBy!=0 );
80639   if( p && ALWAYS(p->nSrc>0) ){
80640     struct SrcList_item *pItem = &p->a[p->nSrc-1];
80641     assert( pItem->notIndexed==0 && pItem->zIndex==0 );
80642     if( pIndexedBy->n==1 && !pIndexedBy->z ){
80643       /* A "NOT INDEXED" clause was supplied. See parse.y 
80644       ** construct "indexed_opt" for details. */
80645       pItem->notIndexed = 1;
80646     }else{
80647       pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
80648     }
80649   }
80650 }
80651
80652 /*
80653 ** When building up a FROM clause in the parser, the join operator
80654 ** is initially attached to the left operand.  But the code generator
80655 ** expects the join operator to be on the right operand.  This routine
80656 ** Shifts all join operators from left to right for an entire FROM
80657 ** clause.
80658 **
80659 ** Example: Suppose the join is like this:
80660 **
80661 **           A natural cross join B
80662 **
80663 ** The operator is "natural cross join".  The A and B operands are stored
80664 ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
80665 ** operator with A.  This routine shifts that operator over to B.
80666 */
80667 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
80668   if( p && p->a ){
80669     int i;
80670     for(i=p->nSrc-1; i>0; i--){
80671       p->a[i].jointype = p->a[i-1].jointype;
80672     }
80673     p->a[0].jointype = 0;
80674   }
80675 }
80676
80677 /*
80678 ** Begin a transaction
80679 */
80680 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
80681   sqlite3 *db;
80682   Vdbe *v;
80683   int i;
80684
80685   assert( pParse!=0 );
80686   db = pParse->db;
80687   assert( db!=0 );
80688 /*  if( db->aDb[0].pBt==0 ) return; */
80689   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
80690     return;
80691   }
80692   v = sqlite3GetVdbe(pParse);
80693   if( !v ) return;
80694   if( type!=TK_DEFERRED ){
80695     for(i=0; i<db->nDb; i++){
80696       sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
80697       sqlite3VdbeUsesBtree(v, i);
80698     }
80699   }
80700   sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
80701 }
80702
80703 /*
80704 ** Commit a transaction
80705 */
80706 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
80707   sqlite3 *db;
80708   Vdbe *v;
80709
80710   assert( pParse!=0 );
80711   db = pParse->db;
80712   assert( db!=0 );
80713 /*  if( db->aDb[0].pBt==0 ) return; */
80714   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
80715     return;
80716   }
80717   v = sqlite3GetVdbe(pParse);
80718   if( v ){
80719     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
80720   }
80721 }
80722
80723 /*
80724 ** Rollback a transaction
80725 */
80726 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
80727   sqlite3 *db;
80728   Vdbe *v;
80729
80730   assert( pParse!=0 );
80731   db = pParse->db;
80732   assert( db!=0 );
80733 /*  if( db->aDb[0].pBt==0 ) return; */
80734   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
80735     return;
80736   }
80737   v = sqlite3GetVdbe(pParse);
80738   if( v ){
80739     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
80740   }
80741 }
80742
80743 /*
80744 ** This function is called by the parser when it parses a command to create,
80745 ** release or rollback an SQL savepoint. 
80746 */
80747 SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
80748   char *zName = sqlite3NameFromToken(pParse->db, pName);
80749   if( zName ){
80750     Vdbe *v = sqlite3GetVdbe(pParse);
80751 #ifndef SQLITE_OMIT_AUTHORIZATION
80752     static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
80753     assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
80754 #endif
80755     if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
80756       sqlite3DbFree(pParse->db, zName);
80757       return;
80758     }
80759     sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
80760   }
80761 }
80762
80763 /*
80764 ** Make sure the TEMP database is open and available for use.  Return
80765 ** the number of errors.  Leave any error messages in the pParse structure.
80766 */
80767 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
80768   sqlite3 *db = pParse->db;
80769   if( db->aDb[1].pBt==0 && !pParse->explain ){
80770     int rc;
80771     Btree *pBt;
80772     static const int flags = 
80773           SQLITE_OPEN_READWRITE |
80774           SQLITE_OPEN_CREATE |
80775           SQLITE_OPEN_EXCLUSIVE |
80776           SQLITE_OPEN_DELETEONCLOSE |
80777           SQLITE_OPEN_TEMP_DB;
80778
80779     rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
80780     if( rc!=SQLITE_OK ){
80781       sqlite3ErrorMsg(pParse, "unable to open a temporary database "
80782         "file for storing temporary tables");
80783       pParse->rc = rc;
80784       return 1;
80785     }
80786     db->aDb[1].pBt = pBt;
80787     assert( db->aDb[1].pSchema );
80788     if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
80789       db->mallocFailed = 1;
80790       return 1;
80791     }
80792   }
80793   return 0;
80794 }
80795
80796 /*
80797 ** Generate VDBE code that will verify the schema cookie and start
80798 ** a read-transaction for all named database files.
80799 **
80800 ** It is important that all schema cookies be verified and all
80801 ** read transactions be started before anything else happens in
80802 ** the VDBE program.  But this routine can be called after much other
80803 ** code has been generated.  So here is what we do:
80804 **
80805 ** The first time this routine is called, we code an OP_Goto that
80806 ** will jump to a subroutine at the end of the program.  Then we
80807 ** record every database that needs its schema verified in the
80808 ** pParse->cookieMask field.  Later, after all other code has been
80809 ** generated, the subroutine that does the cookie verifications and
80810 ** starts the transactions will be coded and the OP_Goto P2 value
80811 ** will be made to point to that subroutine.  The generation of the
80812 ** cookie verification subroutine code happens in sqlite3FinishCoding().
80813 **
80814 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
80815 ** schema on any databases.  This can be used to position the OP_Goto
80816 ** early in the code, before we know if any database tables will be used.
80817 */
80818 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
80819   Parse *pToplevel = sqlite3ParseToplevel(pParse);
80820
80821   if( pToplevel->cookieGoto==0 ){
80822     Vdbe *v = sqlite3GetVdbe(pToplevel);
80823     if( v==0 ) return;  /* This only happens if there was a prior error */
80824     pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
80825   }
80826   if( iDb>=0 ){
80827     sqlite3 *db = pToplevel->db;
80828     yDbMask mask;
80829
80830     assert( iDb<db->nDb );
80831     assert( db->aDb[iDb].pBt!=0 || iDb==1 );
80832     assert( iDb<SQLITE_MAX_ATTACHED+2 );
80833     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
80834     mask = ((yDbMask)1)<<iDb;
80835     if( (pToplevel->cookieMask & mask)==0 ){
80836       pToplevel->cookieMask |= mask;
80837       pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
80838       if( !OMIT_TEMPDB && iDb==1 ){
80839         sqlite3OpenTempDatabase(pToplevel);
80840       }
80841     }
80842   }
80843 }
80844
80845 /*
80846 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each 
80847 ** attached database. Otherwise, invoke it for the database named zDb only.
80848 */
80849 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
80850   sqlite3 *db = pParse->db;
80851   int i;
80852   for(i=0; i<db->nDb; i++){
80853     Db *pDb = &db->aDb[i];
80854     if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
80855       sqlite3CodeVerifySchema(pParse, i);
80856     }
80857   }
80858 }
80859
80860 /*
80861 ** Generate VDBE code that prepares for doing an operation that
80862 ** might change the database.
80863 **
80864 ** This routine starts a new transaction if we are not already within
80865 ** a transaction.  If we are already within a transaction, then a checkpoint
80866 ** is set if the setStatement parameter is true.  A checkpoint should
80867 ** be set for operations that might fail (due to a constraint) part of
80868 ** the way through and which will need to undo some writes without having to
80869 ** rollback the whole transaction.  For operations where all constraints
80870 ** can be checked before any changes are made to the database, it is never
80871 ** necessary to undo a write and the checkpoint should not be set.
80872 */
80873 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
80874   Parse *pToplevel = sqlite3ParseToplevel(pParse);
80875   sqlite3CodeVerifySchema(pParse, iDb);
80876   pToplevel->writeMask |= ((yDbMask)1)<<iDb;
80877   pToplevel->isMultiWrite |= setStatement;
80878 }
80879
80880 /*
80881 ** Indicate that the statement currently under construction might write
80882 ** more than one entry (example: deleting one row then inserting another,
80883 ** inserting multiple rows in a table, or inserting a row and index entries.)
80884 ** If an abort occurs after some of these writes have completed, then it will
80885 ** be necessary to undo the completed writes.
80886 */
80887 SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
80888   Parse *pToplevel = sqlite3ParseToplevel(pParse);
80889   pToplevel->isMultiWrite = 1;
80890 }
80891
80892 /* 
80893 ** The code generator calls this routine if is discovers that it is
80894 ** possible to abort a statement prior to completion.  In order to 
80895 ** perform this abort without corrupting the database, we need to make
80896 ** sure that the statement is protected by a statement transaction.
80897 **
80898 ** Technically, we only need to set the mayAbort flag if the
80899 ** isMultiWrite flag was previously set.  There is a time dependency
80900 ** such that the abort must occur after the multiwrite.  This makes
80901 ** some statements involving the REPLACE conflict resolution algorithm
80902 ** go a little faster.  But taking advantage of this time dependency
80903 ** makes it more difficult to prove that the code is correct (in 
80904 ** particular, it prevents us from writing an effective
80905 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
80906 ** to take the safe route and skip the optimization.
80907 */
80908 SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
80909   Parse *pToplevel = sqlite3ParseToplevel(pParse);
80910   pToplevel->mayAbort = 1;
80911 }
80912
80913 /*
80914 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
80915 ** error. The onError parameter determines which (if any) of the statement
80916 ** and/or current transaction is rolled back.
80917 */
80918 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse *pParse, int onError, char *p4, int p4type){
80919   Vdbe *v = sqlite3GetVdbe(pParse);
80920   if( onError==OE_Abort ){
80921     sqlite3MayAbort(pParse);
80922   }
80923   sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type);
80924 }
80925
80926 /*
80927 ** Check to see if pIndex uses the collating sequence pColl.  Return
80928 ** true if it does and false if it does not.
80929 */
80930 #ifndef SQLITE_OMIT_REINDEX
80931 static int collationMatch(const char *zColl, Index *pIndex){
80932   int i;
80933   assert( zColl!=0 );
80934   for(i=0; i<pIndex->nColumn; i++){
80935     const char *z = pIndex->azColl[i];
80936     assert( z!=0 );
80937     if( 0==sqlite3StrICmp(z, zColl) ){
80938       return 1;
80939     }
80940   }
80941   return 0;
80942 }
80943 #endif
80944
80945 /*
80946 ** Recompute all indices of pTab that use the collating sequence pColl.
80947 ** If pColl==0 then recompute all indices of pTab.
80948 */
80949 #ifndef SQLITE_OMIT_REINDEX
80950 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
80951   Index *pIndex;              /* An index associated with pTab */
80952
80953   for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
80954     if( zColl==0 || collationMatch(zColl, pIndex) ){
80955       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
80956       sqlite3BeginWriteOperation(pParse, 0, iDb);
80957       sqlite3RefillIndex(pParse, pIndex, -1);
80958     }
80959   }
80960 }
80961 #endif
80962
80963 /*
80964 ** Recompute all indices of all tables in all databases where the
80965 ** indices use the collating sequence pColl.  If pColl==0 then recompute
80966 ** all indices everywhere.
80967 */
80968 #ifndef SQLITE_OMIT_REINDEX
80969 static void reindexDatabases(Parse *pParse, char const *zColl){
80970   Db *pDb;                    /* A single database */
80971   int iDb;                    /* The database index number */
80972   sqlite3 *db = pParse->db;   /* The database connection */
80973   HashElem *k;                /* For looping over tables in pDb */
80974   Table *pTab;                /* A table in the database */
80975
80976   assert( sqlite3BtreeHoldsAllMutexes(db) );  /* Needed for schema access */
80977   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
80978     assert( pDb!=0 );
80979     for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
80980       pTab = (Table*)sqliteHashData(k);
80981       reindexTable(pParse, pTab, zColl);
80982     }
80983   }
80984 }
80985 #endif
80986
80987 /*
80988 ** Generate code for the REINDEX command.
80989 **
80990 **        REINDEX                            -- 1
80991 **        REINDEX  <collation>               -- 2
80992 **        REINDEX  ?<database>.?<tablename>  -- 3
80993 **        REINDEX  ?<database>.?<indexname>  -- 4
80994 **
80995 ** Form 1 causes all indices in all attached databases to be rebuilt.
80996 ** Form 2 rebuilds all indices in all databases that use the named
80997 ** collating function.  Forms 3 and 4 rebuild the named index or all
80998 ** indices associated with the named table.
80999 */
81000 #ifndef SQLITE_OMIT_REINDEX
81001 SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
81002   CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
81003   char *z;                    /* Name of a table or index */
81004   const char *zDb;            /* Name of the database */
81005   Table *pTab;                /* A table in the database */
81006   Index *pIndex;              /* An index associated with pTab */
81007   int iDb;                    /* The database index number */
81008   sqlite3 *db = pParse->db;   /* The database connection */
81009   Token *pObjName;            /* Name of the table or index to be reindexed */
81010
81011   /* Read the database schema. If an error occurs, leave an error message
81012   ** and code in pParse and return NULL. */
81013   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
81014     return;
81015   }
81016
81017   if( pName1==0 ){
81018     reindexDatabases(pParse, 0);
81019     return;
81020   }else if( NEVER(pName2==0) || pName2->z==0 ){
81021     char *zColl;
81022     assert( pName1->z );
81023     zColl = sqlite3NameFromToken(pParse->db, pName1);
81024     if( !zColl ) return;
81025     pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
81026     if( pColl ){
81027       reindexDatabases(pParse, zColl);
81028       sqlite3DbFree(db, zColl);
81029       return;
81030     }
81031     sqlite3DbFree(db, zColl);
81032   }
81033   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
81034   if( iDb<0 ) return;
81035   z = sqlite3NameFromToken(db, pObjName);
81036   if( z==0 ) return;
81037   zDb = db->aDb[iDb].zName;
81038   pTab = sqlite3FindTable(db, z, zDb);
81039   if( pTab ){
81040     reindexTable(pParse, pTab, 0);
81041     sqlite3DbFree(db, z);
81042     return;
81043   }
81044   pIndex = sqlite3FindIndex(db, z, zDb);
81045   sqlite3DbFree(db, z);
81046   if( pIndex ){
81047     sqlite3BeginWriteOperation(pParse, 0, iDb);
81048     sqlite3RefillIndex(pParse, pIndex, -1);
81049     return;
81050   }
81051   sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
81052 }
81053 #endif
81054
81055 /*
81056 ** Return a dynamicly allocated KeyInfo structure that can be used
81057 ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
81058 **
81059 ** If successful, a pointer to the new structure is returned. In this case
81060 ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned 
81061 ** pointer. If an error occurs (out of memory or missing collation 
81062 ** sequence), NULL is returned and the state of pParse updated to reflect
81063 ** the error.
81064 */
81065 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
81066   int i;
81067   int nCol = pIdx->nColumn;
81068   int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
81069   sqlite3 *db = pParse->db;
81070   KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
81071
81072   if( pKey ){
81073     pKey->db = pParse->db;
81074     pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
81075     assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
81076     for(i=0; i<nCol; i++){
81077       char *zColl = pIdx->azColl[i];
81078       assert( zColl );
81079       pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
81080       pKey->aSortOrder[i] = pIdx->aSortOrder[i];
81081     }
81082     pKey->nField = (u16)nCol;
81083   }
81084
81085   if( pParse->nErr ){
81086     sqlite3DbFree(db, pKey);
81087     pKey = 0;
81088   }
81089   return pKey;
81090 }
81091
81092 /************** End of build.c ***********************************************/
81093 /************** Begin file callback.c ****************************************/
81094 /*
81095 ** 2005 May 23 
81096 **
81097 ** The author disclaims copyright to this source code.  In place of
81098 ** a legal notice, here is a blessing:
81099 **
81100 **    May you do good and not evil.
81101 **    May you find forgiveness for yourself and forgive others.
81102 **    May you share freely, never taking more than you give.
81103 **
81104 *************************************************************************
81105 **
81106 ** This file contains functions used to access the internal hash tables
81107 ** of user defined functions and collation sequences.
81108 */
81109
81110
81111 /*
81112 ** Invoke the 'collation needed' callback to request a collation sequence
81113 ** in the encoding enc of name zName, length nName.
81114 */
81115 static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
81116   assert( !db->xCollNeeded || !db->xCollNeeded16 );
81117   if( db->xCollNeeded ){
81118     char *zExternal = sqlite3DbStrDup(db, zName);
81119     if( !zExternal ) return;
81120     db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
81121     sqlite3DbFree(db, zExternal);
81122   }
81123 #ifndef SQLITE_OMIT_UTF16
81124   if( db->xCollNeeded16 ){
81125     char const *zExternal;
81126     sqlite3_value *pTmp = sqlite3ValueNew(db);
81127     sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
81128     zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
81129     if( zExternal ){
81130       db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
81131     }
81132     sqlite3ValueFree(pTmp);
81133   }
81134 #endif
81135 }
81136
81137 /*
81138 ** This routine is called if the collation factory fails to deliver a
81139 ** collation function in the best encoding but there may be other versions
81140 ** of this collation function (for other text encodings) available. Use one
81141 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
81142 ** possible.
81143 */
81144 static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
81145   CollSeq *pColl2;
81146   char *z = pColl->zName;
81147   int i;
81148   static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
81149   for(i=0; i<3; i++){
81150     pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
81151     if( pColl2->xCmp!=0 ){
81152       memcpy(pColl, pColl2, sizeof(CollSeq));
81153       pColl->xDel = 0;         /* Do not copy the destructor */
81154       return SQLITE_OK;
81155     }
81156   }
81157   return SQLITE_ERROR;
81158 }
81159
81160 /*
81161 ** This function is responsible for invoking the collation factory callback
81162 ** or substituting a collation sequence of a different encoding when the
81163 ** requested collation sequence is not available in the desired encoding.
81164 ** 
81165 ** If it is not NULL, then pColl must point to the database native encoding 
81166 ** collation sequence with name zName, length nName.
81167 **
81168 ** The return value is either the collation sequence to be used in database
81169 ** db for collation type name zName, length nName, or NULL, if no collation
81170 ** sequence can be found.
81171 **
81172 ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
81173 */
81174 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
81175   sqlite3* db,          /* The database connection */
81176   u8 enc,               /* The desired encoding for the collating sequence */
81177   CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
81178   const char *zName     /* Collating sequence name */
81179 ){
81180   CollSeq *p;
81181
81182   p = pColl;
81183   if( !p ){
81184     p = sqlite3FindCollSeq(db, enc, zName, 0);
81185   }
81186   if( !p || !p->xCmp ){
81187     /* No collation sequence of this type for this encoding is registered.
81188     ** Call the collation factory to see if it can supply us with one.
81189     */
81190     callCollNeeded(db, enc, zName);
81191     p = sqlite3FindCollSeq(db, enc, zName, 0);
81192   }
81193   if( p && !p->xCmp && synthCollSeq(db, p) ){
81194     p = 0;
81195   }
81196   assert( !p || p->xCmp );
81197   return p;
81198 }
81199
81200 /*
81201 ** This routine is called on a collation sequence before it is used to
81202 ** check that it is defined. An undefined collation sequence exists when
81203 ** a database is loaded that contains references to collation sequences
81204 ** that have not been defined by sqlite3_create_collation() etc.
81205 **
81206 ** If required, this routine calls the 'collation needed' callback to
81207 ** request a definition of the collating sequence. If this doesn't work, 
81208 ** an equivalent collating sequence that uses a text encoding different
81209 ** from the main database is substituted, if one is available.
81210 */
81211 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
81212   if( pColl ){
81213     const char *zName = pColl->zName;
81214     sqlite3 *db = pParse->db;
81215     CollSeq *p = sqlite3GetCollSeq(db, ENC(db), pColl, zName);
81216     if( !p ){
81217       sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
81218       pParse->nErr++;
81219       return SQLITE_ERROR;
81220     }
81221     assert( p==pColl );
81222   }
81223   return SQLITE_OK;
81224 }
81225
81226
81227
81228 /*
81229 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
81230 ** specified by zName and nName is not found and parameter 'create' is
81231 ** true, then create a new entry. Otherwise return NULL.
81232 **
81233 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
81234 ** array of three CollSeq structures. The first is the collation sequence
81235 ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
81236 **
81237 ** Stored immediately after the three collation sequences is a copy of
81238 ** the collation sequence name. A pointer to this string is stored in
81239 ** each collation sequence structure.
81240 */
81241 static CollSeq *findCollSeqEntry(
81242   sqlite3 *db,          /* Database connection */
81243   const char *zName,    /* Name of the collating sequence */
81244   int create            /* Create a new entry if true */
81245 ){
81246   CollSeq *pColl;
81247   int nName = sqlite3Strlen30(zName);
81248   pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
81249
81250   if( 0==pColl && create ){
81251     pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
81252     if( pColl ){
81253       CollSeq *pDel = 0;
81254       pColl[0].zName = (char*)&pColl[3];
81255       pColl[0].enc = SQLITE_UTF8;
81256       pColl[1].zName = (char*)&pColl[3];
81257       pColl[1].enc = SQLITE_UTF16LE;
81258       pColl[2].zName = (char*)&pColl[3];
81259       pColl[2].enc = SQLITE_UTF16BE;
81260       memcpy(pColl[0].zName, zName, nName);
81261       pColl[0].zName[nName] = 0;
81262       pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
81263
81264       /* If a malloc() failure occurred in sqlite3HashInsert(), it will 
81265       ** return the pColl pointer to be deleted (because it wasn't added
81266       ** to the hash table).
81267       */
81268       assert( pDel==0 || pDel==pColl );
81269       if( pDel!=0 ){
81270         db->mallocFailed = 1;
81271         sqlite3DbFree(db, pDel);
81272         pColl = 0;
81273       }
81274     }
81275   }
81276   return pColl;
81277 }
81278
81279 /*
81280 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
81281 ** Return the CollSeq* pointer for the collation sequence named zName
81282 ** for the encoding 'enc' from the database 'db'.
81283 **
81284 ** If the entry specified is not found and 'create' is true, then create a
81285 ** new entry.  Otherwise return NULL.
81286 **
81287 ** A separate function sqlite3LocateCollSeq() is a wrapper around
81288 ** this routine.  sqlite3LocateCollSeq() invokes the collation factory
81289 ** if necessary and generates an error message if the collating sequence
81290 ** cannot be found.
81291 **
81292 ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
81293 */
81294 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
81295   sqlite3 *db,
81296   u8 enc,
81297   const char *zName,
81298   int create
81299 ){
81300   CollSeq *pColl;
81301   if( zName ){
81302     pColl = findCollSeqEntry(db, zName, create);
81303   }else{
81304     pColl = db->pDfltColl;
81305   }
81306   assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
81307   assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
81308   if( pColl ) pColl += enc-1;
81309   return pColl;
81310 }
81311
81312 /* During the search for the best function definition, this procedure
81313 ** is called to test how well the function passed as the first argument
81314 ** matches the request for a function with nArg arguments in a system
81315 ** that uses encoding enc. The value returned indicates how well the
81316 ** request is matched. A higher value indicates a better match.
81317 **
81318 ** The returned value is always between 0 and 6, as follows:
81319 **
81320 ** 0: Not a match, or if nArg<0 and the function is has no implementation.
81321 ** 1: A variable arguments function that prefers UTF-8 when a UTF-16
81322 **    encoding is requested, or vice versa.
81323 ** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
81324 **    requested, or vice versa.
81325 ** 3: A variable arguments function using the same text encoding.
81326 ** 4: A function with the exact number of arguments requested that
81327 **    prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
81328 ** 5: A function with the exact number of arguments requested that
81329 **    prefers UTF-16LE when UTF-16BE is requested, or vice versa.
81330 ** 6: An exact match.
81331 **
81332 */
81333 static int matchQuality(FuncDef *p, int nArg, u8 enc){
81334   int match = 0;
81335   if( p->nArg==-1 || p->nArg==nArg 
81336    || (nArg==-1 && (p->xFunc!=0 || p->xStep!=0))
81337   ){
81338     match = 1;
81339     if( p->nArg==nArg || nArg==-1 ){
81340       match = 4;
81341     }
81342     if( enc==p->iPrefEnc ){
81343       match += 2;
81344     }
81345     else if( (enc==SQLITE_UTF16LE && p->iPrefEnc==SQLITE_UTF16BE) ||
81346              (enc==SQLITE_UTF16BE && p->iPrefEnc==SQLITE_UTF16LE) ){
81347       match += 1;
81348     }
81349   }
81350   return match;
81351 }
81352
81353 /*
81354 ** Search a FuncDefHash for a function with the given name.  Return
81355 ** a pointer to the matching FuncDef if found, or 0 if there is no match.
81356 */
81357 static FuncDef *functionSearch(
81358   FuncDefHash *pHash,  /* Hash table to search */
81359   int h,               /* Hash of the name */
81360   const char *zFunc,   /* Name of function */
81361   int nFunc            /* Number of bytes in zFunc */
81362 ){
81363   FuncDef *p;
81364   for(p=pHash->a[h]; p; p=p->pHash){
81365     if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
81366       return p;
81367     }
81368   }
81369   return 0;
81370 }
81371
81372 /*
81373 ** Insert a new FuncDef into a FuncDefHash hash table.
81374 */
81375 SQLITE_PRIVATE void sqlite3FuncDefInsert(
81376   FuncDefHash *pHash,  /* The hash table into which to insert */
81377   FuncDef *pDef        /* The function definition to insert */
81378 ){
81379   FuncDef *pOther;
81380   int nName = sqlite3Strlen30(pDef->zName);
81381   u8 c1 = (u8)pDef->zName[0];
81382   int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
81383   pOther = functionSearch(pHash, h, pDef->zName, nName);
81384   if( pOther ){
81385     assert( pOther!=pDef && pOther->pNext!=pDef );
81386     pDef->pNext = pOther->pNext;
81387     pOther->pNext = pDef;
81388   }else{
81389     pDef->pNext = 0;
81390     pDef->pHash = pHash->a[h];
81391     pHash->a[h] = pDef;
81392   }
81393 }
81394   
81395   
81396
81397 /*
81398 ** Locate a user function given a name, a number of arguments and a flag
81399 ** indicating whether the function prefers UTF-16 over UTF-8.  Return a
81400 ** pointer to the FuncDef structure that defines that function, or return
81401 ** NULL if the function does not exist.
81402 **
81403 ** If the createFlag argument is true, then a new (blank) FuncDef
81404 ** structure is created and liked into the "db" structure if a
81405 ** no matching function previously existed.  When createFlag is true
81406 ** and the nArg parameter is -1, then only a function that accepts
81407 ** any number of arguments will be returned.
81408 **
81409 ** If createFlag is false and nArg is -1, then the first valid
81410 ** function found is returned.  A function is valid if either xFunc
81411 ** or xStep is non-zero.
81412 **
81413 ** If createFlag is false, then a function with the required name and
81414 ** number of arguments may be returned even if the eTextRep flag does not
81415 ** match that requested.
81416 */
81417 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
81418   sqlite3 *db,       /* An open database */
81419   const char *zName, /* Name of the function.  Not null-terminated */
81420   int nName,         /* Number of characters in the name */
81421   int nArg,          /* Number of arguments.  -1 means any number */
81422   u8 enc,            /* Preferred text encoding */
81423   int createFlag     /* Create new entry if true and does not otherwise exist */
81424 ){
81425   FuncDef *p;         /* Iterator variable */
81426   FuncDef *pBest = 0; /* Best match found so far */
81427   int bestScore = 0;  /* Score of best match */
81428   int h;              /* Hash value */
81429
81430
81431   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
81432   h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
81433
81434   /* First search for a match amongst the application-defined functions.
81435   */
81436   p = functionSearch(&db->aFunc, h, zName, nName);
81437   while( p ){
81438     int score = matchQuality(p, nArg, enc);
81439     if( score>bestScore ){
81440       pBest = p;
81441       bestScore = score;
81442     }
81443     p = p->pNext;
81444   }
81445
81446   /* If no match is found, search the built-in functions.
81447   **
81448   ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
81449   ** functions even if a prior app-defined function was found.  And give
81450   ** priority to built-in functions.
81451   **
81452   ** Except, if createFlag is true, that means that we are trying to
81453   ** install a new function.  Whatever FuncDef structure is returned it will
81454   ** have fields overwritten with new information appropriate for the
81455   ** new function.  But the FuncDefs for built-in functions are read-only.
81456   ** So we must not search for built-ins when creating a new function.
81457   */ 
81458   if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
81459     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
81460     bestScore = 0;
81461     p = functionSearch(pHash, h, zName, nName);
81462     while( p ){
81463       int score = matchQuality(p, nArg, enc);
81464       if( score>bestScore ){
81465         pBest = p;
81466         bestScore = score;
81467       }
81468       p = p->pNext;
81469     }
81470   }
81471
81472   /* If the createFlag parameter is true and the search did not reveal an
81473   ** exact match for the name, number of arguments and encoding, then add a
81474   ** new entry to the hash table and return it.
81475   */
81476   if( createFlag && (bestScore<6 || pBest->nArg!=nArg) && 
81477       (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
81478     pBest->zName = (char *)&pBest[1];
81479     pBest->nArg = (u16)nArg;
81480     pBest->iPrefEnc = enc;
81481     memcpy(pBest->zName, zName, nName);
81482     pBest->zName[nName] = 0;
81483     sqlite3FuncDefInsert(&db->aFunc, pBest);
81484   }
81485
81486   if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
81487     return pBest;
81488   }
81489   return 0;
81490 }
81491
81492 /*
81493 ** Free all resources held by the schema structure. The void* argument points
81494 ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the 
81495 ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
81496 ** of the schema hash tables).
81497 **
81498 ** The Schema.cache_size variable is not cleared.
81499 */
81500 SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
81501   Hash temp1;
81502   Hash temp2;
81503   HashElem *pElem;
81504   Schema *pSchema = (Schema *)p;
81505
81506   temp1 = pSchema->tblHash;
81507   temp2 = pSchema->trigHash;
81508   sqlite3HashInit(&pSchema->trigHash);
81509   sqlite3HashClear(&pSchema->idxHash);
81510   for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
81511     sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
81512   }
81513   sqlite3HashClear(&temp2);
81514   sqlite3HashInit(&pSchema->tblHash);
81515   for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
81516     Table *pTab = sqliteHashData(pElem);
81517     sqlite3DeleteTable(0, pTab);
81518   }
81519   sqlite3HashClear(&temp1);
81520   sqlite3HashClear(&pSchema->fkeyHash);
81521   pSchema->pSeqTab = 0;
81522   if( pSchema->flags & DB_SchemaLoaded ){
81523     pSchema->iGeneration++;
81524     pSchema->flags &= ~DB_SchemaLoaded;
81525   }
81526 }
81527
81528 /*
81529 ** Find and return the schema associated with a BTree.  Create
81530 ** a new one if necessary.
81531 */
81532 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
81533   Schema * p;
81534   if( pBt ){
81535     p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
81536   }else{
81537     p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
81538   }
81539   if( !p ){
81540     db->mallocFailed = 1;
81541   }else if ( 0==p->file_format ){
81542     sqlite3HashInit(&p->tblHash);
81543     sqlite3HashInit(&p->idxHash);
81544     sqlite3HashInit(&p->trigHash);
81545     sqlite3HashInit(&p->fkeyHash);
81546     p->enc = SQLITE_UTF8;
81547   }
81548   return p;
81549 }
81550
81551 /************** End of callback.c ********************************************/
81552 /************** Begin file delete.c ******************************************/
81553 /*
81554 ** 2001 September 15
81555 **
81556 ** The author disclaims copyright to this source code.  In place of
81557 ** a legal notice, here is a blessing:
81558 **
81559 **    May you do good and not evil.
81560 **    May you find forgiveness for yourself and forgive others.
81561 **    May you share freely, never taking more than you give.
81562 **
81563 *************************************************************************
81564 ** This file contains C code routines that are called by the parser
81565 ** in order to generate code for DELETE FROM statements.
81566 */
81567
81568 /*
81569 ** While a SrcList can in general represent multiple tables and subqueries
81570 ** (as in the FROM clause of a SELECT statement) in this case it contains
81571 ** the name of a single table, as one might find in an INSERT, DELETE,
81572 ** or UPDATE statement.  Look up that table in the symbol table and
81573 ** return a pointer.  Set an error message and return NULL if the table 
81574 ** name is not found or if any other error occurs.
81575 **
81576 ** The following fields are initialized appropriate in pSrc:
81577 **
81578 **    pSrc->a[0].pTab       Pointer to the Table object
81579 **    pSrc->a[0].pIndex     Pointer to the INDEXED BY index, if there is one
81580 **
81581 */
81582 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
81583   struct SrcList_item *pItem = pSrc->a;
81584   Table *pTab;
81585   assert( pItem && pSrc->nSrc==1 );
81586   pTab = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
81587   sqlite3DeleteTable(pParse->db, pItem->pTab);
81588   pItem->pTab = pTab;
81589   if( pTab ){
81590     pTab->nRef++;
81591   }
81592   if( sqlite3IndexedByLookup(pParse, pItem) ){
81593     pTab = 0;
81594   }
81595   return pTab;
81596 }
81597
81598 /*
81599 ** Check to make sure the given table is writable.  If it is not
81600 ** writable, generate an error message and return 1.  If it is
81601 ** writable return 0;
81602 */
81603 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
81604   /* A table is not writable under the following circumstances:
81605   **
81606   **   1) It is a virtual table and no implementation of the xUpdate method
81607   **      has been provided, or
81608   **   2) It is a system table (i.e. sqlite_master), this call is not
81609   **      part of a nested parse and writable_schema pragma has not 
81610   **      been specified.
81611   **
81612   ** In either case leave an error message in pParse and return non-zero.
81613   */
81614   if( ( IsVirtual(pTab) 
81615      && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
81616    || ( (pTab->tabFlags & TF_Readonly)!=0
81617      && (pParse->db->flags & SQLITE_WriteSchema)==0
81618      && pParse->nested==0 )
81619   ){
81620     sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
81621     return 1;
81622   }
81623
81624 #ifndef SQLITE_OMIT_VIEW
81625   if( !viewOk && pTab->pSelect ){
81626     sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
81627     return 1;
81628   }
81629 #endif
81630   return 0;
81631 }
81632
81633
81634 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
81635 /*
81636 ** Evaluate a view and store its result in an ephemeral table.  The
81637 ** pWhere argument is an optional WHERE clause that restricts the
81638 ** set of rows in the view that are to be added to the ephemeral table.
81639 */
81640 SQLITE_PRIVATE void sqlite3MaterializeView(
81641   Parse *pParse,       /* Parsing context */
81642   Table *pView,        /* View definition */
81643   Expr *pWhere,        /* Optional WHERE clause to be added */
81644   int iCur             /* Cursor number for ephemerial table */
81645 ){
81646   SelectDest dest;
81647   Select *pDup;
81648   sqlite3 *db = pParse->db;
81649
81650   pDup = sqlite3SelectDup(db, pView->pSelect, 0);
81651   if( pWhere ){
81652     SrcList *pFrom;
81653     
81654     pWhere = sqlite3ExprDup(db, pWhere, 0);
81655     pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
81656     if( pFrom ){
81657       assert( pFrom->nSrc==1 );
81658       pFrom->a[0].zAlias = sqlite3DbStrDup(db, pView->zName);
81659       pFrom->a[0].pSelect = pDup;
81660       assert( pFrom->a[0].pOn==0 );
81661       assert( pFrom->a[0].pUsing==0 );
81662     }else{
81663       sqlite3SelectDelete(db, pDup);
81664     }
81665     pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
81666   }
81667   sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
81668   sqlite3Select(pParse, pDup, &dest);
81669   sqlite3SelectDelete(db, pDup);
81670 }
81671 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
81672
81673 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
81674 /*
81675 ** Generate an expression tree to implement the WHERE, ORDER BY,
81676 ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
81677 **
81678 **     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
81679 **                            \__________________________/
81680 **                               pLimitWhere (pInClause)
81681 */
81682 SQLITE_PRIVATE Expr *sqlite3LimitWhere(
81683   Parse *pParse,               /* The parser context */
81684   SrcList *pSrc,               /* the FROM clause -- which tables to scan */
81685   Expr *pWhere,                /* The WHERE clause.  May be null */
81686   ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
81687   Expr *pLimit,                /* The LIMIT clause.  May be null */
81688   Expr *pOffset,               /* The OFFSET clause.  May be null */
81689   char *zStmtType              /* Either DELETE or UPDATE.  For error messages. */
81690 ){
81691   Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
81692   Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
81693   Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
81694   ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
81695   SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
81696   Select *pSelect = NULL;      /* Complete SELECT tree */
81697
81698   /* Check that there isn't an ORDER BY without a LIMIT clause.
81699   */
81700   if( pOrderBy && (pLimit == 0) ) {
81701     sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
81702     pParse->parseError = 1;
81703     goto limit_where_cleanup_2;
81704   }
81705
81706   /* We only need to generate a select expression if there
81707   ** is a limit/offset term to enforce.
81708   */
81709   if( pLimit == 0 ) {
81710     /* if pLimit is null, pOffset will always be null as well. */
81711     assert( pOffset == 0 );
81712     return pWhere;
81713   }
81714
81715   /* Generate a select expression tree to enforce the limit/offset 
81716   ** term for the DELETE or UPDATE statement.  For example:
81717   **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
81718   ** becomes:
81719   **   DELETE FROM table_a WHERE rowid IN ( 
81720   **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
81721   **   );
81722   */
81723
81724   pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
81725   if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
81726   pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
81727   if( pEList == 0 ) goto limit_where_cleanup_2;
81728
81729   /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
81730   ** and the SELECT subtree. */
81731   pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
81732   if( pSelectSrc == 0 ) {
81733     sqlite3ExprListDelete(pParse->db, pEList);
81734     goto limit_where_cleanup_2;
81735   }
81736
81737   /* generate the SELECT expression tree. */
81738   pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
81739                              pOrderBy,0,pLimit,pOffset);
81740   if( pSelect == 0 ) return 0;
81741
81742   /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
81743   pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
81744   if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
81745   pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
81746   if( pInClause == 0 ) goto limit_where_cleanup_1;
81747
81748   pInClause->x.pSelect = pSelect;
81749   pInClause->flags |= EP_xIsSelect;
81750   sqlite3ExprSetHeight(pParse, pInClause);
81751   return pInClause;
81752
81753   /* something went wrong. clean up anything allocated. */
81754 limit_where_cleanup_1:
81755   sqlite3SelectDelete(pParse->db, pSelect);
81756   return 0;
81757
81758 limit_where_cleanup_2:
81759   sqlite3ExprDelete(pParse->db, pWhere);
81760   sqlite3ExprListDelete(pParse->db, pOrderBy);
81761   sqlite3ExprDelete(pParse->db, pLimit);
81762   sqlite3ExprDelete(pParse->db, pOffset);
81763   return 0;
81764 }
81765 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
81766
81767 /*
81768 ** Generate code for a DELETE FROM statement.
81769 **
81770 **     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
81771 **                 \________/       \________________/
81772 **                  pTabList              pWhere
81773 */
81774 SQLITE_PRIVATE void sqlite3DeleteFrom(
81775   Parse *pParse,         /* The parser context */
81776   SrcList *pTabList,     /* The table from which we should delete things */
81777   Expr *pWhere           /* The WHERE clause.  May be null */
81778 ){
81779   Vdbe *v;               /* The virtual database engine */
81780   Table *pTab;           /* The table from which records will be deleted */
81781   const char *zDb;       /* Name of database holding pTab */
81782   int end, addr = 0;     /* A couple addresses of generated code */
81783   int i;                 /* Loop counter */
81784   WhereInfo *pWInfo;     /* Information about the WHERE clause */
81785   Index *pIdx;           /* For looping over indices of the table */
81786   int iCur;              /* VDBE Cursor number for pTab */
81787   sqlite3 *db;           /* Main database structure */
81788   AuthContext sContext;  /* Authorization context */
81789   NameContext sNC;       /* Name context to resolve expressions in */
81790   int iDb;               /* Database number */
81791   int memCnt = -1;       /* Memory cell used for change counting */
81792   int rcauth;            /* Value returned by authorization callback */
81793
81794 #ifndef SQLITE_OMIT_TRIGGER
81795   int isView;                  /* True if attempting to delete from a view */
81796   Trigger *pTrigger;           /* List of table triggers, if required */
81797 #endif
81798
81799   memset(&sContext, 0, sizeof(sContext));
81800   db = pParse->db;
81801   if( pParse->nErr || db->mallocFailed ){
81802     goto delete_from_cleanup;
81803   }
81804   assert( pTabList->nSrc==1 );
81805
81806   /* Locate the table which we want to delete.  This table has to be
81807   ** put in an SrcList structure because some of the subroutines we
81808   ** will be calling are designed to work with multiple tables and expect
81809   ** an SrcList* parameter instead of just a Table* parameter.
81810   */
81811   pTab = sqlite3SrcListLookup(pParse, pTabList);
81812   if( pTab==0 )  goto delete_from_cleanup;
81813
81814   /* Figure out if we have any triggers and if the table being
81815   ** deleted from is a view
81816   */
81817 #ifndef SQLITE_OMIT_TRIGGER
81818   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
81819   isView = pTab->pSelect!=0;
81820 #else
81821 # define pTrigger 0
81822 # define isView 0
81823 #endif
81824 #ifdef SQLITE_OMIT_VIEW
81825 # undef isView
81826 # define isView 0
81827 #endif
81828
81829   /* If pTab is really a view, make sure it has been initialized.
81830   */
81831   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
81832     goto delete_from_cleanup;
81833   }
81834
81835   if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
81836     goto delete_from_cleanup;
81837   }
81838   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
81839   assert( iDb<db->nDb );
81840   zDb = db->aDb[iDb].zName;
81841   rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
81842   assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
81843   if( rcauth==SQLITE_DENY ){
81844     goto delete_from_cleanup;
81845   }
81846   assert(!isView || pTrigger);
81847
81848   /* Assign  cursor number to the table and all its indices.
81849   */
81850   assert( pTabList->nSrc==1 );
81851   iCur = pTabList->a[0].iCursor = pParse->nTab++;
81852   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
81853     pParse->nTab++;
81854   }
81855
81856   /* Start the view context
81857   */
81858   if( isView ){
81859     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
81860   }
81861
81862   /* Begin generating code.
81863   */
81864   v = sqlite3GetVdbe(pParse);
81865   if( v==0 ){
81866     goto delete_from_cleanup;
81867   }
81868   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
81869   sqlite3BeginWriteOperation(pParse, 1, iDb);
81870
81871   /* If we are trying to delete from a view, realize that view into
81872   ** a ephemeral table.
81873   */
81874 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
81875   if( isView ){
81876     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
81877   }
81878 #endif
81879
81880   /* Resolve the column names in the WHERE clause.
81881   */
81882   memset(&sNC, 0, sizeof(sNC));
81883   sNC.pParse = pParse;
81884   sNC.pSrcList = pTabList;
81885   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
81886     goto delete_from_cleanup;
81887   }
81888
81889   /* Initialize the counter of the number of rows deleted, if
81890   ** we are counting rows.
81891   */
81892   if( db->flags & SQLITE_CountRows ){
81893     memCnt = ++pParse->nMem;
81894     sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
81895   }
81896
81897 #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
81898   /* Special case: A DELETE without a WHERE clause deletes everything.
81899   ** It is easier just to erase the whole table. Prior to version 3.6.5,
81900   ** this optimization caused the row change count (the value returned by 
81901   ** API function sqlite3_count_changes) to be set incorrectly.  */
81902   if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab) 
81903    && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
81904   ){
81905     assert( !isView );
81906     sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
81907                       pTab->zName, P4_STATIC);
81908     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
81909       assert( pIdx->pSchema==pTab->pSchema );
81910       sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
81911     }
81912   }else
81913 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
81914   /* The usual case: There is a WHERE clause so we have to scan through
81915   ** the table and pick which records to delete.
81916   */
81917   {
81918     int iRowSet = ++pParse->nMem;   /* Register for rowset of rows to delete */
81919     int iRowid = ++pParse->nMem;    /* Used for storing rowid values. */
81920     int regRowid;                   /* Actual register containing rowids */
81921
81922     /* Collect rowids of every row to be deleted.
81923     */
81924     sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
81925     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0,WHERE_DUPLICATES_OK);
81926     if( pWInfo==0 ) goto delete_from_cleanup;
81927     regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid);
81928     sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
81929     if( db->flags & SQLITE_CountRows ){
81930       sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
81931     }
81932     sqlite3WhereEnd(pWInfo);
81933
81934     /* Delete every item whose key was written to the list during the
81935     ** database scan.  We have to delete items after the scan is complete
81936     ** because deleting an item can change the scan order.  */
81937     end = sqlite3VdbeMakeLabel(v);
81938
81939     /* Unless this is a view, open cursors for the table we are 
81940     ** deleting from and all its indices. If this is a view, then the
81941     ** only effect this statement has is to fire the INSTEAD OF 
81942     ** triggers.  */
81943     if( !isView ){
81944       sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
81945     }
81946
81947     addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
81948
81949     /* Delete the row */
81950 #ifndef SQLITE_OMIT_VIRTUALTABLE
81951     if( IsVirtual(pTab) ){
81952       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
81953       sqlite3VtabMakeWritable(pParse, pTab);
81954       sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
81955       sqlite3VdbeChangeP5(v, OE_Abort);
81956       sqlite3MayAbort(pParse);
81957     }else
81958 #endif
81959     {
81960       int count = (pParse->nested==0);    /* True to count changes */
81961       sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
81962     }
81963
81964     /* End of the delete loop */
81965     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
81966     sqlite3VdbeResolveLabel(v, end);
81967
81968     /* Close the cursors open on the table and its indexes. */
81969     if( !isView && !IsVirtual(pTab) ){
81970       for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
81971         sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
81972       }
81973       sqlite3VdbeAddOp1(v, OP_Close, iCur);
81974     }
81975   }
81976
81977   /* Update the sqlite_sequence table by storing the content of the
81978   ** maximum rowid counter values recorded while inserting into
81979   ** autoincrement tables.
81980   */
81981   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
81982     sqlite3AutoincrementEnd(pParse);
81983   }
81984
81985   /* Return the number of rows that were deleted. If this routine is 
81986   ** generating code because of a call to sqlite3NestedParse(), do not
81987   ** invoke the callback function.
81988   */
81989   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
81990     sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
81991     sqlite3VdbeSetNumCols(v, 1);
81992     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
81993   }
81994
81995 delete_from_cleanup:
81996   sqlite3AuthContextPop(&sContext);
81997   sqlite3SrcListDelete(db, pTabList);
81998   sqlite3ExprDelete(db, pWhere);
81999   return;
82000 }
82001 /* Make sure "isView" and other macros defined above are undefined. Otherwise
82002 ** thely may interfere with compilation of other functions in this file
82003 ** (or in another file, if this file becomes part of the amalgamation).  */
82004 #ifdef isView
82005  #undef isView
82006 #endif
82007 #ifdef pTrigger
82008  #undef pTrigger
82009 #endif
82010
82011 /*
82012 ** This routine generates VDBE code that causes a single row of a
82013 ** single table to be deleted.
82014 **
82015 ** The VDBE must be in a particular state when this routine is called.
82016 ** These are the requirements:
82017 **
82018 **   1.  A read/write cursor pointing to pTab, the table containing the row
82019 **       to be deleted, must be opened as cursor number $iCur.
82020 **
82021 **   2.  Read/write cursors for all indices of pTab must be open as
82022 **       cursor number base+i for the i-th index.
82023 **
82024 **   3.  The record number of the row to be deleted must be stored in
82025 **       memory cell iRowid.
82026 **
82027 ** This routine generates code to remove both the table record and all 
82028 ** index entries that point to that record.
82029 */
82030 SQLITE_PRIVATE void sqlite3GenerateRowDelete(
82031   Parse *pParse,     /* Parsing context */
82032   Table *pTab,       /* Table containing the row to be deleted */
82033   int iCur,          /* Cursor number for the table */
82034   int iRowid,        /* Memory cell that contains the rowid to delete */
82035   int count,         /* If non-zero, increment the row change counter */
82036   Trigger *pTrigger, /* List of triggers to (potentially) fire */
82037   int onconf         /* Default ON CONFLICT policy for triggers */
82038 ){
82039   Vdbe *v = pParse->pVdbe;        /* Vdbe */
82040   int iOld = 0;                   /* First register in OLD.* array */
82041   int iLabel;                     /* Label resolved to end of generated code */
82042
82043   /* Vdbe is guaranteed to have been allocated by this stage. */
82044   assert( v );
82045
82046   /* Seek cursor iCur to the row to delete. If this row no longer exists 
82047   ** (this can happen if a trigger program has already deleted it), do
82048   ** not attempt to delete it or fire any DELETE triggers.  */
82049   iLabel = sqlite3VdbeMakeLabel(v);
82050   sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
82051  
82052   /* If there are any triggers to fire, allocate a range of registers to
82053   ** use for the old.* references in the triggers.  */
82054   if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
82055     u32 mask;                     /* Mask of OLD.* columns in use */
82056     int iCol;                     /* Iterator used while populating OLD.* */
82057
82058     /* TODO: Could use temporary registers here. Also could attempt to
82059     ** avoid copying the contents of the rowid register.  */
82060     mask = sqlite3TriggerColmask(
82061         pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
82062     );
82063     mask |= sqlite3FkOldmask(pParse, pTab);
82064     iOld = pParse->nMem+1;
82065     pParse->nMem += (1 + pTab->nCol);
82066
82067     /* Populate the OLD.* pseudo-table register array. These values will be 
82068     ** used by any BEFORE and AFTER triggers that exist.  */
82069     sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
82070     for(iCol=0; iCol<pTab->nCol; iCol++){
82071       if( mask==0xffffffff || mask&(1<<iCol) ){
82072         sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, iOld+iCol+1);
82073       }
82074     }
82075
82076     /* Invoke BEFORE DELETE trigger programs. */
82077     sqlite3CodeRowTrigger(pParse, pTrigger, 
82078         TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
82079     );
82080
82081     /* Seek the cursor to the row to be deleted again. It may be that
82082     ** the BEFORE triggers coded above have already removed the row
82083     ** being deleted. Do not attempt to delete the row a second time, and 
82084     ** do not fire AFTER triggers.  */
82085     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
82086
82087     /* Do FK processing. This call checks that any FK constraints that
82088     ** refer to this table (i.e. constraints attached to other tables) 
82089     ** are not violated by deleting this row.  */
82090     sqlite3FkCheck(pParse, pTab, iOld, 0);
82091   }
82092
82093   /* Delete the index and table entries. Skip this step if pTab is really
82094   ** a view (in which case the only effect of the DELETE statement is to
82095   ** fire the INSTEAD OF triggers).  */ 
82096   if( pTab->pSelect==0 ){
82097     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
82098     sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
82099     if( count ){
82100       sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
82101     }
82102   }
82103
82104   /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
82105   ** handle rows (possibly in other tables) that refer via a foreign key
82106   ** to the row just deleted. */ 
82107   sqlite3FkActions(pParse, pTab, 0, iOld);
82108
82109   /* Invoke AFTER DELETE trigger programs. */
82110   sqlite3CodeRowTrigger(pParse, pTrigger, 
82111       TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
82112   );
82113
82114   /* Jump here if the row had already been deleted before any BEFORE
82115   ** trigger programs were invoked. Or if a trigger program throws a 
82116   ** RAISE(IGNORE) exception.  */
82117   sqlite3VdbeResolveLabel(v, iLabel);
82118 }
82119
82120 /*
82121 ** This routine generates VDBE code that causes the deletion of all
82122 ** index entries associated with a single row of a single table.
82123 **
82124 ** The VDBE must be in a particular state when this routine is called.
82125 ** These are the requirements:
82126 **
82127 **   1.  A read/write cursor pointing to pTab, the table containing the row
82128 **       to be deleted, must be opened as cursor number "iCur".
82129 **
82130 **   2.  Read/write cursors for all indices of pTab must be open as
82131 **       cursor number iCur+i for the i-th index.
82132 **
82133 **   3.  The "iCur" cursor must be pointing to the row that is to be
82134 **       deleted.
82135 */
82136 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
82137   Parse *pParse,     /* Parsing and code generating context */
82138   Table *pTab,       /* Table containing the row to be deleted */
82139   int iCur,          /* Cursor number for the table */
82140   int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
82141 ){
82142   int i;
82143   Index *pIdx;
82144   int r1;
82145
82146   for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
82147     if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
82148     r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
82149     sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
82150   }
82151 }
82152
82153 /*
82154 ** Generate code that will assemble an index key and put it in register
82155 ** regOut.  The key with be for index pIdx which is an index on pTab.
82156 ** iCur is the index of a cursor open on the pTab table and pointing to
82157 ** the entry that needs indexing.
82158 **
82159 ** Return a register number which is the first in a block of
82160 ** registers that holds the elements of the index key.  The
82161 ** block of registers has already been deallocated by the time
82162 ** this routine returns.
82163 */
82164 SQLITE_PRIVATE int sqlite3GenerateIndexKey(
82165   Parse *pParse,     /* Parsing context */
82166   Index *pIdx,       /* The index for which to generate a key */
82167   int iCur,          /* Cursor number for the pIdx->pTable table */
82168   int regOut,        /* Write the new index key to this register */
82169   int doMakeRec      /* Run the OP_MakeRecord instruction if true */
82170 ){
82171   Vdbe *v = pParse->pVdbe;
82172   int j;
82173   Table *pTab = pIdx->pTable;
82174   int regBase;
82175   int nCol;
82176
82177   nCol = pIdx->nColumn;
82178   regBase = sqlite3GetTempRange(pParse, nCol+1);
82179   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
82180   for(j=0; j<nCol; j++){
82181     int idx = pIdx->aiColumn[j];
82182     if( idx==pTab->iPKey ){
82183       sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
82184     }else{
82185       sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
82186       sqlite3ColumnDefault(v, pTab, idx, -1);
82187     }
82188   }
82189   if( doMakeRec ){
82190     const char *zAff;
82191     if( pTab->pSelect || (pParse->db->flags & SQLITE_IdxRealAsInt)!=0 ){
82192       zAff = 0;
82193     }else{
82194       zAff = sqlite3IndexAffinityStr(v, pIdx);
82195     }
82196     sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
82197     sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT);
82198   }
82199   sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
82200   return regBase;
82201 }
82202
82203 /************** End of delete.c **********************************************/
82204 /************** Begin file func.c ********************************************/
82205 /*
82206 ** 2002 February 23
82207 **
82208 ** The author disclaims copyright to this source code.  In place of
82209 ** a legal notice, here is a blessing:
82210 **
82211 **    May you do good and not evil.
82212 **    May you find forgiveness for yourself and forgive others.
82213 **    May you share freely, never taking more than you give.
82214 **
82215 *************************************************************************
82216 ** This file contains the C functions that implement various SQL
82217 ** functions of SQLite.  
82218 **
82219 ** There is only one exported symbol in this file - the function
82220 ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
82221 ** All other code has file scope.
82222 */
82223
82224 /*
82225 ** Return the collating function associated with a function.
82226 */
82227 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
82228   return context->pColl;
82229 }
82230
82231 /*
82232 ** Implementation of the non-aggregate min() and max() functions
82233 */
82234 static void minmaxFunc(
82235   sqlite3_context *context,
82236   int argc,
82237   sqlite3_value **argv
82238 ){
82239   int i;
82240   int mask;    /* 0 for min() or 0xffffffff for max() */
82241   int iBest;
82242   CollSeq *pColl;
82243
82244   assert( argc>1 );
82245   mask = sqlite3_user_data(context)==0 ? 0 : -1;
82246   pColl = sqlite3GetFuncCollSeq(context);
82247   assert( pColl );
82248   assert( mask==-1 || mask==0 );
82249   iBest = 0;
82250   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
82251   for(i=1; i<argc; i++){
82252     if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
82253     if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
82254       testcase( mask==0 );
82255       iBest = i;
82256     }
82257   }
82258   sqlite3_result_value(context, argv[iBest]);
82259 }
82260
82261 /*
82262 ** Return the type of the argument.
82263 */
82264 static void typeofFunc(
82265   sqlite3_context *context,
82266   int NotUsed,
82267   sqlite3_value **argv
82268 ){
82269   const char *z = 0;
82270   UNUSED_PARAMETER(NotUsed);
82271   switch( sqlite3_value_type(argv[0]) ){
82272     case SQLITE_INTEGER: z = "integer"; break;
82273     case SQLITE_TEXT:    z = "text";    break;
82274     case SQLITE_FLOAT:   z = "real";    break;
82275     case SQLITE_BLOB:    z = "blob";    break;
82276     default:             z = "null";    break;
82277   }
82278   sqlite3_result_text(context, z, -1, SQLITE_STATIC);
82279 }
82280
82281
82282 /*
82283 ** Implementation of the length() function
82284 */
82285 static void lengthFunc(
82286   sqlite3_context *context,
82287   int argc,
82288   sqlite3_value **argv
82289 ){
82290   int len;
82291
82292   assert( argc==1 );
82293   UNUSED_PARAMETER(argc);
82294   switch( sqlite3_value_type(argv[0]) ){
82295     case SQLITE_BLOB:
82296     case SQLITE_INTEGER:
82297     case SQLITE_FLOAT: {
82298       sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
82299       break;
82300     }
82301     case SQLITE_TEXT: {
82302       const unsigned char *z = sqlite3_value_text(argv[0]);
82303       if( z==0 ) return;
82304       len = 0;
82305       while( *z ){
82306         len++;
82307         SQLITE_SKIP_UTF8(z);
82308       }
82309       sqlite3_result_int(context, len);
82310       break;
82311     }
82312     default: {
82313       sqlite3_result_null(context);
82314       break;
82315     }
82316   }
82317 }
82318
82319 /*
82320 ** Implementation of the abs() function.
82321 **
82322 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
82323 ** the numeric argument X. 
82324 */
82325 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
82326   assert( argc==1 );
82327   UNUSED_PARAMETER(argc);
82328   switch( sqlite3_value_type(argv[0]) ){
82329     case SQLITE_INTEGER: {
82330       i64 iVal = sqlite3_value_int64(argv[0]);
82331       if( iVal<0 ){
82332         if( (iVal<<1)==0 ){
82333           /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then
82334           ** abs(X) throws an integer overflow error since there is no
82335           ** equivalent positive 64-bit two complement value. */
82336           sqlite3_result_error(context, "integer overflow", -1);
82337           return;
82338         }
82339         iVal = -iVal;
82340       } 
82341       sqlite3_result_int64(context, iVal);
82342       break;
82343     }
82344     case SQLITE_NULL: {
82345       /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
82346       sqlite3_result_null(context);
82347       break;
82348     }
82349     default: {
82350       /* Because sqlite3_value_double() returns 0.0 if the argument is not
82351       ** something that can be converted into a number, we have:
82352       ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
82353       ** cannot be converted to a numeric value. 
82354       */
82355       double rVal = sqlite3_value_double(argv[0]);
82356       if( rVal<0 ) rVal = -rVal;
82357       sqlite3_result_double(context, rVal);
82358       break;
82359     }
82360   }
82361 }
82362
82363 /*
82364 ** Implementation of the substr() function.
82365 **
82366 ** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
82367 ** p1 is 1-indexed.  So substr(x,1,1) returns the first character
82368 ** of x.  If x is text, then we actually count UTF-8 characters.
82369 ** If x is a blob, then we count bytes.
82370 **
82371 ** If p1 is negative, then we begin abs(p1) from the end of x[].
82372 **
82373 ** If p2 is negative, return the p2 characters preceeding p1.
82374 */
82375 static void substrFunc(
82376   sqlite3_context *context,
82377   int argc,
82378   sqlite3_value **argv
82379 ){
82380   const unsigned char *z;
82381   const unsigned char *z2;
82382   int len;
82383   int p0type;
82384   i64 p1, p2;
82385   int negP2 = 0;
82386
82387   assert( argc==3 || argc==2 );
82388   if( sqlite3_value_type(argv[1])==SQLITE_NULL
82389    || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
82390   ){
82391     return;
82392   }
82393   p0type = sqlite3_value_type(argv[0]);
82394   p1 = sqlite3_value_int(argv[1]);
82395   if( p0type==SQLITE_BLOB ){
82396     len = sqlite3_value_bytes(argv[0]);
82397     z = sqlite3_value_blob(argv[0]);
82398     if( z==0 ) return;
82399     assert( len==sqlite3_value_bytes(argv[0]) );
82400   }else{
82401     z = sqlite3_value_text(argv[0]);
82402     if( z==0 ) return;
82403     len = 0;
82404     if( p1<0 ){
82405       for(z2=z; *z2; len++){
82406         SQLITE_SKIP_UTF8(z2);
82407       }
82408     }
82409   }
82410   if( argc==3 ){
82411     p2 = sqlite3_value_int(argv[2]);
82412     if( p2<0 ){
82413       p2 = -p2;
82414       negP2 = 1;
82415     }
82416   }else{
82417     p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
82418   }
82419   if( p1<0 ){
82420     p1 += len;
82421     if( p1<0 ){
82422       p2 += p1;
82423       if( p2<0 ) p2 = 0;
82424       p1 = 0;
82425     }
82426   }else if( p1>0 ){
82427     p1--;
82428   }else if( p2>0 ){
82429     p2--;
82430   }
82431   if( negP2 ){
82432     p1 -= p2;
82433     if( p1<0 ){
82434       p2 += p1;
82435       p1 = 0;
82436     }
82437   }
82438   assert( p1>=0 && p2>=0 );
82439   if( p0type!=SQLITE_BLOB ){
82440     while( *z && p1 ){
82441       SQLITE_SKIP_UTF8(z);
82442       p1--;
82443     }
82444     for(z2=z; *z2 && p2; p2--){
82445       SQLITE_SKIP_UTF8(z2);
82446     }
82447     sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
82448   }else{
82449     if( p1+p2>len ){
82450       p2 = len-p1;
82451       if( p2<0 ) p2 = 0;
82452     }
82453     sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
82454   }
82455 }
82456
82457 /*
82458 ** Implementation of the round() function
82459 */
82460 #ifndef SQLITE_OMIT_FLOATING_POINT
82461 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
82462   int n = 0;
82463   double r;
82464   char *zBuf;
82465   assert( argc==1 || argc==2 );
82466   if( argc==2 ){
82467     if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
82468     n = sqlite3_value_int(argv[1]);
82469     if( n>30 ) n = 30;
82470     if( n<0 ) n = 0;
82471   }
82472   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
82473   r = sqlite3_value_double(argv[0]);
82474   /* If Y==0 and X will fit in a 64-bit int,
82475   ** handle the rounding directly,
82476   ** otherwise use printf.
82477   */
82478   if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
82479     r = (double)((sqlite_int64)(r+0.5));
82480   }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
82481     r = -(double)((sqlite_int64)((-r)+0.5));
82482   }else{
82483     zBuf = sqlite3_mprintf("%.*f",n,r);
82484     if( zBuf==0 ){
82485       sqlite3_result_error_nomem(context);
82486       return;
82487     }
82488     sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
82489     sqlite3_free(zBuf);
82490   }
82491   sqlite3_result_double(context, r);
82492 }
82493 #endif
82494
82495 /*
82496 ** Allocate nByte bytes of space using sqlite3_malloc(). If the
82497 ** allocation fails, call sqlite3_result_error_nomem() to notify
82498 ** the database handle that malloc() has failed and return NULL.
82499 ** If nByte is larger than the maximum string or blob length, then
82500 ** raise an SQLITE_TOOBIG exception and return NULL.
82501 */
82502 static void *contextMalloc(sqlite3_context *context, i64 nByte){
82503   char *z;
82504   sqlite3 *db = sqlite3_context_db_handle(context);
82505   assert( nByte>0 );
82506   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
82507   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
82508   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
82509     sqlite3_result_error_toobig(context);
82510     z = 0;
82511   }else{
82512     z = sqlite3Malloc((int)nByte);
82513     if( !z ){
82514       sqlite3_result_error_nomem(context);
82515     }
82516   }
82517   return z;
82518 }
82519
82520 /*
82521 ** Implementation of the upper() and lower() SQL functions.
82522 */
82523 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
82524   char *z1;
82525   const char *z2;
82526   int i, n;
82527   UNUSED_PARAMETER(argc);
82528   z2 = (char*)sqlite3_value_text(argv[0]);
82529   n = sqlite3_value_bytes(argv[0]);
82530   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
82531   assert( z2==(char*)sqlite3_value_text(argv[0]) );
82532   if( z2 ){
82533     z1 = contextMalloc(context, ((i64)n)+1);
82534     if( z1 ){
82535       memcpy(z1, z2, n+1);
82536       for(i=0; z1[i]; i++){
82537         z1[i] = (char)sqlite3Toupper(z1[i]);
82538       }
82539       sqlite3_result_text(context, z1, -1, sqlite3_free);
82540     }
82541   }
82542 }
82543 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
82544   u8 *z1;
82545   const char *z2;
82546   int i, n;
82547   UNUSED_PARAMETER(argc);
82548   z2 = (char*)sqlite3_value_text(argv[0]);
82549   n = sqlite3_value_bytes(argv[0]);
82550   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
82551   assert( z2==(char*)sqlite3_value_text(argv[0]) );
82552   if( z2 ){
82553     z1 = contextMalloc(context, ((i64)n)+1);
82554     if( z1 ){
82555       memcpy(z1, z2, n+1);
82556       for(i=0; z1[i]; i++){
82557         z1[i] = sqlite3Tolower(z1[i]);
82558       }
82559       sqlite3_result_text(context, (char *)z1, -1, sqlite3_free);
82560     }
82561   }
82562 }
82563
82564
82565 #if 0  /* This function is never used. */
82566 /*
82567 ** The COALESCE() and IFNULL() functions used to be implemented as shown
82568 ** here.  But now they are implemented as VDBE code so that unused arguments
82569 ** do not have to be computed.  This legacy implementation is retained as
82570 ** comment.
82571 */
82572 /*
82573 ** Implementation of the IFNULL(), NVL(), and COALESCE() functions.  
82574 ** All three do the same thing.  They return the first non-NULL
82575 ** argument.
82576 */
82577 static void ifnullFunc(
82578   sqlite3_context *context,
82579   int argc,
82580   sqlite3_value **argv
82581 ){
82582   int i;
82583   for(i=0; i<argc; i++){
82584     if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
82585       sqlite3_result_value(context, argv[i]);
82586       break;
82587     }
82588   }
82589 }
82590 #endif /* NOT USED */
82591 #define ifnullFunc versionFunc   /* Substitute function - never called */
82592
82593 /*
82594 ** Implementation of random().  Return a random integer.  
82595 */
82596 static void randomFunc(
82597   sqlite3_context *context,
82598   int NotUsed,
82599   sqlite3_value **NotUsed2
82600 ){
82601   sqlite_int64 r;
82602   UNUSED_PARAMETER2(NotUsed, NotUsed2);
82603   sqlite3_randomness(sizeof(r), &r);
82604   if( r<0 ){
82605     /* We need to prevent a random number of 0x8000000000000000 
82606     ** (or -9223372036854775808) since when you do abs() of that
82607     ** number of you get the same value back again.  To do this
82608     ** in a way that is testable, mask the sign bit off of negative
82609     ** values, resulting in a positive value.  Then take the 
82610     ** 2s complement of that positive value.  The end result can
82611     ** therefore be no less than -9223372036854775807.
82612     */
82613     r = -(r ^ (((sqlite3_int64)1)<<63));
82614   }
82615   sqlite3_result_int64(context, r);
82616 }
82617
82618 /*
82619 ** Implementation of randomblob(N).  Return a random blob
82620 ** that is N bytes long.
82621 */
82622 static void randomBlob(
82623   sqlite3_context *context,
82624   int argc,
82625   sqlite3_value **argv
82626 ){
82627   int n;
82628   unsigned char *p;
82629   assert( argc==1 );
82630   UNUSED_PARAMETER(argc);
82631   n = sqlite3_value_int(argv[0]);
82632   if( n<1 ){
82633     n = 1;
82634   }
82635   p = contextMalloc(context, n);
82636   if( p ){
82637     sqlite3_randomness(n, p);
82638     sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
82639   }
82640 }
82641
82642 /*
82643 ** Implementation of the last_insert_rowid() SQL function.  The return
82644 ** value is the same as the sqlite3_last_insert_rowid() API function.
82645 */
82646 static void last_insert_rowid(
82647   sqlite3_context *context, 
82648   int NotUsed, 
82649   sqlite3_value **NotUsed2
82650 ){
82651   sqlite3 *db = sqlite3_context_db_handle(context);
82652   UNUSED_PARAMETER2(NotUsed, NotUsed2);
82653   /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
82654   ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
82655   ** function. */
82656   sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
82657 }
82658
82659 /*
82660 ** Implementation of the changes() SQL function.
82661 **
82662 ** IMP: R-62073-11209 The changes() SQL function is a wrapper
82663 ** around the sqlite3_changes() C/C++ function and hence follows the same
82664 ** rules for counting changes.
82665 */
82666 static void changes(
82667   sqlite3_context *context,
82668   int NotUsed,
82669   sqlite3_value **NotUsed2
82670 ){
82671   sqlite3 *db = sqlite3_context_db_handle(context);
82672   UNUSED_PARAMETER2(NotUsed, NotUsed2);
82673   sqlite3_result_int(context, sqlite3_changes(db));
82674 }
82675
82676 /*
82677 ** Implementation of the total_changes() SQL function.  The return value is
82678 ** the same as the sqlite3_total_changes() API function.
82679 */
82680 static void total_changes(
82681   sqlite3_context *context,
82682   int NotUsed,
82683   sqlite3_value **NotUsed2
82684 ){
82685   sqlite3 *db = sqlite3_context_db_handle(context);
82686   UNUSED_PARAMETER2(NotUsed, NotUsed2);
82687   /* IMP: R-52756-41993 This function is a wrapper around the
82688   ** sqlite3_total_changes() C/C++ interface. */
82689   sqlite3_result_int(context, sqlite3_total_changes(db));
82690 }
82691
82692 /*
82693 ** A structure defining how to do GLOB-style comparisons.
82694 */
82695 struct compareInfo {
82696   u8 matchAll;
82697   u8 matchOne;
82698   u8 matchSet;
82699   u8 noCase;
82700 };
82701
82702 /*
82703 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
82704 ** character is exactly one byte in size.  Also, all characters are
82705 ** able to participate in upper-case-to-lower-case mappings in EBCDIC
82706 ** whereas only characters less than 0x80 do in ASCII.
82707 */
82708 #if defined(SQLITE_EBCDIC)
82709 # define sqlite3Utf8Read(A,C)  (*(A++))
82710 # define GlogUpperToLower(A)   A = sqlite3UpperToLower[A]
82711 #else
82712 # define GlogUpperToLower(A)   if( !((A)&~0x7f) ){ A = sqlite3UpperToLower[A]; }
82713 #endif
82714
82715 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
82716 /* The correct SQL-92 behavior is for the LIKE operator to ignore
82717 ** case.  Thus  'a' LIKE 'A' would be true. */
82718 static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
82719 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
82720 ** is case sensitive causing 'a' LIKE 'A' to be false */
82721 static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
82722
82723 /*
82724 ** Compare two UTF-8 strings for equality where the first string can
82725 ** potentially be a "glob" expression.  Return true (1) if they
82726 ** are the same and false (0) if they are different.
82727 **
82728 ** Globbing rules:
82729 **
82730 **      '*'       Matches any sequence of zero or more characters.
82731 **
82732 **      '?'       Matches exactly one character.
82733 **
82734 **     [...]      Matches one character from the enclosed list of
82735 **                characters.
82736 **
82737 **     [^...]     Matches one character not in the enclosed list.
82738 **
82739 ** With the [...] and [^...] matching, a ']' character can be included
82740 ** in the list by making it the first character after '[' or '^'.  A
82741 ** range of characters can be specified using '-'.  Example:
82742 ** "[a-z]" matches any single lower-case letter.  To match a '-', make
82743 ** it the last character in the list.
82744 **
82745 ** This routine is usually quick, but can be N**2 in the worst case.
82746 **
82747 ** Hints: to match '*' or '?', put them in "[]".  Like this:
82748 **
82749 **         abc[*]xyz        Matches "abc*xyz" only
82750 */
82751 static int patternCompare(
82752   const u8 *zPattern,              /* The glob pattern */
82753   const u8 *zString,               /* The string to compare against the glob */
82754   const struct compareInfo *pInfo, /* Information about how to do the compare */
82755   u32 esc                          /* The escape character */
82756 ){
82757   u32 c, c2;
82758   int invert;
82759   int seen;
82760   u8 matchOne = pInfo->matchOne;
82761   u8 matchAll = pInfo->matchAll;
82762   u8 matchSet = pInfo->matchSet;
82763   u8 noCase = pInfo->noCase; 
82764   int prevEscape = 0;     /* True if the previous character was 'escape' */
82765
82766   while( (c = sqlite3Utf8Read(zPattern,&zPattern))!=0 ){
82767     if( !prevEscape && c==matchAll ){
82768       while( (c=sqlite3Utf8Read(zPattern,&zPattern)) == matchAll
82769                || c == matchOne ){
82770         if( c==matchOne && sqlite3Utf8Read(zString, &zString)==0 ){
82771           return 0;
82772         }
82773       }
82774       if( c==0 ){
82775         return 1;
82776       }else if( c==esc ){
82777         c = sqlite3Utf8Read(zPattern, &zPattern);
82778         if( c==0 ){
82779           return 0;
82780         }
82781       }else if( c==matchSet ){
82782         assert( esc==0 );         /* This is GLOB, not LIKE */
82783         assert( matchSet<0x80 );  /* '[' is a single-byte character */
82784         while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
82785           SQLITE_SKIP_UTF8(zString);
82786         }
82787         return *zString!=0;
82788       }
82789       while( (c2 = sqlite3Utf8Read(zString,&zString))!=0 ){
82790         if( noCase ){
82791           GlogUpperToLower(c2);
82792           GlogUpperToLower(c);
82793           while( c2 != 0 && c2 != c ){
82794             c2 = sqlite3Utf8Read(zString, &zString);
82795             GlogUpperToLower(c2);
82796           }
82797         }else{
82798           while( c2 != 0 && c2 != c ){
82799             c2 = sqlite3Utf8Read(zString, &zString);
82800           }
82801         }
82802         if( c2==0 ) return 0;
82803         if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
82804       }
82805       return 0;
82806     }else if( !prevEscape && c==matchOne ){
82807       if( sqlite3Utf8Read(zString, &zString)==0 ){
82808         return 0;
82809       }
82810     }else if( c==matchSet ){
82811       u32 prior_c = 0;
82812       assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
82813       seen = 0;
82814       invert = 0;
82815       c = sqlite3Utf8Read(zString, &zString);
82816       if( c==0 ) return 0;
82817       c2 = sqlite3Utf8Read(zPattern, &zPattern);
82818       if( c2=='^' ){
82819         invert = 1;
82820         c2 = sqlite3Utf8Read(zPattern, &zPattern);
82821       }
82822       if( c2==']' ){
82823         if( c==']' ) seen = 1;
82824         c2 = sqlite3Utf8Read(zPattern, &zPattern);
82825       }
82826       while( c2 && c2!=']' ){
82827         if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
82828           c2 = sqlite3Utf8Read(zPattern, &zPattern);
82829           if( c>=prior_c && c<=c2 ) seen = 1;
82830           prior_c = 0;
82831         }else{
82832           if( c==c2 ){
82833             seen = 1;
82834           }
82835           prior_c = c2;
82836         }
82837         c2 = sqlite3Utf8Read(zPattern, &zPattern);
82838       }
82839       if( c2==0 || (seen ^ invert)==0 ){
82840         return 0;
82841       }
82842     }else if( esc==c && !prevEscape ){
82843       prevEscape = 1;
82844     }else{
82845       c2 = sqlite3Utf8Read(zString, &zString);
82846       if( noCase ){
82847         GlogUpperToLower(c);
82848         GlogUpperToLower(c2);
82849       }
82850       if( c!=c2 ){
82851         return 0;
82852       }
82853       prevEscape = 0;
82854     }
82855   }
82856   return *zString==0;
82857 }
82858
82859 /*
82860 ** Count the number of times that the LIKE operator (or GLOB which is
82861 ** just a variation of LIKE) gets called.  This is used for testing
82862 ** only.
82863 */
82864 #ifdef SQLITE_TEST
82865 SQLITE_API int sqlite3_like_count = 0;
82866 #endif
82867
82868
82869 /*
82870 ** Implementation of the like() SQL function.  This function implements
82871 ** the build-in LIKE operator.  The first argument to the function is the
82872 ** pattern and the second argument is the string.  So, the SQL statements:
82873 **
82874 **       A LIKE B
82875 **
82876 ** is implemented as like(B,A).
82877 **
82878 ** This same function (with a different compareInfo structure) computes
82879 ** the GLOB operator.
82880 */
82881 static void likeFunc(
82882   sqlite3_context *context, 
82883   int argc, 
82884   sqlite3_value **argv
82885 ){
82886   const unsigned char *zA, *zB;
82887   u32 escape = 0;
82888   int nPat;
82889   sqlite3 *db = sqlite3_context_db_handle(context);
82890
82891   zB = sqlite3_value_text(argv[0]);
82892   zA = sqlite3_value_text(argv[1]);
82893
82894   /* Limit the length of the LIKE or GLOB pattern to avoid problems
82895   ** of deep recursion and N*N behavior in patternCompare().
82896   */
82897   nPat = sqlite3_value_bytes(argv[0]);
82898   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
82899   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
82900   if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
82901     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
82902     return;
82903   }
82904   assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
82905
82906   if( argc==3 ){
82907     /* The escape character string must consist of a single UTF-8 character.
82908     ** Otherwise, return an error.
82909     */
82910     const unsigned char *zEsc = sqlite3_value_text(argv[2]);
82911     if( zEsc==0 ) return;
82912     if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
82913       sqlite3_result_error(context, 
82914           "ESCAPE expression must be a single character", -1);
82915       return;
82916     }
82917     escape = sqlite3Utf8Read(zEsc, &zEsc);
82918   }
82919   if( zA && zB ){
82920     struct compareInfo *pInfo = sqlite3_user_data(context);
82921 #ifdef SQLITE_TEST
82922     sqlite3_like_count++;
82923 #endif
82924     
82925     sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
82926   }
82927 }
82928
82929 /*
82930 ** Implementation of the NULLIF(x,y) function.  The result is the first
82931 ** argument if the arguments are different.  The result is NULL if the
82932 ** arguments are equal to each other.
82933 */
82934 static void nullifFunc(
82935   sqlite3_context *context,
82936   int NotUsed,
82937   sqlite3_value **argv
82938 ){
82939   CollSeq *pColl = sqlite3GetFuncCollSeq(context);
82940   UNUSED_PARAMETER(NotUsed);
82941   if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
82942     sqlite3_result_value(context, argv[0]);
82943   }
82944 }
82945
82946 /*
82947 ** Implementation of the sqlite_version() function.  The result is the version
82948 ** of the SQLite library that is running.
82949 */
82950 static void versionFunc(
82951   sqlite3_context *context,
82952   int NotUsed,
82953   sqlite3_value **NotUsed2
82954 ){
82955   UNUSED_PARAMETER2(NotUsed, NotUsed2);
82956   /* IMP: R-48699-48617 This function is an SQL wrapper around the
82957   ** sqlite3_libversion() C-interface. */
82958   sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
82959 }
82960
82961 /*
82962 ** Implementation of the sqlite_source_id() function. The result is a string
82963 ** that identifies the particular version of the source code used to build
82964 ** SQLite.
82965 */
82966 static void sourceidFunc(
82967   sqlite3_context *context,
82968   int NotUsed,
82969   sqlite3_value **NotUsed2
82970 ){
82971   UNUSED_PARAMETER2(NotUsed, NotUsed2);
82972   /* IMP: R-24470-31136 This function is an SQL wrapper around the
82973   ** sqlite3_sourceid() C interface. */
82974   sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
82975 }
82976
82977 /*
82978 ** Implementation of the sqlite_log() function.  This is a wrapper around
82979 ** sqlite3_log().  The return value is NULL.  The function exists purely for
82980 ** its side-effects.
82981 */
82982 static void errlogFunc(
82983   sqlite3_context *context,
82984   int argc,
82985   sqlite3_value **argv
82986 ){
82987   UNUSED_PARAMETER(argc);
82988   UNUSED_PARAMETER(context);
82989   sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
82990 }
82991
82992 /*
82993 ** Implementation of the sqlite_compileoption_used() function.
82994 ** The result is an integer that identifies if the compiler option
82995 ** was used to build SQLite.
82996 */
82997 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
82998 static void compileoptionusedFunc(
82999   sqlite3_context *context,
83000   int argc,
83001   sqlite3_value **argv
83002 ){
83003   const char *zOptName;
83004   assert( argc==1 );
83005   UNUSED_PARAMETER(argc);
83006   /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
83007   ** function is a wrapper around the sqlite3_compileoption_used() C/C++
83008   ** function.
83009   */
83010   if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
83011     sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
83012   }
83013 }
83014 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
83015
83016 /*
83017 ** Implementation of the sqlite_compileoption_get() function. 
83018 ** The result is a string that identifies the compiler options 
83019 ** used to build SQLite.
83020 */
83021 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
83022 static void compileoptiongetFunc(
83023   sqlite3_context *context,
83024   int argc,
83025   sqlite3_value **argv
83026 ){
83027   int n;
83028   assert( argc==1 );
83029   UNUSED_PARAMETER(argc);
83030   /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
83031   ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
83032   */
83033   n = sqlite3_value_int(argv[0]);
83034   sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
83035 }
83036 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
83037
83038 /* Array for converting from half-bytes (nybbles) into ASCII hex
83039 ** digits. */
83040 static const char hexdigits[] = {
83041   '0', '1', '2', '3', '4', '5', '6', '7',
83042   '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' 
83043 };
83044
83045 /*
83046 ** EXPERIMENTAL - This is not an official function.  The interface may
83047 ** change.  This function may disappear.  Do not write code that depends
83048 ** on this function.
83049 **
83050 ** Implementation of the QUOTE() function.  This function takes a single
83051 ** argument.  If the argument is numeric, the return value is the same as
83052 ** the argument.  If the argument is NULL, the return value is the string
83053 ** "NULL".  Otherwise, the argument is enclosed in single quotes with
83054 ** single-quote escapes.
83055 */
83056 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
83057   assert( argc==1 );
83058   UNUSED_PARAMETER(argc);
83059   switch( sqlite3_value_type(argv[0]) ){
83060     case SQLITE_INTEGER:
83061     case SQLITE_FLOAT: {
83062       sqlite3_result_value(context, argv[0]);
83063       break;
83064     }
83065     case SQLITE_BLOB: {
83066       char *zText = 0;
83067       char const *zBlob = sqlite3_value_blob(argv[0]);
83068       int nBlob = sqlite3_value_bytes(argv[0]);
83069       assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
83070       zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4); 
83071       if( zText ){
83072         int i;
83073         for(i=0; i<nBlob; i++){
83074           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
83075           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
83076         }
83077         zText[(nBlob*2)+2] = '\'';
83078         zText[(nBlob*2)+3] = '\0';
83079         zText[0] = 'X';
83080         zText[1] = '\'';
83081         sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
83082         sqlite3_free(zText);
83083       }
83084       break;
83085     }
83086     case SQLITE_TEXT: {
83087       int i,j;
83088       u64 n;
83089       const unsigned char *zArg = sqlite3_value_text(argv[0]);
83090       char *z;
83091
83092       if( zArg==0 ) return;
83093       for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
83094       z = contextMalloc(context, ((i64)i)+((i64)n)+3);
83095       if( z ){
83096         z[0] = '\'';
83097         for(i=0, j=1; zArg[i]; i++){
83098           z[j++] = zArg[i];
83099           if( zArg[i]=='\'' ){
83100             z[j++] = '\'';
83101           }
83102         }
83103         z[j++] = '\'';
83104         z[j] = 0;
83105         sqlite3_result_text(context, z, j, sqlite3_free);
83106       }
83107       break;
83108     }
83109     default: {
83110       assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
83111       sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
83112       break;
83113     }
83114   }
83115 }
83116
83117 /*
83118 ** The hex() function.  Interpret the argument as a blob.  Return
83119 ** a hexadecimal rendering as text.
83120 */
83121 static void hexFunc(
83122   sqlite3_context *context,
83123   int argc,
83124   sqlite3_value **argv
83125 ){
83126   int i, n;
83127   const unsigned char *pBlob;
83128   char *zHex, *z;
83129   assert( argc==1 );
83130   UNUSED_PARAMETER(argc);
83131   pBlob = sqlite3_value_blob(argv[0]);
83132   n = sqlite3_value_bytes(argv[0]);
83133   assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
83134   z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
83135   if( zHex ){
83136     for(i=0; i<n; i++, pBlob++){
83137       unsigned char c = *pBlob;
83138       *(z++) = hexdigits[(c>>4)&0xf];
83139       *(z++) = hexdigits[c&0xf];
83140     }
83141     *z = 0;
83142     sqlite3_result_text(context, zHex, n*2, sqlite3_free);
83143   }
83144 }
83145
83146 /*
83147 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
83148 */
83149 static void zeroblobFunc(
83150   sqlite3_context *context,
83151   int argc,
83152   sqlite3_value **argv
83153 ){
83154   i64 n;
83155   sqlite3 *db = sqlite3_context_db_handle(context);
83156   assert( argc==1 );
83157   UNUSED_PARAMETER(argc);
83158   n = sqlite3_value_int64(argv[0]);
83159   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
83160   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
83161   if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
83162     sqlite3_result_error_toobig(context);
83163   }else{
83164     sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
83165   }
83166 }
83167
83168 /*
83169 ** The replace() function.  Three arguments are all strings: call
83170 ** them A, B, and C. The result is also a string which is derived
83171 ** from A by replacing every occurance of B with C.  The match
83172 ** must be exact.  Collating sequences are not used.
83173 */
83174 static void replaceFunc(
83175   sqlite3_context *context,
83176   int argc,
83177   sqlite3_value **argv
83178 ){
83179   const unsigned char *zStr;        /* The input string A */
83180   const unsigned char *zPattern;    /* The pattern string B */
83181   const unsigned char *zRep;        /* The replacement string C */
83182   unsigned char *zOut;              /* The output */
83183   int nStr;                /* Size of zStr */
83184   int nPattern;            /* Size of zPattern */
83185   int nRep;                /* Size of zRep */
83186   i64 nOut;                /* Maximum size of zOut */
83187   int loopLimit;           /* Last zStr[] that might match zPattern[] */
83188   int i, j;                /* Loop counters */
83189
83190   assert( argc==3 );
83191   UNUSED_PARAMETER(argc);
83192   zStr = sqlite3_value_text(argv[0]);
83193   if( zStr==0 ) return;
83194   nStr = sqlite3_value_bytes(argv[0]);
83195   assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
83196   zPattern = sqlite3_value_text(argv[1]);
83197   if( zPattern==0 ){
83198     assert( sqlite3_value_type(argv[1])==SQLITE_NULL
83199             || sqlite3_context_db_handle(context)->mallocFailed );
83200     return;
83201   }
83202   if( zPattern[0]==0 ){
83203     assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
83204     sqlite3_result_value(context, argv[0]);
83205     return;
83206   }
83207   nPattern = sqlite3_value_bytes(argv[1]);
83208   assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
83209   zRep = sqlite3_value_text(argv[2]);
83210   if( zRep==0 ) return;
83211   nRep = sqlite3_value_bytes(argv[2]);
83212   assert( zRep==sqlite3_value_text(argv[2]) );
83213   nOut = nStr + 1;
83214   assert( nOut<SQLITE_MAX_LENGTH );
83215   zOut = contextMalloc(context, (i64)nOut);
83216   if( zOut==0 ){
83217     return;
83218   }
83219   loopLimit = nStr - nPattern;  
83220   for(i=j=0; i<=loopLimit; i++){
83221     if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
83222       zOut[j++] = zStr[i];
83223     }else{
83224       u8 *zOld;
83225       sqlite3 *db = sqlite3_context_db_handle(context);
83226       nOut += nRep - nPattern;
83227       testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
83228       testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
83229       if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
83230         sqlite3_result_error_toobig(context);
83231         sqlite3_free(zOut);
83232         return;
83233       }
83234       zOld = zOut;
83235       zOut = sqlite3_realloc(zOut, (int)nOut);
83236       if( zOut==0 ){
83237         sqlite3_result_error_nomem(context);
83238         sqlite3_free(zOld);
83239         return;
83240       }
83241       memcpy(&zOut[j], zRep, nRep);
83242       j += nRep;
83243       i += nPattern-1;
83244     }
83245   }
83246   assert( j+nStr-i+1==nOut );
83247   memcpy(&zOut[j], &zStr[i], nStr-i);
83248   j += nStr - i;
83249   assert( j<=nOut );
83250   zOut[j] = 0;
83251   sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
83252 }
83253
83254 /*
83255 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
83256 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
83257 */
83258 static void trimFunc(
83259   sqlite3_context *context,
83260   int argc,
83261   sqlite3_value **argv
83262 ){
83263   const unsigned char *zIn;         /* Input string */
83264   const unsigned char *zCharSet;    /* Set of characters to trim */
83265   int nIn;                          /* Number of bytes in input */
83266   int flags;                        /* 1: trimleft  2: trimright  3: trim */
83267   int i;                            /* Loop counter */
83268   unsigned char *aLen = 0;          /* Length of each character in zCharSet */
83269   unsigned char **azChar = 0;       /* Individual characters in zCharSet */
83270   int nChar;                        /* Number of characters in zCharSet */
83271
83272   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
83273     return;
83274   }
83275   zIn = sqlite3_value_text(argv[0]);
83276   if( zIn==0 ) return;
83277   nIn = sqlite3_value_bytes(argv[0]);
83278   assert( zIn==sqlite3_value_text(argv[0]) );
83279   if( argc==1 ){
83280     static const unsigned char lenOne[] = { 1 };
83281     static unsigned char * const azOne[] = { (u8*)" " };
83282     nChar = 1;
83283     aLen = (u8*)lenOne;
83284     azChar = (unsigned char **)azOne;
83285     zCharSet = 0;
83286   }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
83287     return;
83288   }else{
83289     const unsigned char *z;
83290     for(z=zCharSet, nChar=0; *z; nChar++){
83291       SQLITE_SKIP_UTF8(z);
83292     }
83293     if( nChar>0 ){
83294       azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
83295       if( azChar==0 ){
83296         return;
83297       }
83298       aLen = (unsigned char*)&azChar[nChar];
83299       for(z=zCharSet, nChar=0; *z; nChar++){
83300         azChar[nChar] = (unsigned char *)z;
83301         SQLITE_SKIP_UTF8(z);
83302         aLen[nChar] = (u8)(z - azChar[nChar]);
83303       }
83304     }
83305   }
83306   if( nChar>0 ){
83307     flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
83308     if( flags & 1 ){
83309       while( nIn>0 ){
83310         int len = 0;
83311         for(i=0; i<nChar; i++){
83312           len = aLen[i];
83313           if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
83314         }
83315         if( i>=nChar ) break;
83316         zIn += len;
83317         nIn -= len;
83318       }
83319     }
83320     if( flags & 2 ){
83321       while( nIn>0 ){
83322         int len = 0;
83323         for(i=0; i<nChar; i++){
83324           len = aLen[i];
83325           if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
83326         }
83327         if( i>=nChar ) break;
83328         nIn -= len;
83329       }
83330     }
83331     if( zCharSet ){
83332       sqlite3_free(azChar);
83333     }
83334   }
83335   sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
83336 }
83337
83338
83339 /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
83340 ** is only available if the SQLITE_SOUNDEX compile-time option is used
83341 ** when SQLite is built.
83342 */
83343 #ifdef SQLITE_SOUNDEX
83344 /*
83345 ** Compute the soundex encoding of a word.
83346 **
83347 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
83348 ** soundex encoding of the string X. 
83349 */
83350 static void soundexFunc(
83351   sqlite3_context *context,
83352   int argc,
83353   sqlite3_value **argv
83354 ){
83355   char zResult[8];
83356   const u8 *zIn;
83357   int i, j;
83358   static const unsigned char iCode[] = {
83359     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
83360     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
83361     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
83362     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
83363     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
83364     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
83365     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
83366     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
83367   };
83368   assert( argc==1 );
83369   zIn = (u8*)sqlite3_value_text(argv[0]);
83370   if( zIn==0 ) zIn = (u8*)"";
83371   for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
83372   if( zIn[i] ){
83373     u8 prevcode = iCode[zIn[i]&0x7f];
83374     zResult[0] = sqlite3Toupper(zIn[i]);
83375     for(j=1; j<4 && zIn[i]; i++){
83376       int code = iCode[zIn[i]&0x7f];
83377       if( code>0 ){
83378         if( code!=prevcode ){
83379           prevcode = code;
83380           zResult[j++] = code + '0';
83381         }
83382       }else{
83383         prevcode = 0;
83384       }
83385     }
83386     while( j<4 ){
83387       zResult[j++] = '0';
83388     }
83389     zResult[j] = 0;
83390     sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
83391   }else{
83392     /* IMP: R-64894-50321 The string "?000" is returned if the argument
83393     ** is NULL or contains no ASCII alphabetic characters. */
83394     sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
83395   }
83396 }
83397 #endif /* SQLITE_SOUNDEX */
83398
83399 #ifndef SQLITE_OMIT_LOAD_EXTENSION
83400 /*
83401 ** A function that loads a shared-library extension then returns NULL.
83402 */
83403 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
83404   const char *zFile = (const char *)sqlite3_value_text(argv[0]);
83405   const char *zProc;
83406   sqlite3 *db = sqlite3_context_db_handle(context);
83407   char *zErrMsg = 0;
83408
83409   if( argc==2 ){
83410     zProc = (const char *)sqlite3_value_text(argv[1]);
83411   }else{
83412     zProc = 0;
83413   }
83414   if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
83415     sqlite3_result_error(context, zErrMsg, -1);
83416     sqlite3_free(zErrMsg);
83417   }
83418 }
83419 #endif
83420
83421
83422 /*
83423 ** An instance of the following structure holds the context of a
83424 ** sum() or avg() aggregate computation.
83425 */
83426 typedef struct SumCtx SumCtx;
83427 struct SumCtx {
83428   double rSum;      /* Floating point sum */
83429   i64 iSum;         /* Integer sum */   
83430   i64 cnt;          /* Number of elements summed */
83431   u8 overflow;      /* True if integer overflow seen */
83432   u8 approx;        /* True if non-integer value was input to the sum */
83433 };
83434
83435 /*
83436 ** Routines used to compute the sum, average, and total.
83437 **
83438 ** The SUM() function follows the (broken) SQL standard which means
83439 ** that it returns NULL if it sums over no inputs.  TOTAL returns
83440 ** 0.0 in that case.  In addition, TOTAL always returns a float where
83441 ** SUM might return an integer if it never encounters a floating point
83442 ** value.  TOTAL never fails, but SUM might through an exception if
83443 ** it overflows an integer.
83444 */
83445 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
83446   SumCtx *p;
83447   int type;
83448   assert( argc==1 );
83449   UNUSED_PARAMETER(argc);
83450   p = sqlite3_aggregate_context(context, sizeof(*p));
83451   type = sqlite3_value_numeric_type(argv[0]);
83452   if( p && type!=SQLITE_NULL ){
83453     p->cnt++;
83454     if( type==SQLITE_INTEGER ){
83455       i64 v = sqlite3_value_int64(argv[0]);
83456       p->rSum += v;
83457       if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
83458         p->overflow = 1;
83459       }
83460     }else{
83461       p->rSum += sqlite3_value_double(argv[0]);
83462       p->approx = 1;
83463     }
83464   }
83465 }
83466 static void sumFinalize(sqlite3_context *context){
83467   SumCtx *p;
83468   p = sqlite3_aggregate_context(context, 0);
83469   if( p && p->cnt>0 ){
83470     if( p->overflow ){
83471       sqlite3_result_error(context,"integer overflow",-1);
83472     }else if( p->approx ){
83473       sqlite3_result_double(context, p->rSum);
83474     }else{
83475       sqlite3_result_int64(context, p->iSum);
83476     }
83477   }
83478 }
83479 static void avgFinalize(sqlite3_context *context){
83480   SumCtx *p;
83481   p = sqlite3_aggregate_context(context, 0);
83482   if( p && p->cnt>0 ){
83483     sqlite3_result_double(context, p->rSum/(double)p->cnt);
83484   }
83485 }
83486 static void totalFinalize(sqlite3_context *context){
83487   SumCtx *p;
83488   p = sqlite3_aggregate_context(context, 0);
83489   /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
83490   sqlite3_result_double(context, p ? p->rSum : (double)0);
83491 }
83492
83493 /*
83494 ** The following structure keeps track of state information for the
83495 ** count() aggregate function.
83496 */
83497 typedef struct CountCtx CountCtx;
83498 struct CountCtx {
83499   i64 n;
83500 };
83501
83502 /*
83503 ** Routines to implement the count() aggregate function.
83504 */
83505 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
83506   CountCtx *p;
83507   p = sqlite3_aggregate_context(context, sizeof(*p));
83508   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
83509     p->n++;
83510   }
83511
83512 #ifndef SQLITE_OMIT_DEPRECATED
83513   /* The sqlite3_aggregate_count() function is deprecated.  But just to make
83514   ** sure it still operates correctly, verify that its count agrees with our 
83515   ** internal count when using count(*) and when the total count can be
83516   ** expressed as a 32-bit integer. */
83517   assert( argc==1 || p==0 || p->n>0x7fffffff
83518           || p->n==sqlite3_aggregate_count(context) );
83519 #endif
83520 }   
83521 static void countFinalize(sqlite3_context *context){
83522   CountCtx *p;
83523   p = sqlite3_aggregate_context(context, 0);
83524   sqlite3_result_int64(context, p ? p->n : 0);
83525 }
83526
83527 /*
83528 ** Routines to implement min() and max() aggregate functions.
83529 */
83530 static void minmaxStep(
83531   sqlite3_context *context, 
83532   int NotUsed, 
83533   sqlite3_value **argv
83534 ){
83535   Mem *pArg  = (Mem *)argv[0];
83536   Mem *pBest;
83537   UNUSED_PARAMETER(NotUsed);
83538
83539   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
83540   pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
83541   if( !pBest ) return;
83542
83543   if( pBest->flags ){
83544     int max;
83545     int cmp;
83546     CollSeq *pColl = sqlite3GetFuncCollSeq(context);
83547     /* This step function is used for both the min() and max() aggregates,
83548     ** the only difference between the two being that the sense of the
83549     ** comparison is inverted. For the max() aggregate, the
83550     ** sqlite3_user_data() function returns (void *)-1. For min() it
83551     ** returns (void *)db, where db is the sqlite3* database pointer.
83552     ** Therefore the next statement sets variable 'max' to 1 for the max()
83553     ** aggregate, or 0 for min().
83554     */
83555     max = sqlite3_user_data(context)!=0;
83556     cmp = sqlite3MemCompare(pBest, pArg, pColl);
83557     if( (max && cmp<0) || (!max && cmp>0) ){
83558       sqlite3VdbeMemCopy(pBest, pArg);
83559     }
83560   }else{
83561     sqlite3VdbeMemCopy(pBest, pArg);
83562   }
83563 }
83564 static void minMaxFinalize(sqlite3_context *context){
83565   sqlite3_value *pRes;
83566   pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
83567   if( pRes ){
83568     if( ALWAYS(pRes->flags) ){
83569       sqlite3_result_value(context, pRes);
83570     }
83571     sqlite3VdbeMemRelease(pRes);
83572   }
83573 }
83574
83575 /*
83576 ** group_concat(EXPR, ?SEPARATOR?)
83577 */
83578 static void groupConcatStep(
83579   sqlite3_context *context,
83580   int argc,
83581   sqlite3_value **argv
83582 ){
83583   const char *zVal;
83584   StrAccum *pAccum;
83585   const char *zSep;
83586   int nVal, nSep;
83587   assert( argc==1 || argc==2 );
83588   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
83589   pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
83590
83591   if( pAccum ){
83592     sqlite3 *db = sqlite3_context_db_handle(context);
83593     int firstTerm = pAccum->useMalloc==0;
83594     pAccum->useMalloc = 2;
83595     pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
83596     if( !firstTerm ){
83597       if( argc==2 ){
83598         zSep = (char*)sqlite3_value_text(argv[1]);
83599         nSep = sqlite3_value_bytes(argv[1]);
83600       }else{
83601         zSep = ",";
83602         nSep = 1;
83603       }
83604       sqlite3StrAccumAppend(pAccum, zSep, nSep);
83605     }
83606     zVal = (char*)sqlite3_value_text(argv[0]);
83607     nVal = sqlite3_value_bytes(argv[0]);
83608     sqlite3StrAccumAppend(pAccum, zVal, nVal);
83609   }
83610 }
83611 static void groupConcatFinalize(sqlite3_context *context){
83612   StrAccum *pAccum;
83613   pAccum = sqlite3_aggregate_context(context, 0);
83614   if( pAccum ){
83615     if( pAccum->tooBig ){
83616       sqlite3_result_error_toobig(context);
83617     }else if( pAccum->mallocFailed ){
83618       sqlite3_result_error_nomem(context);
83619     }else{    
83620       sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1, 
83621                           sqlite3_free);
83622     }
83623   }
83624 }
83625
83626 /*
83627 ** This routine does per-connection function registration.  Most
83628 ** of the built-in functions above are part of the global function set.
83629 ** This routine only deals with those that are not global.
83630 */
83631 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
83632   int rc = sqlite3_overload_function(db, "MATCH", 2);
83633   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
83634   if( rc==SQLITE_NOMEM ){
83635     db->mallocFailed = 1;
83636   }
83637 }
83638
83639 /*
83640 ** Set the LIKEOPT flag on the 2-argument function with the given name.
83641 */
83642 static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
83643   FuncDef *pDef;
83644   pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
83645                              2, SQLITE_UTF8, 0);
83646   if( ALWAYS(pDef) ){
83647     pDef->flags = flagVal;
83648   }
83649 }
83650
83651 /*
83652 ** Register the built-in LIKE and GLOB functions.  The caseSensitive
83653 ** parameter determines whether or not the LIKE operator is case
83654 ** sensitive.  GLOB is always case sensitive.
83655 */
83656 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
83657   struct compareInfo *pInfo;
83658   if( caseSensitive ){
83659     pInfo = (struct compareInfo*)&likeInfoAlt;
83660   }else{
83661     pInfo = (struct compareInfo*)&likeInfoNorm;
83662   }
83663   sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
83664   sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
83665   sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8, 
83666       (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
83667   setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
83668   setLikeOptFlag(db, "like", 
83669       caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
83670 }
83671
83672 /*
83673 ** pExpr points to an expression which implements a function.  If
83674 ** it is appropriate to apply the LIKE optimization to that function
83675 ** then set aWc[0] through aWc[2] to the wildcard characters and
83676 ** return TRUE.  If the function is not a LIKE-style function then
83677 ** return FALSE.
83678 */
83679 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
83680   FuncDef *pDef;
83681   if( pExpr->op!=TK_FUNCTION 
83682    || !pExpr->x.pList 
83683    || pExpr->x.pList->nExpr!=2
83684   ){
83685     return 0;
83686   }
83687   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
83688   pDef = sqlite3FindFunction(db, pExpr->u.zToken, 
83689                              sqlite3Strlen30(pExpr->u.zToken),
83690                              2, SQLITE_UTF8, 0);
83691   if( NEVER(pDef==0) || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
83692     return 0;
83693   }
83694
83695   /* The memcpy() statement assumes that the wildcard characters are
83696   ** the first three statements in the compareInfo structure.  The
83697   ** asserts() that follow verify that assumption
83698   */
83699   memcpy(aWc, pDef->pUserData, 3);
83700   assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
83701   assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
83702   assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
83703   *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
83704   return 1;
83705 }
83706
83707 /*
83708 ** All all of the FuncDef structures in the aBuiltinFunc[] array above
83709 ** to the global function hash table.  This occurs at start-time (as
83710 ** a consequence of calling sqlite3_initialize()).
83711 **
83712 ** After this routine runs
83713 */
83714 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
83715   /*
83716   ** The following array holds FuncDef structures for all of the functions
83717   ** defined in this file.
83718   **
83719   ** The array cannot be constant since changes are made to the
83720   ** FuncDef.pHash elements at start-time.  The elements of this array
83721   ** are read-only after initialization is complete.
83722   */
83723   static SQLITE_WSD FuncDef aBuiltinFunc[] = {
83724     FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
83725     FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
83726     FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
83727     FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
83728     FUNCTION(trim,               1, 3, 0, trimFunc         ),
83729     FUNCTION(trim,               2, 3, 0, trimFunc         ),
83730     FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
83731     FUNCTION(min,                0, 0, 1, 0                ),
83732     AGGREGATE(min,               1, 0, 1, minmaxStep,      minMaxFinalize ),
83733     FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
83734     FUNCTION(max,                0, 1, 1, 0                ),
83735     AGGREGATE(max,               1, 1, 1, minmaxStep,      minMaxFinalize ),
83736     FUNCTION(typeof,             1, 0, 0, typeofFunc       ),
83737     FUNCTION(length,             1, 0, 0, lengthFunc       ),
83738     FUNCTION(substr,             2, 0, 0, substrFunc       ),
83739     FUNCTION(substr,             3, 0, 0, substrFunc       ),
83740     FUNCTION(abs,                1, 0, 0, absFunc          ),
83741 #ifndef SQLITE_OMIT_FLOATING_POINT
83742     FUNCTION(round,              1, 0, 0, roundFunc        ),
83743     FUNCTION(round,              2, 0, 0, roundFunc        ),
83744 #endif
83745     FUNCTION(upper,              1, 0, 0, upperFunc        ),
83746     FUNCTION(lower,              1, 0, 0, lowerFunc        ),
83747     FUNCTION(coalesce,           1, 0, 0, 0                ),
83748     FUNCTION(coalesce,           0, 0, 0, 0                ),
83749 /*  FUNCTION(coalesce,          -1, 0, 0, ifnullFunc       ), */
83750     {-1,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"coalesce",0,0},
83751     FUNCTION(hex,                1, 0, 0, hexFunc          ),
83752 /*  FUNCTION(ifnull,             2, 0, 0, ifnullFunc       ), */
83753     {2,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"ifnull",0,0},
83754     FUNCTION(random,             0, 0, 0, randomFunc       ),
83755     FUNCTION(randomblob,         1, 0, 0, randomBlob       ),
83756     FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
83757     FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),
83758     FUNCTION(sqlite_source_id,   0, 0, 0, sourceidFunc     ),
83759     FUNCTION(sqlite_log,         2, 0, 0, errlogFunc       ),
83760 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
83761     FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
83762     FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
83763 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
83764     FUNCTION(quote,              1, 0, 0, quoteFunc        ),
83765     FUNCTION(last_insert_rowid,  0, 0, 0, last_insert_rowid),
83766     FUNCTION(changes,            0, 0, 0, changes          ),
83767     FUNCTION(total_changes,      0, 0, 0, total_changes    ),
83768     FUNCTION(replace,            3, 0, 0, replaceFunc      ),
83769     FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
83770   #ifdef SQLITE_SOUNDEX
83771     FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
83772   #endif
83773   #ifndef SQLITE_OMIT_LOAD_EXTENSION
83774     FUNCTION(load_extension,     1, 0, 0, loadExt          ),
83775     FUNCTION(load_extension,     2, 0, 0, loadExt          ),
83776   #endif
83777     AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
83778     AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
83779     AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
83780  /* AGGREGATE(count,             0, 0, 0, countStep,       countFinalize  ), */
83781     {0,SQLITE_UTF8,SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0,0},
83782     AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
83783     AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
83784     AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
83785   
83786     LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
83787   #ifdef SQLITE_CASE_SENSITIVE_LIKE
83788     LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
83789     LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
83790   #else
83791     LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
83792     LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
83793   #endif
83794   };
83795
83796   int i;
83797   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
83798   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
83799
83800   for(i=0; i<ArraySize(aBuiltinFunc); i++){
83801     sqlite3FuncDefInsert(pHash, &aFunc[i]);
83802   }
83803   sqlite3RegisterDateTimeFunctions();
83804 #ifndef SQLITE_OMIT_ALTERTABLE
83805   sqlite3AlterFunctions();
83806 #endif
83807 }
83808
83809 /************** End of func.c ************************************************/
83810 /************** Begin file fkey.c ********************************************/
83811 /*
83812 **
83813 ** The author disclaims copyright to this source code.  In place of
83814 ** a legal notice, here is a blessing:
83815 **
83816 **    May you do good and not evil.
83817 **    May you find forgiveness for yourself and forgive others.
83818 **    May you share freely, never taking more than you give.
83819 **
83820 *************************************************************************
83821 ** This file contains code used by the compiler to add foreign key
83822 ** support to compiled SQL statements.
83823 */
83824
83825 #ifndef SQLITE_OMIT_FOREIGN_KEY
83826 #ifndef SQLITE_OMIT_TRIGGER
83827
83828 /*
83829 ** Deferred and Immediate FKs
83830 ** --------------------------
83831 **
83832 ** Foreign keys in SQLite come in two flavours: deferred and immediate.
83833 ** If an immediate foreign key constraint is violated, SQLITE_CONSTRAINT
83834 ** is returned and the current statement transaction rolled back. If a 
83835 ** deferred foreign key constraint is violated, no action is taken 
83836 ** immediately. However if the application attempts to commit the 
83837 ** transaction before fixing the constraint violation, the attempt fails.
83838 **
83839 ** Deferred constraints are implemented using a simple counter associated
83840 ** with the database handle. The counter is set to zero each time a 
83841 ** database transaction is opened. Each time a statement is executed 
83842 ** that causes a foreign key violation, the counter is incremented. Each
83843 ** time a statement is executed that removes an existing violation from
83844 ** the database, the counter is decremented. When the transaction is
83845 ** committed, the commit fails if the current value of the counter is
83846 ** greater than zero. This scheme has two big drawbacks:
83847 **
83848 **   * When a commit fails due to a deferred foreign key constraint, 
83849 **     there is no way to tell which foreign constraint is not satisfied,
83850 **     or which row it is not satisfied for.
83851 **
83852 **   * If the database contains foreign key violations when the 
83853 **     transaction is opened, this may cause the mechanism to malfunction.
83854 **
83855 ** Despite these problems, this approach is adopted as it seems simpler
83856 ** than the alternatives.
83857 **
83858 ** INSERT operations:
83859 **
83860 **   I.1) For each FK for which the table is the child table, search
83861 **        the parent table for a match. If none is found increment the
83862 **        constraint counter.
83863 **
83864 **   I.2) For each FK for which the table is the parent table, 
83865 **        search the child table for rows that correspond to the new
83866 **        row in the parent table. Decrement the counter for each row
83867 **        found (as the constraint is now satisfied).
83868 **
83869 ** DELETE operations:
83870 **
83871 **   D.1) For each FK for which the table is the child table, 
83872 **        search the parent table for a row that corresponds to the 
83873 **        deleted row in the child table. If such a row is not found, 
83874 **        decrement the counter.
83875 **
83876 **   D.2) For each FK for which the table is the parent table, search 
83877 **        the child table for rows that correspond to the deleted row 
83878 **        in the parent table. For each found increment the counter.
83879 **
83880 ** UPDATE operations:
83881 **
83882 **   An UPDATE command requires that all 4 steps above are taken, but only
83883 **   for FK constraints for which the affected columns are actually 
83884 **   modified (values must be compared at runtime).
83885 **
83886 ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
83887 ** This simplifies the implementation a bit.
83888 **
83889 ** For the purposes of immediate FK constraints, the OR REPLACE conflict
83890 ** resolution is considered to delete rows before the new row is inserted.
83891 ** If a delete caused by OR REPLACE violates an FK constraint, an exception
83892 ** is thrown, even if the FK constraint would be satisfied after the new 
83893 ** row is inserted.
83894 **
83895 ** Immediate constraints are usually handled similarly. The only difference 
83896 ** is that the counter used is stored as part of each individual statement
83897 ** object (struct Vdbe). If, after the statement has run, its immediate
83898 ** constraint counter is greater than zero, it returns SQLITE_CONSTRAINT
83899 ** and the statement transaction is rolled back. An exception is an INSERT
83900 ** statement that inserts a single row only (no triggers). In this case,
83901 ** instead of using a counter, an exception is thrown immediately if the
83902 ** INSERT violates a foreign key constraint. This is necessary as such
83903 ** an INSERT does not open a statement transaction.
83904 **
83905 ** TODO: How should dropping a table be handled? How should renaming a 
83906 ** table be handled?
83907 **
83908 **
83909 ** Query API Notes
83910 ** ---------------
83911 **
83912 ** Before coding an UPDATE or DELETE row operation, the code-generator
83913 ** for those two operations needs to know whether or not the operation
83914 ** requires any FK processing and, if so, which columns of the original
83915 ** row are required by the FK processing VDBE code (i.e. if FKs were
83916 ** implemented using triggers, which of the old.* columns would be 
83917 ** accessed). No information is required by the code-generator before
83918 ** coding an INSERT operation. The functions used by the UPDATE/DELETE
83919 ** generation code to query for this information are:
83920 **
83921 **   sqlite3FkRequired() - Test to see if FK processing is required.
83922 **   sqlite3FkOldmask()  - Query for the set of required old.* columns.
83923 **
83924 **
83925 ** Externally accessible module functions
83926 ** --------------------------------------
83927 **
83928 **   sqlite3FkCheck()    - Check for foreign key violations.
83929 **   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
83930 **   sqlite3FkDelete()   - Delete an FKey structure.
83931 */
83932
83933 /*
83934 ** VDBE Calling Convention
83935 ** -----------------------
83936 **
83937 ** Example:
83938 **
83939 **   For the following INSERT statement:
83940 **
83941 **     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
83942 **     INSERT INTO t1 VALUES(1, 2, 3.1);
83943 **
83944 **   Register (x):        2    (type integer)
83945 **   Register (x+1):      1    (type integer)
83946 **   Register (x+2):      NULL (type NULL)
83947 **   Register (x+3):      3.1  (type real)
83948 */
83949
83950 /*
83951 ** A foreign key constraint requires that the key columns in the parent
83952 ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
83953 ** Given that pParent is the parent table for foreign key constraint pFKey, 
83954 ** search the schema a unique index on the parent key columns. 
83955 **
83956 ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY 
83957 ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx 
83958 ** is set to point to the unique index. 
83959 ** 
83960 ** If the parent key consists of a single column (the foreign key constraint
83961 ** is not a composite foreign key), output variable *paiCol is set to NULL.
83962 ** Otherwise, it is set to point to an allocated array of size N, where
83963 ** N is the number of columns in the parent key. The first element of the
83964 ** array is the index of the child table column that is mapped by the FK
83965 ** constraint to the parent table column stored in the left-most column
83966 ** of index *ppIdx. The second element of the array is the index of the
83967 ** child table column that corresponds to the second left-most column of
83968 ** *ppIdx, and so on.
83969 **
83970 ** If the required index cannot be found, either because:
83971 **
83972 **   1) The named parent key columns do not exist, or
83973 **
83974 **   2) The named parent key columns do exist, but are not subject to a
83975 **      UNIQUE or PRIMARY KEY constraint, or
83976 **
83977 **   3) No parent key columns were provided explicitly as part of the
83978 **      foreign key definition, and the parent table does not have a
83979 **      PRIMARY KEY, or
83980 **
83981 **   4) No parent key columns were provided explicitly as part of the
83982 **      foreign key definition, and the PRIMARY KEY of the parent table 
83983 **      consists of a a different number of columns to the child key in 
83984 **      the child table.
83985 **
83986 ** then non-zero is returned, and a "foreign key mismatch" error loaded
83987 ** into pParse. If an OOM error occurs, non-zero is returned and the
83988 ** pParse->db->mallocFailed flag is set.
83989 */
83990 static int locateFkeyIndex(
83991   Parse *pParse,                  /* Parse context to store any error in */
83992   Table *pParent,                 /* Parent table of FK constraint pFKey */
83993   FKey *pFKey,                    /* Foreign key to find index for */
83994   Index **ppIdx,                  /* OUT: Unique index on parent table */
83995   int **paiCol                    /* OUT: Map of index columns in pFKey */
83996 ){
83997   Index *pIdx = 0;                    /* Value to return via *ppIdx */
83998   int *aiCol = 0;                     /* Value to return via *paiCol */
83999   int nCol = pFKey->nCol;             /* Number of columns in parent key */
84000   char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
84001
84002   /* The caller is responsible for zeroing output parameters. */
84003   assert( ppIdx && *ppIdx==0 );
84004   assert( !paiCol || *paiCol==0 );
84005   assert( pParse );
84006
84007   /* If this is a non-composite (single column) foreign key, check if it 
84008   ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx 
84009   ** and *paiCol set to zero and return early. 
84010   **
84011   ** Otherwise, for a composite foreign key (more than one column), allocate
84012   ** space for the aiCol array (returned via output parameter *paiCol).
84013   ** Non-composite foreign keys do not require the aiCol array.
84014   */
84015   if( nCol==1 ){
84016     /* The FK maps to the IPK if any of the following are true:
84017     **
84018     **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly 
84019     **      mapped to the primary key of table pParent, or
84020     **   2) The FK is explicitly mapped to a column declared as INTEGER
84021     **      PRIMARY KEY.
84022     */
84023     if( pParent->iPKey>=0 ){
84024       if( !zKey ) return 0;
84025       if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
84026     }
84027   }else if( paiCol ){
84028     assert( nCol>1 );
84029     aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
84030     if( !aiCol ) return 1;
84031     *paiCol = aiCol;
84032   }
84033
84034   for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
84035     if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){ 
84036       /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
84037       ** of columns. If each indexed column corresponds to a foreign key
84038       ** column of pFKey, then this index is a winner.  */
84039
84040       if( zKey==0 ){
84041         /* If zKey is NULL, then this foreign key is implicitly mapped to 
84042         ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be 
84043         ** identified by the test (Index.autoIndex==2).  */
84044         if( pIdx->autoIndex==2 ){
84045           if( aiCol ){
84046             int i;
84047             for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
84048           }
84049           break;
84050         }
84051       }else{
84052         /* If zKey is non-NULL, then this foreign key was declared to
84053         ** map to an explicit list of columns in table pParent. Check if this
84054         ** index matches those columns. Also, check that the index uses
84055         ** the default collation sequences for each column. */
84056         int i, j;
84057         for(i=0; i<nCol; i++){
84058           int iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
84059           char *zDfltColl;                  /* Def. collation for column */
84060           char *zIdxCol;                    /* Name of indexed column */
84061
84062           /* If the index uses a collation sequence that is different from
84063           ** the default collation sequence for the column, this index is
84064           ** unusable. Bail out early in this case.  */
84065           zDfltColl = pParent->aCol[iCol].zColl;
84066           if( !zDfltColl ){
84067             zDfltColl = "BINARY";
84068           }
84069           if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
84070
84071           zIdxCol = pParent->aCol[iCol].zName;
84072           for(j=0; j<nCol; j++){
84073             if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
84074               if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
84075               break;
84076             }
84077           }
84078           if( j==nCol ) break;
84079         }
84080         if( i==nCol ) break;      /* pIdx is usable */
84081       }
84082     }
84083   }
84084
84085   if( !pIdx ){
84086     if( !pParse->disableTriggers ){
84087       sqlite3ErrorMsg(pParse, "foreign key mismatch");
84088     }
84089     sqlite3DbFree(pParse->db, aiCol);
84090     return 1;
84091   }
84092
84093   *ppIdx = pIdx;
84094   return 0;
84095 }
84096
84097 /*
84098 ** This function is called when a row is inserted into or deleted from the 
84099 ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed 
84100 ** on the child table of pFKey, this function is invoked twice for each row
84101 ** affected - once to "delete" the old row, and then again to "insert" the
84102 ** new row.
84103 **
84104 ** Each time it is called, this function generates VDBE code to locate the
84105 ** row in the parent table that corresponds to the row being inserted into 
84106 ** or deleted from the child table. If the parent row can be found, no 
84107 ** special action is taken. Otherwise, if the parent row can *not* be
84108 ** found in the parent table:
84109 **
84110 **   Operation | FK type   | Action taken
84111 **   --------------------------------------------------------------------------
84112 **   INSERT      immediate   Increment the "immediate constraint counter".
84113 **
84114 **   DELETE      immediate   Decrement the "immediate constraint counter".
84115 **
84116 **   INSERT      deferred    Increment the "deferred constraint counter".
84117 **
84118 **   DELETE      deferred    Decrement the "deferred constraint counter".
84119 **
84120 ** These operations are identified in the comment at the top of this file 
84121 ** (fkey.c) as "I.1" and "D.1".
84122 */
84123 static void fkLookupParent(
84124   Parse *pParse,        /* Parse context */
84125   int iDb,              /* Index of database housing pTab */
84126   Table *pTab,          /* Parent table of FK pFKey */
84127   Index *pIdx,          /* Unique index on parent key columns in pTab */
84128   FKey *pFKey,          /* Foreign key constraint */
84129   int *aiCol,           /* Map from parent key columns to child table columns */
84130   int regData,          /* Address of array containing child table row */
84131   int nIncr,            /* Increment constraint counter by this */
84132   int isIgnore          /* If true, pretend pTab contains all NULL values */
84133 ){
84134   int i;                                    /* Iterator variable */
84135   Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
84136   int iCur = pParse->nTab - 1;              /* Cursor number to use */
84137   int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */
84138
84139   /* If nIncr is less than zero, then check at runtime if there are any
84140   ** outstanding constraints to resolve. If there are not, there is no need
84141   ** to check if deleting this row resolves any outstanding violations.
84142   **
84143   ** Check if any of the key columns in the child table row are NULL. If 
84144   ** any are, then the constraint is considered satisfied. No need to 
84145   ** search for a matching row in the parent table.  */
84146   if( nIncr<0 ){
84147     sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
84148   }
84149   for(i=0; i<pFKey->nCol; i++){
84150     int iReg = aiCol[i] + regData + 1;
84151     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
84152   }
84153
84154   if( isIgnore==0 ){
84155     if( pIdx==0 ){
84156       /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
84157       ** column of the parent table (table pTab).  */
84158       int iMustBeInt;               /* Address of MustBeInt instruction */
84159       int regTemp = sqlite3GetTempReg(pParse);
84160   
84161       /* Invoke MustBeInt to coerce the child key value to an integer (i.e. 
84162       ** apply the affinity of the parent key). If this fails, then there
84163       ** is no matching parent key. Before using MustBeInt, make a copy of
84164       ** the value. Otherwise, the value inserted into the child key column
84165       ** will have INTEGER affinity applied to it, which may not be correct.  */
84166       sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
84167       iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
84168   
84169       /* If the parent table is the same as the child table, and we are about
84170       ** to increment the constraint-counter (i.e. this is an INSERT operation),
84171       ** then check if the row being inserted matches itself. If so, do not
84172       ** increment the constraint-counter.  */
84173       if( pTab==pFKey->pFrom && nIncr==1 ){
84174         sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
84175       }
84176   
84177       sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
84178       sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
84179       sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
84180       sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
84181       sqlite3VdbeJumpHere(v, iMustBeInt);
84182       sqlite3ReleaseTempReg(pParse, regTemp);
84183     }else{
84184       int nCol = pFKey->nCol;
84185       int regTemp = sqlite3GetTempRange(pParse, nCol);
84186       int regRec = sqlite3GetTempReg(pParse);
84187       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
84188   
84189       sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
84190       sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
84191       for(i=0; i<nCol; i++){
84192         sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
84193       }
84194   
84195       /* If the parent table is the same as the child table, and we are about
84196       ** to increment the constraint-counter (i.e. this is an INSERT operation),
84197       ** then check if the row being inserted matches itself. If so, do not
84198       ** increment the constraint-counter. 
84199       **
84200       ** If any of the parent-key values are NULL, then the row cannot match 
84201       ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
84202       ** of the parent-key values are NULL (at this point it is known that
84203       ** none of the child key values are).
84204       */
84205       if( pTab==pFKey->pFrom && nIncr==1 ){
84206         int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
84207         for(i=0; i<nCol; i++){
84208           int iChild = aiCol[i]+1+regData;
84209           int iParent = pIdx->aiColumn[i]+1+regData;
84210           assert( aiCol[i]!=pTab->iPKey );
84211           if( pIdx->aiColumn[i]==pTab->iPKey ){
84212             /* The parent key is a composite key that includes the IPK column */
84213             iParent = regData;
84214           }
84215           sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
84216           sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
84217         }
84218         sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
84219       }
84220   
84221       sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
84222       sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT);
84223       sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);
84224   
84225       sqlite3ReleaseTempReg(pParse, regRec);
84226       sqlite3ReleaseTempRange(pParse, regTemp, nCol);
84227     }
84228   }
84229
84230   if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
84231     /* Special case: If this is an INSERT statement that will insert exactly
84232     ** one row into the table, raise a constraint immediately instead of
84233     ** incrementing a counter. This is necessary as the VM code is being
84234     ** generated for will not open a statement transaction.  */
84235     assert( nIncr==1 );
84236     sqlite3HaltConstraint(
84237         pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
84238     );
84239   }else{
84240     if( nIncr>0 && pFKey->isDeferred==0 ){
84241       sqlite3ParseToplevel(pParse)->mayAbort = 1;
84242     }
84243     sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
84244   }
84245
84246   sqlite3VdbeResolveLabel(v, iOk);
84247   sqlite3VdbeAddOp1(v, OP_Close, iCur);
84248 }
84249
84250 /*
84251 ** This function is called to generate code executed when a row is deleted
84252 ** from the parent table of foreign key constraint pFKey and, if pFKey is 
84253 ** deferred, when a row is inserted into the same table. When generating
84254 ** code for an SQL UPDATE operation, this function may be called twice -
84255 ** once to "delete" the old row and once to "insert" the new row.
84256 **
84257 ** The code generated by this function scans through the rows in the child
84258 ** table that correspond to the parent table row being deleted or inserted.
84259 ** For each child row found, one of the following actions is taken:
84260 **
84261 **   Operation | FK type   | Action taken
84262 **   --------------------------------------------------------------------------
84263 **   DELETE      immediate   Increment the "immediate constraint counter".
84264 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
84265 **                           throw a "foreign key constraint failed" exception.
84266 **
84267 **   INSERT      immediate   Decrement the "immediate constraint counter".
84268 **
84269 **   DELETE      deferred    Increment the "deferred constraint counter".
84270 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
84271 **                           throw a "foreign key constraint failed" exception.
84272 **
84273 **   INSERT      deferred    Decrement the "deferred constraint counter".
84274 **
84275 ** These operations are identified in the comment at the top of this file 
84276 ** (fkey.c) as "I.2" and "D.2".
84277 */
84278 static void fkScanChildren(
84279   Parse *pParse,                  /* Parse context */
84280   SrcList *pSrc,                  /* SrcList containing the table to scan */
84281   Table *pTab,
84282   Index *pIdx,                    /* Foreign key index */
84283   FKey *pFKey,                    /* Foreign key relationship */
84284   int *aiCol,                     /* Map from pIdx cols to child table cols */
84285   int regData,                    /* Referenced table data starts here */
84286   int nIncr                       /* Amount to increment deferred counter by */
84287 ){
84288   sqlite3 *db = pParse->db;       /* Database handle */
84289   int i;                          /* Iterator variable */
84290   Expr *pWhere = 0;               /* WHERE clause to scan with */
84291   NameContext sNameContext;       /* Context used to resolve WHERE clause */
84292   WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
84293   int iFkIfZero = 0;              /* Address of OP_FkIfZero */
84294   Vdbe *v = sqlite3GetVdbe(pParse);
84295
84296   assert( !pIdx || pIdx->pTable==pTab );
84297
84298   if( nIncr<0 ){
84299     iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
84300   }
84301
84302   /* Create an Expr object representing an SQL expression like:
84303   **
84304   **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
84305   **
84306   ** The collation sequence used for the comparison should be that of
84307   ** the parent key columns. The affinity of the parent key column should
84308   ** be applied to each child key value before the comparison takes place.
84309   */
84310   for(i=0; i<pFKey->nCol; i++){
84311     Expr *pLeft;                  /* Value from parent table row */
84312     Expr *pRight;                 /* Column ref to child table */
84313     Expr *pEq;                    /* Expression (pLeft = pRight) */
84314     int iCol;                     /* Index of column in child table */ 
84315     const char *zCol;             /* Name of column in child table */
84316
84317     pLeft = sqlite3Expr(db, TK_REGISTER, 0);
84318     if( pLeft ){
84319       /* Set the collation sequence and affinity of the LHS of each TK_EQ
84320       ** expression to the parent key column defaults.  */
84321       if( pIdx ){
84322         Column *pCol;
84323         iCol = pIdx->aiColumn[i];
84324         pCol = &pTab->aCol[iCol];
84325         if( pTab->iPKey==iCol ) iCol = -1;
84326         pLeft->iTable = regData+iCol+1;
84327         pLeft->affinity = pCol->affinity;
84328         pLeft->pColl = sqlite3LocateCollSeq(pParse, pCol->zColl);
84329       }else{
84330         pLeft->iTable = regData;
84331         pLeft->affinity = SQLITE_AFF_INTEGER;
84332       }
84333     }
84334     iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
84335     assert( iCol>=0 );
84336     zCol = pFKey->pFrom->aCol[iCol].zName;
84337     pRight = sqlite3Expr(db, TK_ID, zCol);
84338     pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
84339     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
84340   }
84341
84342   /* If the child table is the same as the parent table, and this scan
84343   ** is taking place as part of a DELETE operation (operation D.2), omit the
84344   ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE 
84345   ** clause, where $rowid is the rowid of the row being deleted.  */
84346   if( pTab==pFKey->pFrom && nIncr>0 ){
84347     Expr *pEq;                    /* Expression (pLeft = pRight) */
84348     Expr *pLeft;                  /* Value from parent table row */
84349     Expr *pRight;                 /* Column ref to child table */
84350     pLeft = sqlite3Expr(db, TK_REGISTER, 0);
84351     pRight = sqlite3Expr(db, TK_COLUMN, 0);
84352     if( pLeft && pRight ){
84353       pLeft->iTable = regData;
84354       pLeft->affinity = SQLITE_AFF_INTEGER;
84355       pRight->iTable = pSrc->a[0].iCursor;
84356       pRight->iColumn = -1;
84357     }
84358     pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
84359     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
84360   }
84361
84362   /* Resolve the references in the WHERE clause. */
84363   memset(&sNameContext, 0, sizeof(NameContext));
84364   sNameContext.pSrcList = pSrc;
84365   sNameContext.pParse = pParse;
84366   sqlite3ResolveExprNames(&sNameContext, pWhere);
84367
84368   /* Create VDBE to loop through the entries in pSrc that match the WHERE
84369   ** clause. If the constraint is not deferred, throw an exception for
84370   ** each row found. Otherwise, for deferred constraints, increment the
84371   ** deferred constraint counter by nIncr for each row selected.  */
84372   pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0);
84373   if( nIncr>0 && pFKey->isDeferred==0 ){
84374     sqlite3ParseToplevel(pParse)->mayAbort = 1;
84375   }
84376   sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
84377   if( pWInfo ){
84378     sqlite3WhereEnd(pWInfo);
84379   }
84380
84381   /* Clean up the WHERE clause constructed above. */
84382   sqlite3ExprDelete(db, pWhere);
84383   if( iFkIfZero ){
84384     sqlite3VdbeJumpHere(v, iFkIfZero);
84385   }
84386 }
84387
84388 /*
84389 ** This function returns a pointer to the head of a linked list of FK
84390 ** constraints for which table pTab is the parent table. For example,
84391 ** given the following schema:
84392 **
84393 **   CREATE TABLE t1(a PRIMARY KEY);
84394 **   CREATE TABLE t2(b REFERENCES t1(a);
84395 **
84396 ** Calling this function with table "t1" as an argument returns a pointer
84397 ** to the FKey structure representing the foreign key constraint on table
84398 ** "t2". Calling this function with "t2" as the argument would return a
84399 ** NULL pointer (as there are no FK constraints for which t2 is the parent
84400 ** table).
84401 */
84402 SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
84403   int nName = sqlite3Strlen30(pTab->zName);
84404   return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
84405 }
84406
84407 /*
84408 ** The second argument is a Trigger structure allocated by the 
84409 ** fkActionTrigger() routine. This function deletes the Trigger structure
84410 ** and all of its sub-components.
84411 **
84412 ** The Trigger structure or any of its sub-components may be allocated from
84413 ** the lookaside buffer belonging to database handle dbMem.
84414 */
84415 static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
84416   if( p ){
84417     TriggerStep *pStep = p->step_list;
84418     sqlite3ExprDelete(dbMem, pStep->pWhere);
84419     sqlite3ExprListDelete(dbMem, pStep->pExprList);
84420     sqlite3SelectDelete(dbMem, pStep->pSelect);
84421     sqlite3ExprDelete(dbMem, p->pWhen);
84422     sqlite3DbFree(dbMem, p);
84423   }
84424 }
84425
84426 /*
84427 ** This function is called to generate code that runs when table pTab is
84428 ** being dropped from the database. The SrcList passed as the second argument
84429 ** to this function contains a single entry guaranteed to resolve to
84430 ** table pTab.
84431 **
84432 ** Normally, no code is required. However, if either
84433 **
84434 **   (a) The table is the parent table of a FK constraint, or
84435 **   (b) The table is the child table of a deferred FK constraint and it is
84436 **       determined at runtime that there are outstanding deferred FK 
84437 **       constraint violations in the database,
84438 **
84439 ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
84440 ** the table from the database. Triggers are disabled while running this
84441 ** DELETE, but foreign key actions are not.
84442 */
84443 SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
84444   sqlite3 *db = pParse->db;
84445   if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
84446     int iSkip = 0;
84447     Vdbe *v = sqlite3GetVdbe(pParse);
84448
84449     assert( v );                  /* VDBE has already been allocated */
84450     if( sqlite3FkReferences(pTab)==0 ){
84451       /* Search for a deferred foreign key constraint for which this table
84452       ** is the child table. If one cannot be found, return without 
84453       ** generating any VDBE code. If one can be found, then jump over
84454       ** the entire DELETE if there are no outstanding deferred constraints
84455       ** when this statement is run.  */
84456       FKey *p;
84457       for(p=pTab->pFKey; p; p=p->pNextFrom){
84458         if( p->isDeferred ) break;
84459       }
84460       if( !p ) return;
84461       iSkip = sqlite3VdbeMakeLabel(v);
84462       sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
84463     }
84464
84465     pParse->disableTriggers = 1;
84466     sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
84467     pParse->disableTriggers = 0;
84468
84469     /* If the DELETE has generated immediate foreign key constraint 
84470     ** violations, halt the VDBE and return an error at this point, before
84471     ** any modifications to the schema are made. This is because statement
84472     ** transactions are not able to rollback schema changes.  */
84473     sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
84474     sqlite3HaltConstraint(
84475         pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
84476     );
84477
84478     if( iSkip ){
84479       sqlite3VdbeResolveLabel(v, iSkip);
84480     }
84481   }
84482 }
84483
84484 /*
84485 ** This function is called when inserting, deleting or updating a row of
84486 ** table pTab to generate VDBE code to perform foreign key constraint 
84487 ** processing for the operation.
84488 **
84489 ** For a DELETE operation, parameter regOld is passed the index of the
84490 ** first register in an array of (pTab->nCol+1) registers containing the
84491 ** rowid of the row being deleted, followed by each of the column values
84492 ** of the row being deleted, from left to right. Parameter regNew is passed
84493 ** zero in this case.
84494 **
84495 ** For an INSERT operation, regOld is passed zero and regNew is passed the
84496 ** first register of an array of (pTab->nCol+1) registers containing the new
84497 ** row data.
84498 **
84499 ** For an UPDATE operation, this function is called twice. Once before
84500 ** the original record is deleted from the table using the calling convention
84501 ** described for DELETE. Then again after the original record is deleted
84502 ** but before the new record is inserted using the INSERT convention. 
84503 */
84504 SQLITE_PRIVATE void sqlite3FkCheck(
84505   Parse *pParse,                  /* Parse context */
84506   Table *pTab,                    /* Row is being deleted from this table */ 
84507   int regOld,                     /* Previous row data is stored here */
84508   int regNew                      /* New row data is stored here */
84509 ){
84510   sqlite3 *db = pParse->db;       /* Database handle */
84511   FKey *pFKey;                    /* Used to iterate through FKs */
84512   int iDb;                        /* Index of database containing pTab */
84513   const char *zDb;                /* Name of database containing pTab */
84514   int isIgnoreErrors = pParse->disableTriggers;
84515
84516   /* Exactly one of regOld and regNew should be non-zero. */
84517   assert( (regOld==0)!=(regNew==0) );
84518
84519   /* If foreign-keys are disabled, this function is a no-op. */
84520   if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
84521
84522   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
84523   zDb = db->aDb[iDb].zName;
84524
84525   /* Loop through all the foreign key constraints for which pTab is the
84526   ** child table (the table that the foreign key definition is part of).  */
84527   for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
84528     Table *pTo;                   /* Parent table of foreign key pFKey */
84529     Index *pIdx = 0;              /* Index on key columns in pTo */
84530     int *aiFree = 0;
84531     int *aiCol;
84532     int iCol;
84533     int i;
84534     int isIgnore = 0;
84535
84536     /* Find the parent table of this foreign key. Also find a unique index 
84537     ** on the parent key columns in the parent table. If either of these 
84538     ** schema items cannot be located, set an error in pParse and return 
84539     ** early.  */
84540     if( pParse->disableTriggers ){
84541       pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
84542     }else{
84543       pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
84544     }
84545     if( !pTo || locateFkeyIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
84546       if( !isIgnoreErrors || db->mallocFailed ) return;
84547       continue;
84548     }
84549     assert( pFKey->nCol==1 || (aiFree && pIdx) );
84550
84551     if( aiFree ){
84552       aiCol = aiFree;
84553     }else{
84554       iCol = pFKey->aCol[0].iFrom;
84555       aiCol = &iCol;
84556     }
84557     for(i=0; i<pFKey->nCol; i++){
84558       if( aiCol[i]==pTab->iPKey ){
84559         aiCol[i] = -1;
84560       }
84561 #ifndef SQLITE_OMIT_AUTHORIZATION
84562       /* Request permission to read the parent key columns. If the 
84563       ** authorization callback returns SQLITE_IGNORE, behave as if any
84564       ** values read from the parent table are NULL. */
84565       if( db->xAuth ){
84566         int rcauth;
84567         char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
84568         rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
84569         isIgnore = (rcauth==SQLITE_IGNORE);
84570       }
84571 #endif
84572     }
84573
84574     /* Take a shared-cache advisory read-lock on the parent table. Allocate 
84575     ** a cursor to use to search the unique index on the parent key columns 
84576     ** in the parent table.  */
84577     sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
84578     pParse->nTab++;
84579
84580     if( regOld!=0 ){
84581       /* A row is being removed from the child table. Search for the parent.
84582       ** If the parent does not exist, removing the child row resolves an 
84583       ** outstanding foreign key constraint violation. */
84584       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
84585     }
84586     if( regNew!=0 ){
84587       /* A row is being added to the child table. If a parent row cannot
84588       ** be found, adding the child row has violated the FK constraint. */ 
84589       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
84590     }
84591
84592     sqlite3DbFree(db, aiFree);
84593   }
84594
84595   /* Loop through all the foreign key constraints that refer to this table */
84596   for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
84597     Index *pIdx = 0;              /* Foreign key index for pFKey */
84598     SrcList *pSrc;
84599     int *aiCol = 0;
84600
84601     if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
84602       assert( regOld==0 && regNew!=0 );
84603       /* Inserting a single row into a parent table cannot cause an immediate
84604       ** foreign key violation. So do nothing in this case.  */
84605       continue;
84606     }
84607
84608     if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
84609       if( !isIgnoreErrors || db->mallocFailed ) return;
84610       continue;
84611     }
84612     assert( aiCol || pFKey->nCol==1 );
84613
84614     /* Create a SrcList structure containing a single table (the table 
84615     ** the foreign key that refers to this table is attached to). This
84616     ** is required for the sqlite3WhereXXX() interface.  */
84617     pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
84618     if( pSrc ){
84619       struct SrcList_item *pItem = pSrc->a;
84620       pItem->pTab = pFKey->pFrom;
84621       pItem->zName = pFKey->pFrom->zName;
84622       pItem->pTab->nRef++;
84623       pItem->iCursor = pParse->nTab++;
84624   
84625       if( regNew!=0 ){
84626         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
84627       }
84628       if( regOld!=0 ){
84629         /* If there is a RESTRICT action configured for the current operation
84630         ** on the parent table of this FK, then throw an exception 
84631         ** immediately if the FK constraint is violated, even if this is a
84632         ** deferred trigger. That's what RESTRICT means. To defer checking
84633         ** the constraint, the FK should specify NO ACTION (represented
84634         ** using OE_None). NO ACTION is the default.  */
84635         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
84636       }
84637       pItem->zName = 0;
84638       sqlite3SrcListDelete(db, pSrc);
84639     }
84640     sqlite3DbFree(db, aiCol);
84641   }
84642 }
84643
84644 #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
84645
84646 /*
84647 ** This function is called before generating code to update or delete a 
84648 ** row contained in table pTab.
84649 */
84650 SQLITE_PRIVATE u32 sqlite3FkOldmask(
84651   Parse *pParse,                  /* Parse context */
84652   Table *pTab                     /* Table being modified */
84653 ){
84654   u32 mask = 0;
84655   if( pParse->db->flags&SQLITE_ForeignKeys ){
84656     FKey *p;
84657     int i;
84658     for(p=pTab->pFKey; p; p=p->pNextFrom){
84659       for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
84660     }
84661     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
84662       Index *pIdx = 0;
84663       locateFkeyIndex(pParse, pTab, p, &pIdx, 0);
84664       if( pIdx ){
84665         for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
84666       }
84667     }
84668   }
84669   return mask;
84670 }
84671
84672 /*
84673 ** This function is called before generating code to update or delete a 
84674 ** row contained in table pTab. If the operation is a DELETE, then
84675 ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
84676 ** to an array of size N, where N is the number of columns in table pTab.
84677 ** If the i'th column is not modified by the UPDATE, then the corresponding 
84678 ** entry in the aChange[] array is set to -1. If the column is modified,
84679 ** the value is 0 or greater. Parameter chngRowid is set to true if the
84680 ** UPDATE statement modifies the rowid fields of the table.
84681 **
84682 ** If any foreign key processing will be required, this function returns
84683 ** true. If there is no foreign key related processing, this function 
84684 ** returns false.
84685 */
84686 SQLITE_PRIVATE int sqlite3FkRequired(
84687   Parse *pParse,                  /* Parse context */
84688   Table *pTab,                    /* Table being modified */
84689   int *aChange,                   /* Non-NULL for UPDATE operations */
84690   int chngRowid                   /* True for UPDATE that affects rowid */
84691 ){
84692   if( pParse->db->flags&SQLITE_ForeignKeys ){
84693     if( !aChange ){
84694       /* A DELETE operation. Foreign key processing is required if the 
84695       ** table in question is either the child or parent table for any 
84696       ** foreign key constraint.  */
84697       return (sqlite3FkReferences(pTab) || pTab->pFKey);
84698     }else{
84699       /* This is an UPDATE. Foreign key processing is only required if the
84700       ** operation modifies one or more child or parent key columns. */
84701       int i;
84702       FKey *p;
84703
84704       /* Check if any child key columns are being modified. */
84705       for(p=pTab->pFKey; p; p=p->pNextFrom){
84706         for(i=0; i<p->nCol; i++){
84707           int iChildKey = p->aCol[i].iFrom;
84708           if( aChange[iChildKey]>=0 ) return 1;
84709           if( iChildKey==pTab->iPKey && chngRowid ) return 1;
84710         }
84711       }
84712
84713       /* Check if any parent key columns are being modified. */
84714       for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
84715         for(i=0; i<p->nCol; i++){
84716           char *zKey = p->aCol[i].zCol;
84717           int iKey;
84718           for(iKey=0; iKey<pTab->nCol; iKey++){
84719             Column *pCol = &pTab->aCol[iKey];
84720             if( (zKey ? !sqlite3StrICmp(pCol->zName, zKey) : pCol->isPrimKey) ){
84721               if( aChange[iKey]>=0 ) return 1;
84722               if( iKey==pTab->iPKey && chngRowid ) return 1;
84723             }
84724           }
84725         }
84726       }
84727     }
84728   }
84729   return 0;
84730 }
84731
84732 /*
84733 ** This function is called when an UPDATE or DELETE operation is being 
84734 ** compiled on table pTab, which is the parent table of foreign-key pFKey.
84735 ** If the current operation is an UPDATE, then the pChanges parameter is
84736 ** passed a pointer to the list of columns being modified. If it is a
84737 ** DELETE, pChanges is passed a NULL pointer.
84738 **
84739 ** It returns a pointer to a Trigger structure containing a trigger
84740 ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
84741 ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
84742 ** returned (these actions require no special handling by the triggers
84743 ** sub-system, code for them is created by fkScanChildren()).
84744 **
84745 ** For example, if pFKey is the foreign key and pTab is table "p" in 
84746 ** the following schema:
84747 **
84748 **   CREATE TABLE p(pk PRIMARY KEY);
84749 **   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
84750 **
84751 ** then the returned trigger structure is equivalent to:
84752 **
84753 **   CREATE TRIGGER ... DELETE ON p BEGIN
84754 **     DELETE FROM c WHERE ck = old.pk;
84755 **   END;
84756 **
84757 ** The returned pointer is cached as part of the foreign key object. It
84758 ** is eventually freed along with the rest of the foreign key object by 
84759 ** sqlite3FkDelete().
84760 */
84761 static Trigger *fkActionTrigger(
84762   Parse *pParse,                  /* Parse context */
84763   Table *pTab,                    /* Table being updated or deleted from */
84764   FKey *pFKey,                    /* Foreign key to get action for */
84765   ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
84766 ){
84767   sqlite3 *db = pParse->db;       /* Database handle */
84768   int action;                     /* One of OE_None, OE_Cascade etc. */
84769   Trigger *pTrigger;              /* Trigger definition to return */
84770   int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
84771
84772   action = pFKey->aAction[iAction];
84773   pTrigger = pFKey->apTrigger[iAction];
84774
84775   if( action!=OE_None && !pTrigger ){
84776     u8 enableLookaside;           /* Copy of db->lookaside.bEnabled */
84777     char const *zFrom;            /* Name of child table */
84778     int nFrom;                    /* Length in bytes of zFrom */
84779     Index *pIdx = 0;              /* Parent key index for this FK */
84780     int *aiCol = 0;               /* child table cols -> parent key cols */
84781     TriggerStep *pStep = 0;        /* First (only) step of trigger program */
84782     Expr *pWhere = 0;             /* WHERE clause of trigger step */
84783     ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
84784     Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
84785     int i;                        /* Iterator variable */
84786     Expr *pWhen = 0;              /* WHEN clause for the trigger */
84787
84788     if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
84789     assert( aiCol || pFKey->nCol==1 );
84790
84791     for(i=0; i<pFKey->nCol; i++){
84792       Token tOld = { "old", 3 };  /* Literal "old" token */
84793       Token tNew = { "new", 3 };  /* Literal "new" token */
84794       Token tFromCol;             /* Name of column in child table */
84795       Token tToCol;               /* Name of column in parent table */
84796       int iFromCol;               /* Idx of column in child table */
84797       Expr *pEq;                  /* tFromCol = OLD.tToCol */
84798
84799       iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
84800       assert( iFromCol>=0 );
84801       tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
84802       tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
84803
84804       tToCol.n = sqlite3Strlen30(tToCol.z);
84805       tFromCol.n = sqlite3Strlen30(tFromCol.z);
84806
84807       /* Create the expression "OLD.zToCol = zFromCol". It is important
84808       ** that the "OLD.zToCol" term is on the LHS of the = operator, so
84809       ** that the affinity and collation sequence associated with the
84810       ** parent table are used for the comparison. */
84811       pEq = sqlite3PExpr(pParse, TK_EQ,
84812           sqlite3PExpr(pParse, TK_DOT, 
84813             sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
84814             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
84815           , 0),
84816           sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
84817       , 0);
84818       pWhere = sqlite3ExprAnd(db, pWhere, pEq);
84819
84820       /* For ON UPDATE, construct the next term of the WHEN clause.
84821       ** The final WHEN clause will be like this:
84822       **
84823       **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
84824       */
84825       if( pChanges ){
84826         pEq = sqlite3PExpr(pParse, TK_IS,
84827             sqlite3PExpr(pParse, TK_DOT, 
84828               sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
84829               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
84830               0),
84831             sqlite3PExpr(pParse, TK_DOT, 
84832               sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
84833               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
84834               0),
84835             0);
84836         pWhen = sqlite3ExprAnd(db, pWhen, pEq);
84837       }
84838   
84839       if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
84840         Expr *pNew;
84841         if( action==OE_Cascade ){
84842           pNew = sqlite3PExpr(pParse, TK_DOT, 
84843             sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
84844             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
84845           , 0);
84846         }else if( action==OE_SetDflt ){
84847           Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
84848           if( pDflt ){
84849             pNew = sqlite3ExprDup(db, pDflt, 0);
84850           }else{
84851             pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
84852           }
84853         }else{
84854           pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
84855         }
84856         pList = sqlite3ExprListAppend(pParse, pList, pNew);
84857         sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
84858       }
84859     }
84860     sqlite3DbFree(db, aiCol);
84861
84862     zFrom = pFKey->pFrom->zName;
84863     nFrom = sqlite3Strlen30(zFrom);
84864
84865     if( action==OE_Restrict ){
84866       Token tFrom;
84867       Expr *pRaise; 
84868
84869       tFrom.z = zFrom;
84870       tFrom.n = nFrom;
84871       pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed");
84872       if( pRaise ){
84873         pRaise->affinity = OE_Abort;
84874       }
84875       pSelect = sqlite3SelectNew(pParse, 
84876           sqlite3ExprListAppend(pParse, 0, pRaise),
84877           sqlite3SrcListAppend(db, 0, &tFrom, 0),
84878           pWhere,
84879           0, 0, 0, 0, 0, 0
84880       );
84881       pWhere = 0;
84882     }
84883
84884     /* Disable lookaside memory allocation */
84885     enableLookaside = db->lookaside.bEnabled;
84886     db->lookaside.bEnabled = 0;
84887
84888     pTrigger = (Trigger *)sqlite3DbMallocZero(db, 
84889         sizeof(Trigger) +         /* struct Trigger */
84890         sizeof(TriggerStep) +     /* Single step in trigger program */
84891         nFrom + 1                 /* Space for pStep->target.z */
84892     );
84893     if( pTrigger ){
84894       pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
84895       pStep->target.z = (char *)&pStep[1];
84896       pStep->target.n = nFrom;
84897       memcpy((char *)pStep->target.z, zFrom, nFrom);
84898   
84899       pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
84900       pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
84901       pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
84902       if( pWhen ){
84903         pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
84904         pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
84905       }
84906     }
84907
84908     /* Re-enable the lookaside buffer, if it was disabled earlier. */
84909     db->lookaside.bEnabled = enableLookaside;
84910
84911     sqlite3ExprDelete(db, pWhere);
84912     sqlite3ExprDelete(db, pWhen);
84913     sqlite3ExprListDelete(db, pList);
84914     sqlite3SelectDelete(db, pSelect);
84915     if( db->mallocFailed==1 ){
84916       fkTriggerDelete(db, pTrigger);
84917       return 0;
84918     }
84919
84920     switch( action ){
84921       case OE_Restrict:
84922         pStep->op = TK_SELECT; 
84923         break;
84924       case OE_Cascade: 
84925         if( !pChanges ){ 
84926           pStep->op = TK_DELETE; 
84927           break; 
84928         }
84929       default:
84930         pStep->op = TK_UPDATE;
84931     }
84932     pStep->pTrig = pTrigger;
84933     pTrigger->pSchema = pTab->pSchema;
84934     pTrigger->pTabSchema = pTab->pSchema;
84935     pFKey->apTrigger[iAction] = pTrigger;
84936     pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
84937   }
84938
84939   return pTrigger;
84940 }
84941
84942 /*
84943 ** This function is called when deleting or updating a row to implement
84944 ** any required CASCADE, SET NULL or SET DEFAULT actions.
84945 */
84946 SQLITE_PRIVATE void sqlite3FkActions(
84947   Parse *pParse,                  /* Parse context */
84948   Table *pTab,                    /* Table being updated or deleted from */
84949   ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
84950   int regOld                      /* Address of array containing old row */
84951 ){
84952   /* If foreign-key support is enabled, iterate through all FKs that 
84953   ** refer to table pTab. If there is an action associated with the FK 
84954   ** for this operation (either update or delete), invoke the associated 
84955   ** trigger sub-program.  */
84956   if( pParse->db->flags&SQLITE_ForeignKeys ){
84957     FKey *pFKey;                  /* Iterator variable */
84958     for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
84959       Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);
84960       if( pAction ){
84961         sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);
84962       }
84963     }
84964   }
84965 }
84966
84967 #endif /* ifndef SQLITE_OMIT_TRIGGER */
84968
84969 /*
84970 ** Free all memory associated with foreign key definitions attached to
84971 ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
84972 ** hash table.
84973 */
84974 SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
84975   FKey *pFKey;                    /* Iterator variable */
84976   FKey *pNext;                    /* Copy of pFKey->pNextFrom */
84977
84978   assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
84979   for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
84980
84981     /* Remove the FK from the fkeyHash hash table. */
84982     if( !db || db->pnBytesFreed==0 ){
84983       if( pFKey->pPrevTo ){
84984         pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
84985       }else{
84986         void *p = (void *)pFKey->pNextTo;
84987         const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
84988         sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), p);
84989       }
84990       if( pFKey->pNextTo ){
84991         pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
84992       }
84993     }
84994
84995     /* EV: R-30323-21917 Each foreign key constraint in SQLite is
84996     ** classified as either immediate or deferred.
84997     */
84998     assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
84999
85000     /* Delete any triggers created to implement actions for this FK. */
85001 #ifndef SQLITE_OMIT_TRIGGER
85002     fkTriggerDelete(db, pFKey->apTrigger[0]);
85003     fkTriggerDelete(db, pFKey->apTrigger[1]);
85004 #endif
85005
85006     pNext = pFKey->pNextFrom;
85007     sqlite3DbFree(db, pFKey);
85008   }
85009 }
85010 #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
85011
85012 /************** End of fkey.c ************************************************/
85013 /************** Begin file insert.c ******************************************/
85014 /*
85015 ** 2001 September 15
85016 **
85017 ** The author disclaims copyright to this source code.  In place of
85018 ** a legal notice, here is a blessing:
85019 **
85020 **    May you do good and not evil.
85021 **    May you find forgiveness for yourself and forgive others.
85022 **    May you share freely, never taking more than you give.
85023 **
85024 *************************************************************************
85025 ** This file contains C code routines that are called by the parser
85026 ** to handle INSERT statements in SQLite.
85027 */
85028
85029 /*
85030 ** Generate code that will open a table for reading.
85031 */
85032 SQLITE_PRIVATE void sqlite3OpenTable(
85033   Parse *p,       /* Generate code into this VDBE */
85034   int iCur,       /* The cursor number of the table */
85035   int iDb,        /* The database index in sqlite3.aDb[] */
85036   Table *pTab,    /* The table to be opened */
85037   int opcode      /* OP_OpenRead or OP_OpenWrite */
85038 ){
85039   Vdbe *v;
85040   if( IsVirtual(pTab) ) return;
85041   v = sqlite3GetVdbe(p);
85042   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
85043   sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
85044   sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
85045   sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
85046   VdbeComment((v, "%s", pTab->zName));
85047 }
85048
85049 /*
85050 ** Return a pointer to the column affinity string associated with index
85051 ** pIdx. A column affinity string has one character for each column in 
85052 ** the table, according to the affinity of the column:
85053 **
85054 **  Character      Column affinity
85055 **  ------------------------------
85056 **  'a'            TEXT
85057 **  'b'            NONE
85058 **  'c'            NUMERIC
85059 **  'd'            INTEGER
85060 **  'e'            REAL
85061 **
85062 ** An extra 'b' is appended to the end of the string to cover the
85063 ** rowid that appears as the last column in every index.
85064 **
85065 ** Memory for the buffer containing the column index affinity string
85066 ** is managed along with the rest of the Index structure. It will be
85067 ** released when sqlite3DeleteIndex() is called.
85068 */
85069 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
85070   if( !pIdx->zColAff ){
85071     /* The first time a column affinity string for a particular index is
85072     ** required, it is allocated and populated here. It is then stored as
85073     ** a member of the Index structure for subsequent use.
85074     **
85075     ** The column affinity string will eventually be deleted by
85076     ** sqliteDeleteIndex() when the Index structure itself is cleaned
85077     ** up.
85078     */
85079     int n;
85080     Table *pTab = pIdx->pTable;
85081     sqlite3 *db = sqlite3VdbeDb(v);
85082     pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+2);
85083     if( !pIdx->zColAff ){
85084       db->mallocFailed = 1;
85085       return 0;
85086     }
85087     for(n=0; n<pIdx->nColumn; n++){
85088       pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
85089     }
85090     pIdx->zColAff[n++] = SQLITE_AFF_NONE;
85091     pIdx->zColAff[n] = 0;
85092   }
85093  
85094   return pIdx->zColAff;
85095 }
85096
85097 /*
85098 ** Set P4 of the most recently inserted opcode to a column affinity
85099 ** string for table pTab. A column affinity string has one character
85100 ** for each column indexed by the index, according to the affinity of the
85101 ** column:
85102 **
85103 **  Character      Column affinity
85104 **  ------------------------------
85105 **  'a'            TEXT
85106 **  'b'            NONE
85107 **  'c'            NUMERIC
85108 **  'd'            INTEGER
85109 **  'e'            REAL
85110 */
85111 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
85112   /* The first time a column affinity string for a particular table
85113   ** is required, it is allocated and populated here. It is then 
85114   ** stored as a member of the Table structure for subsequent use.
85115   **
85116   ** The column affinity string will eventually be deleted by
85117   ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
85118   */
85119   if( !pTab->zColAff ){
85120     char *zColAff;
85121     int i;
85122     sqlite3 *db = sqlite3VdbeDb(v);
85123
85124     zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
85125     if( !zColAff ){
85126       db->mallocFailed = 1;
85127       return;
85128     }
85129
85130     for(i=0; i<pTab->nCol; i++){
85131       zColAff[i] = pTab->aCol[i].affinity;
85132     }
85133     zColAff[pTab->nCol] = '\0';
85134
85135     pTab->zColAff = zColAff;
85136   }
85137
85138   sqlite3VdbeChangeP4(v, -1, pTab->zColAff, P4_TRANSIENT);
85139 }
85140
85141 /*
85142 ** Return non-zero if the table pTab in database iDb or any of its indices
85143 ** have been opened at any point in the VDBE program beginning at location
85144 ** iStartAddr throught the end of the program.  This is used to see if 
85145 ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can 
85146 ** run without using temporary table for the results of the SELECT. 
85147 */
85148 static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
85149   Vdbe *v = sqlite3GetVdbe(p);
85150   int i;
85151   int iEnd = sqlite3VdbeCurrentAddr(v);
85152 #ifndef SQLITE_OMIT_VIRTUALTABLE
85153   VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
85154 #endif
85155
85156   for(i=iStartAddr; i<iEnd; i++){
85157     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
85158     assert( pOp!=0 );
85159     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
85160       Index *pIndex;
85161       int tnum = pOp->p2;
85162       if( tnum==pTab->tnum ){
85163         return 1;
85164       }
85165       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
85166         if( tnum==pIndex->tnum ){
85167           return 1;
85168         }
85169       }
85170     }
85171 #ifndef SQLITE_OMIT_VIRTUALTABLE
85172     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
85173       assert( pOp->p4.pVtab!=0 );
85174       assert( pOp->p4type==P4_VTAB );
85175       return 1;
85176     }
85177 #endif
85178   }
85179   return 0;
85180 }
85181
85182 #ifndef SQLITE_OMIT_AUTOINCREMENT
85183 /*
85184 ** Locate or create an AutoincInfo structure associated with table pTab
85185 ** which is in database iDb.  Return the register number for the register
85186 ** that holds the maximum rowid.
85187 **
85188 ** There is at most one AutoincInfo structure per table even if the
85189 ** same table is autoincremented multiple times due to inserts within
85190 ** triggers.  A new AutoincInfo structure is created if this is the
85191 ** first use of table pTab.  On 2nd and subsequent uses, the original
85192 ** AutoincInfo structure is used.
85193 **
85194 ** Three memory locations are allocated:
85195 **
85196 **   (1)  Register to hold the name of the pTab table.
85197 **   (2)  Register to hold the maximum ROWID of pTab.
85198 **   (3)  Register to hold the rowid in sqlite_sequence of pTab
85199 **
85200 ** The 2nd register is the one that is returned.  That is all the
85201 ** insert routine needs to know about.
85202 */
85203 static int autoIncBegin(
85204   Parse *pParse,      /* Parsing context */
85205   int iDb,            /* Index of the database holding pTab */
85206   Table *pTab         /* The table we are writing to */
85207 ){
85208   int memId = 0;      /* Register holding maximum rowid */
85209   if( pTab->tabFlags & TF_Autoincrement ){
85210     Parse *pToplevel = sqlite3ParseToplevel(pParse);
85211     AutoincInfo *pInfo;
85212
85213     pInfo = pToplevel->pAinc;
85214     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
85215     if( pInfo==0 ){
85216       pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
85217       if( pInfo==0 ) return 0;
85218       pInfo->pNext = pToplevel->pAinc;
85219       pToplevel->pAinc = pInfo;
85220       pInfo->pTab = pTab;
85221       pInfo->iDb = iDb;
85222       pToplevel->nMem++;                  /* Register to hold name of table */
85223       pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
85224       pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
85225     }
85226     memId = pInfo->regCtr;
85227   }
85228   return memId;
85229 }
85230
85231 /*
85232 ** This routine generates code that will initialize all of the
85233 ** register used by the autoincrement tracker.  
85234 */
85235 SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
85236   AutoincInfo *p;            /* Information about an AUTOINCREMENT */
85237   sqlite3 *db = pParse->db;  /* The database connection */
85238   Db *pDb;                   /* Database only autoinc table */
85239   int memId;                 /* Register holding max rowid */
85240   int addr;                  /* A VDBE address */
85241   Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
85242
85243   /* This routine is never called during trigger-generation.  It is
85244   ** only called from the top-level */
85245   assert( pParse->pTriggerTab==0 );
85246   assert( pParse==sqlite3ParseToplevel(pParse) );
85247
85248   assert( v );   /* We failed long ago if this is not so */
85249   for(p = pParse->pAinc; p; p = p->pNext){
85250     pDb = &db->aDb[p->iDb];
85251     memId = p->regCtr;
85252     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
85253     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
85254     addr = sqlite3VdbeCurrentAddr(v);
85255     sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
85256     sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
85257     sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
85258     sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
85259     sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
85260     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
85261     sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
85262     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
85263     sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
85264     sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
85265     sqlite3VdbeAddOp0(v, OP_Close);
85266   }
85267 }
85268
85269 /*
85270 ** Update the maximum rowid for an autoincrement calculation.
85271 **
85272 ** This routine should be called when the top of the stack holds a
85273 ** new rowid that is about to be inserted.  If that new rowid is
85274 ** larger than the maximum rowid in the memId memory cell, then the
85275 ** memory cell is updated.  The stack is unchanged.
85276 */
85277 static void autoIncStep(Parse *pParse, int memId, int regRowid){
85278   if( memId>0 ){
85279     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
85280   }
85281 }
85282
85283 /*
85284 ** This routine generates the code needed to write autoincrement
85285 ** maximum rowid values back into the sqlite_sequence register.
85286 ** Every statement that might do an INSERT into an autoincrement
85287 ** table (either directly or through triggers) needs to call this
85288 ** routine just before the "exit" code.
85289 */
85290 SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
85291   AutoincInfo *p;
85292   Vdbe *v = pParse->pVdbe;
85293   sqlite3 *db = pParse->db;
85294
85295   assert( v );
85296   for(p = pParse->pAinc; p; p = p->pNext){
85297     Db *pDb = &db->aDb[p->iDb];
85298     int j1, j2, j3, j4, j5;
85299     int iRec;
85300     int memId = p->regCtr;
85301
85302     iRec = sqlite3GetTempReg(pParse);
85303     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
85304     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
85305     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
85306     j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
85307     j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
85308     j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
85309     sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
85310     sqlite3VdbeJumpHere(v, j2);
85311     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
85312     j5 = sqlite3VdbeAddOp0(v, OP_Goto);
85313     sqlite3VdbeJumpHere(v, j4);
85314     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
85315     sqlite3VdbeJumpHere(v, j1);
85316     sqlite3VdbeJumpHere(v, j5);
85317     sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
85318     sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
85319     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
85320     sqlite3VdbeAddOp0(v, OP_Close);
85321     sqlite3ReleaseTempReg(pParse, iRec);
85322   }
85323 }
85324 #else
85325 /*
85326 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
85327 ** above are all no-ops
85328 */
85329 # define autoIncBegin(A,B,C) (0)
85330 # define autoIncStep(A,B,C)
85331 #endif /* SQLITE_OMIT_AUTOINCREMENT */
85332
85333
85334 /* Forward declaration */
85335 static int xferOptimization(
85336   Parse *pParse,        /* Parser context */
85337   Table *pDest,         /* The table we are inserting into */
85338   Select *pSelect,      /* A SELECT statement to use as the data source */
85339   int onError,          /* How to handle constraint errors */
85340   int iDbDest           /* The database of pDest */
85341 );
85342
85343 /*
85344 ** This routine is call to handle SQL of the following forms:
85345 **
85346 **    insert into TABLE (IDLIST) values(EXPRLIST)
85347 **    insert into TABLE (IDLIST) select
85348 **
85349 ** The IDLIST following the table name is always optional.  If omitted,
85350 ** then a list of all columns for the table is substituted.  The IDLIST
85351 ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
85352 **
85353 ** The pList parameter holds EXPRLIST in the first form of the INSERT
85354 ** statement above, and pSelect is NULL.  For the second form, pList is
85355 ** NULL and pSelect is a pointer to the select statement used to generate
85356 ** data for the insert.
85357 **
85358 ** The code generated follows one of four templates.  For a simple
85359 ** select with data coming from a VALUES clause, the code executes
85360 ** once straight down through.  Pseudo-code follows (we call this
85361 ** the "1st template"):
85362 **
85363 **         open write cursor to <table> and its indices
85364 **         puts VALUES clause expressions onto the stack
85365 **         write the resulting record into <table>
85366 **         cleanup
85367 **
85368 ** The three remaining templates assume the statement is of the form
85369 **
85370 **   INSERT INTO <table> SELECT ...
85371 **
85372 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
85373 ** in other words if the SELECT pulls all columns from a single table
85374 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
85375 ** if <table2> and <table1> are distinct tables but have identical
85376 ** schemas, including all the same indices, then a special optimization
85377 ** is invoked that copies raw records from <table2> over to <table1>.
85378 ** See the xferOptimization() function for the implementation of this
85379 ** template.  This is the 2nd template.
85380 **
85381 **         open a write cursor to <table>
85382 **         open read cursor on <table2>
85383 **         transfer all records in <table2> over to <table>
85384 **         close cursors
85385 **         foreach index on <table>
85386 **           open a write cursor on the <table> index
85387 **           open a read cursor on the corresponding <table2> index
85388 **           transfer all records from the read to the write cursors
85389 **           close cursors
85390 **         end foreach
85391 **
85392 ** The 3rd template is for when the second template does not apply
85393 ** and the SELECT clause does not read from <table> at any time.
85394 ** The generated code follows this template:
85395 **
85396 **         EOF <- 0
85397 **         X <- A
85398 **         goto B
85399 **      A: setup for the SELECT
85400 **         loop over the rows in the SELECT
85401 **           load values into registers R..R+n
85402 **           yield X
85403 **         end loop
85404 **         cleanup after the SELECT
85405 **         EOF <- 1
85406 **         yield X
85407 **         goto A
85408 **      B: open write cursor to <table> and its indices
85409 **      C: yield X
85410 **         if EOF goto D
85411 **         insert the select result into <table> from R..R+n
85412 **         goto C
85413 **      D: cleanup
85414 **
85415 ** The 4th template is used if the insert statement takes its
85416 ** values from a SELECT but the data is being inserted into a table
85417 ** that is also read as part of the SELECT.  In the third form,
85418 ** we have to use a intermediate table to store the results of
85419 ** the select.  The template is like this:
85420 **
85421 **         EOF <- 0
85422 **         X <- A
85423 **         goto B
85424 **      A: setup for the SELECT
85425 **         loop over the tables in the SELECT
85426 **           load value into register R..R+n
85427 **           yield X
85428 **         end loop
85429 **         cleanup after the SELECT
85430 **         EOF <- 1
85431 **         yield X
85432 **         halt-error
85433 **      B: open temp table
85434 **      L: yield X
85435 **         if EOF goto M
85436 **         insert row from R..R+n into temp table
85437 **         goto L
85438 **      M: open write cursor to <table> and its indices
85439 **         rewind temp table
85440 **      C: loop over rows of intermediate table
85441 **           transfer values form intermediate table into <table>
85442 **         end loop
85443 **      D: cleanup
85444 */
85445 SQLITE_PRIVATE void sqlite3Insert(
85446   Parse *pParse,        /* Parser context */
85447   SrcList *pTabList,    /* Name of table into which we are inserting */
85448   ExprList *pList,      /* List of values to be inserted */
85449   Select *pSelect,      /* A SELECT statement to use as the data source */
85450   IdList *pColumn,      /* Column names corresponding to IDLIST. */
85451   int onError           /* How to handle constraint errors */
85452 ){
85453   sqlite3 *db;          /* The main database structure */
85454   Table *pTab;          /* The table to insert into.  aka TABLE */
85455   char *zTab;           /* Name of the table into which we are inserting */
85456   const char *zDb;      /* Name of the database holding this table */
85457   int i, j, idx;        /* Loop counters */
85458   Vdbe *v;              /* Generate code into this virtual machine */
85459   Index *pIdx;          /* For looping over indices of the table */
85460   int nColumn;          /* Number of columns in the data */
85461   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
85462   int baseCur = 0;      /* VDBE Cursor number for pTab */
85463   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
85464   int endOfLoop;        /* Label for the end of the insertion loop */
85465   int useTempTable = 0; /* Store SELECT results in intermediate table */
85466   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
85467   int addrInsTop = 0;   /* Jump to label "D" */
85468   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
85469   int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
85470   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
85471   int iDb;              /* Index of database holding TABLE */
85472   Db *pDb;              /* The database containing table being inserted into */
85473   int appendFlag = 0;   /* True if the insert is likely to be an append */
85474
85475   /* Register allocations */
85476   int regFromSelect = 0;/* Base register for data coming from SELECT */
85477   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
85478   int regRowCount = 0;  /* Memory cell used for the row counter */
85479   int regIns;           /* Block of regs holding rowid+data being inserted */
85480   int regRowid;         /* registers holding insert rowid */
85481   int regData;          /* register holding first column to insert */
85482   int regEof = 0;       /* Register recording end of SELECT data */
85483   int *aRegIdx = 0;     /* One register allocated to each index */
85484
85485 #ifndef SQLITE_OMIT_TRIGGER
85486   int isView;                 /* True if attempting to insert into a view */
85487   Trigger *pTrigger;          /* List of triggers on pTab, if required */
85488   int tmask;                  /* Mask of trigger times */
85489 #endif
85490
85491   db = pParse->db;
85492   memset(&dest, 0, sizeof(dest));
85493   if( pParse->nErr || db->mallocFailed ){
85494     goto insert_cleanup;
85495   }
85496
85497   /* Locate the table into which we will be inserting new information.
85498   */
85499   assert( pTabList->nSrc==1 );
85500   zTab = pTabList->a[0].zName;
85501   if( NEVER(zTab==0) ) goto insert_cleanup;
85502   pTab = sqlite3SrcListLookup(pParse, pTabList);
85503   if( pTab==0 ){
85504     goto insert_cleanup;
85505   }
85506   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
85507   assert( iDb<db->nDb );
85508   pDb = &db->aDb[iDb];
85509   zDb = pDb->zName;
85510   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
85511     goto insert_cleanup;
85512   }
85513
85514   /* Figure out if we have any triggers and if the table being
85515   ** inserted into is a view
85516   */
85517 #ifndef SQLITE_OMIT_TRIGGER
85518   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
85519   isView = pTab->pSelect!=0;
85520 #else
85521 # define pTrigger 0
85522 # define tmask 0
85523 # define isView 0
85524 #endif
85525 #ifdef SQLITE_OMIT_VIEW
85526 # undef isView
85527 # define isView 0
85528 #endif
85529   assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
85530
85531   /* If pTab is really a view, make sure it has been initialized.
85532   ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual 
85533   ** module table).
85534   */
85535   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
85536     goto insert_cleanup;
85537   }
85538
85539   /* Ensure that:
85540   *  (a) the table is not read-only, 
85541   *  (b) that if it is a view then ON INSERT triggers exist
85542   */
85543   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
85544     goto insert_cleanup;
85545   }
85546
85547   /* Allocate a VDBE
85548   */
85549   v = sqlite3GetVdbe(pParse);
85550   if( v==0 ) goto insert_cleanup;
85551   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
85552   sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
85553
85554 #ifndef SQLITE_OMIT_XFER_OPT
85555   /* If the statement is of the form
85556   **
85557   **       INSERT INTO <table1> SELECT * FROM <table2>;
85558   **
85559   ** Then special optimizations can be applied that make the transfer
85560   ** very fast and which reduce fragmentation of indices.
85561   **
85562   ** This is the 2nd template.
85563   */
85564   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
85565     assert( !pTrigger );
85566     assert( pList==0 );
85567     goto insert_end;
85568   }
85569 #endif /* SQLITE_OMIT_XFER_OPT */
85570
85571   /* If this is an AUTOINCREMENT table, look up the sequence number in the
85572   ** sqlite_sequence table and store it in memory cell regAutoinc.
85573   */
85574   regAutoinc = autoIncBegin(pParse, iDb, pTab);
85575
85576   /* Figure out how many columns of data are supplied.  If the data
85577   ** is coming from a SELECT statement, then generate a co-routine that
85578   ** produces a single row of the SELECT on each invocation.  The
85579   ** co-routine is the common header to the 3rd and 4th templates.
85580   */
85581   if( pSelect ){
85582     /* Data is coming from a SELECT.  Generate code to implement that SELECT
85583     ** as a co-routine.  The code is common to both the 3rd and 4th
85584     ** templates:
85585     **
85586     **         EOF <- 0
85587     **         X <- A
85588     **         goto B
85589     **      A: setup for the SELECT
85590     **         loop over the tables in the SELECT
85591     **           load value into register R..R+n
85592     **           yield X
85593     **         end loop
85594     **         cleanup after the SELECT
85595     **         EOF <- 1
85596     **         yield X
85597     **         halt-error
85598     **
85599     ** On each invocation of the co-routine, it puts a single row of the
85600     ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
85601     ** (These output registers are allocated by sqlite3Select().)  When
85602     ** the SELECT completes, it sets the EOF flag stored in regEof.
85603     */
85604     int rc, j1;
85605
85606     regEof = ++pParse->nMem;
85607     sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);      /* EOF <- 0 */
85608     VdbeComment((v, "SELECT eof flag"));
85609     sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
85610     addrSelect = sqlite3VdbeCurrentAddr(v)+2;
85611     sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm);
85612     j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
85613     VdbeComment((v, "Jump over SELECT coroutine"));
85614
85615     /* Resolve the expressions in the SELECT statement and execute it. */
85616     rc = sqlite3Select(pParse, pSelect, &dest);
85617     assert( pParse->nErr==0 || rc );
85618     if( rc || NEVER(pParse->nErr) || db->mallocFailed ){
85619       goto insert_cleanup;
85620     }
85621     sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);         /* EOF <- 1 */
85622     sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);   /* yield X */
85623     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
85624     VdbeComment((v, "End of SELECT coroutine"));
85625     sqlite3VdbeJumpHere(v, j1);                          /* label B: */
85626
85627     regFromSelect = dest.iMem;
85628     assert( pSelect->pEList );
85629     nColumn = pSelect->pEList->nExpr;
85630     assert( dest.nMem==nColumn );
85631
85632     /* Set useTempTable to TRUE if the result of the SELECT statement
85633     ** should be written into a temporary table (template 4).  Set to
85634     ** FALSE if each* row of the SELECT can be written directly into
85635     ** the destination table (template 3).
85636     **
85637     ** A temp table must be used if the table being updated is also one
85638     ** of the tables being read by the SELECT statement.  Also use a 
85639     ** temp table in the case of row triggers.
85640     */
85641     if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
85642       useTempTable = 1;
85643     }
85644
85645     if( useTempTable ){
85646       /* Invoke the coroutine to extract information from the SELECT
85647       ** and add it to a transient table srcTab.  The code generated
85648       ** here is from the 4th template:
85649       **
85650       **      B: open temp table
85651       **      L: yield X
85652       **         if EOF goto M
85653       **         insert row from R..R+n into temp table
85654       **         goto L
85655       **      M: ...
85656       */
85657       int regRec;          /* Register to hold packed record */
85658       int regTempRowid;    /* Register to hold temp table ROWID */
85659       int addrTop;         /* Label "L" */
85660       int addrIf;          /* Address of jump to M */
85661
85662       srcTab = pParse->nTab++;
85663       regRec = sqlite3GetTempReg(pParse);
85664       regTempRowid = sqlite3GetTempReg(pParse);
85665       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
85666       addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
85667       addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
85668       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
85669       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
85670       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
85671       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
85672       sqlite3VdbeJumpHere(v, addrIf);
85673       sqlite3ReleaseTempReg(pParse, regRec);
85674       sqlite3ReleaseTempReg(pParse, regTempRowid);
85675     }
85676   }else{
85677     /* This is the case if the data for the INSERT is coming from a VALUES
85678     ** clause
85679     */
85680     NameContext sNC;
85681     memset(&sNC, 0, sizeof(sNC));
85682     sNC.pParse = pParse;
85683     srcTab = -1;
85684     assert( useTempTable==0 );
85685     nColumn = pList ? pList->nExpr : 0;
85686     for(i=0; i<nColumn; i++){
85687       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
85688         goto insert_cleanup;
85689       }
85690     }
85691   }
85692
85693   /* Make sure the number of columns in the source data matches the number
85694   ** of columns to be inserted into the table.
85695   */
85696   if( IsVirtual(pTab) ){
85697     for(i=0; i<pTab->nCol; i++){
85698       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
85699     }
85700   }
85701   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
85702     sqlite3ErrorMsg(pParse, 
85703        "table %S has %d columns but %d values were supplied",
85704        pTabList, 0, pTab->nCol-nHidden, nColumn);
85705     goto insert_cleanup;
85706   }
85707   if( pColumn!=0 && nColumn!=pColumn->nId ){
85708     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
85709     goto insert_cleanup;
85710   }
85711
85712   /* If the INSERT statement included an IDLIST term, then make sure
85713   ** all elements of the IDLIST really are columns of the table and 
85714   ** remember the column indices.
85715   **
85716   ** If the table has an INTEGER PRIMARY KEY column and that column
85717   ** is named in the IDLIST, then record in the keyColumn variable
85718   ** the index into IDLIST of the primary key column.  keyColumn is
85719   ** the index of the primary key as it appears in IDLIST, not as
85720   ** is appears in the original table.  (The index of the primary
85721   ** key in the original table is pTab->iPKey.)
85722   */
85723   if( pColumn ){
85724     for(i=0; i<pColumn->nId; i++){
85725       pColumn->a[i].idx = -1;
85726     }
85727     for(i=0; i<pColumn->nId; i++){
85728       for(j=0; j<pTab->nCol; j++){
85729         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
85730           pColumn->a[i].idx = j;
85731           if( j==pTab->iPKey ){
85732             keyColumn = i;
85733           }
85734           break;
85735         }
85736       }
85737       if( j>=pTab->nCol ){
85738         if( sqlite3IsRowid(pColumn->a[i].zName) ){
85739           keyColumn = i;
85740         }else{
85741           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
85742               pTabList, 0, pColumn->a[i].zName);
85743           pParse->checkSchema = 1;
85744           goto insert_cleanup;
85745         }
85746       }
85747     }
85748   }
85749
85750   /* If there is no IDLIST term but the table has an integer primary
85751   ** key, the set the keyColumn variable to the primary key column index
85752   ** in the original table definition.
85753   */
85754   if( pColumn==0 && nColumn>0 ){
85755     keyColumn = pTab->iPKey;
85756   }
85757     
85758   /* Initialize the count of rows to be inserted
85759   */
85760   if( db->flags & SQLITE_CountRows ){
85761     regRowCount = ++pParse->nMem;
85762     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
85763   }
85764
85765   /* If this is not a view, open the table and and all indices */
85766   if( !isView ){
85767     int nIdx;
85768
85769     baseCur = pParse->nTab;
85770     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
85771     aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
85772     if( aRegIdx==0 ){
85773       goto insert_cleanup;
85774     }
85775     for(i=0; i<nIdx; i++){
85776       aRegIdx[i] = ++pParse->nMem;
85777     }
85778   }
85779
85780   /* This is the top of the main insertion loop */
85781   if( useTempTable ){
85782     /* This block codes the top of loop only.  The complete loop is the
85783     ** following pseudocode (template 4):
85784     **
85785     **         rewind temp table
85786     **      C: loop over rows of intermediate table
85787     **           transfer values form intermediate table into <table>
85788     **         end loop
85789     **      D: ...
85790     */
85791     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
85792     addrCont = sqlite3VdbeCurrentAddr(v);
85793   }else if( pSelect ){
85794     /* This block codes the top of loop only.  The complete loop is the
85795     ** following pseudocode (template 3):
85796     **
85797     **      C: yield X
85798     **         if EOF goto D
85799     **         insert the select result into <table> from R..R+n
85800     **         goto C
85801     **      D: ...
85802     */
85803     addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
85804     addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
85805   }
85806
85807   /* Allocate registers for holding the rowid of the new row,
85808   ** the content of the new row, and the assemblied row record.
85809   */
85810   regRowid = regIns = pParse->nMem+1;
85811   pParse->nMem += pTab->nCol + 1;
85812   if( IsVirtual(pTab) ){
85813     regRowid++;
85814     pParse->nMem++;
85815   }
85816   regData = regRowid+1;
85817
85818   /* Run the BEFORE and INSTEAD OF triggers, if there are any
85819   */
85820   endOfLoop = sqlite3VdbeMakeLabel(v);
85821   if( tmask & TRIGGER_BEFORE ){
85822     int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
85823
85824     /* build the NEW.* reference row.  Note that if there is an INTEGER
85825     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
85826     ** translated into a unique ID for the row.  But on a BEFORE trigger,
85827     ** we do not know what the unique ID will be (because the insert has
85828     ** not happened yet) so we substitute a rowid of -1
85829     */
85830     if( keyColumn<0 ){
85831       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
85832     }else{
85833       int j1;
85834       if( useTempTable ){
85835         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
85836       }else{
85837         assert( pSelect==0 );  /* Otherwise useTempTable is true */
85838         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
85839       }
85840       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
85841       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
85842       sqlite3VdbeJumpHere(v, j1);
85843       sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
85844     }
85845
85846     /* Cannot have triggers on a virtual table. If it were possible,
85847     ** this block would have to account for hidden column.
85848     */
85849     assert( !IsVirtual(pTab) );
85850
85851     /* Create the new column data
85852     */
85853     for(i=0; i<pTab->nCol; i++){
85854       if( pColumn==0 ){
85855         j = i;
85856       }else{
85857         for(j=0; j<pColumn->nId; j++){
85858           if( pColumn->a[j].idx==i ) break;
85859         }
85860       }
85861       if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
85862         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
85863       }else if( useTempTable ){
85864         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1); 
85865       }else{
85866         assert( pSelect==0 ); /* Otherwise useTempTable is true */
85867         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
85868       }
85869     }
85870
85871     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
85872     ** do not attempt any conversions before assembling the record.
85873     ** If this is a real table, attempt conversions as required by the
85874     ** table column affinities.
85875     */
85876     if( !isView ){
85877       sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
85878       sqlite3TableAffinityStr(v, pTab);
85879     }
85880
85881     /* Fire BEFORE or INSTEAD OF triggers */
85882     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE, 
85883         pTab, regCols-pTab->nCol-1, onError, endOfLoop);
85884
85885     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
85886   }
85887
85888   /* Push the record number for the new entry onto the stack.  The
85889   ** record number is a randomly generate integer created by NewRowid
85890   ** except when the table has an INTEGER PRIMARY KEY column, in which
85891   ** case the record number is the same as that column. 
85892   */
85893   if( !isView ){
85894     if( IsVirtual(pTab) ){
85895       /* The row that the VUpdate opcode will delete: none */
85896       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
85897     }
85898     if( keyColumn>=0 ){
85899       if( useTempTable ){
85900         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
85901       }else if( pSelect ){
85902         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
85903       }else{
85904         VdbeOp *pOp;
85905         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
85906         pOp = sqlite3VdbeGetOp(v, -1);
85907         if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
85908           appendFlag = 1;
85909           pOp->opcode = OP_NewRowid;
85910           pOp->p1 = baseCur;
85911           pOp->p2 = regRowid;
85912           pOp->p3 = regAutoinc;
85913         }
85914       }
85915       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
85916       ** to generate a unique primary key value.
85917       */
85918       if( !appendFlag ){
85919         int j1;
85920         if( !IsVirtual(pTab) ){
85921           j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
85922           sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
85923           sqlite3VdbeJumpHere(v, j1);
85924         }else{
85925           j1 = sqlite3VdbeCurrentAddr(v);
85926           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
85927         }
85928         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
85929       }
85930     }else if( IsVirtual(pTab) ){
85931       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
85932     }else{
85933       sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
85934       appendFlag = 1;
85935     }
85936     autoIncStep(pParse, regAutoinc, regRowid);
85937
85938     /* Push onto the stack, data for all columns of the new entry, beginning
85939     ** with the first column.
85940     */
85941     nHidden = 0;
85942     for(i=0; i<pTab->nCol; i++){
85943       int iRegStore = regRowid+1+i;
85944       if( i==pTab->iPKey ){
85945         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
85946         ** Whenever this column is read, the record number will be substituted
85947         ** in its place.  So will fill this column with a NULL to avoid
85948         ** taking up data space with information that will never be used. */
85949         sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
85950         continue;
85951       }
85952       if( pColumn==0 ){
85953         if( IsHiddenColumn(&pTab->aCol[i]) ){
85954           assert( IsVirtual(pTab) );
85955           j = -1;
85956           nHidden++;
85957         }else{
85958           j = i - nHidden;
85959         }
85960       }else{
85961         for(j=0; j<pColumn->nId; j++){
85962           if( pColumn->a[j].idx==i ) break;
85963         }
85964       }
85965       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
85966         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
85967       }else if( useTempTable ){
85968         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); 
85969       }else if( pSelect ){
85970         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
85971       }else{
85972         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
85973       }
85974     }
85975
85976     /* Generate code to check constraints and generate index keys and
85977     ** do the insertion.
85978     */
85979 #ifndef SQLITE_OMIT_VIRTUALTABLE
85980     if( IsVirtual(pTab) ){
85981       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
85982       sqlite3VtabMakeWritable(pParse, pTab);
85983       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
85984       sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
85985       sqlite3MayAbort(pParse);
85986     }else
85987 #endif
85988     {
85989       int isReplace;    /* Set to true if constraints may cause a replace */
85990       sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
85991           keyColumn>=0, 0, onError, endOfLoop, &isReplace
85992       );
85993       sqlite3FkCheck(pParse, pTab, 0, regIns);
85994       sqlite3CompleteInsertion(
85995           pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
85996       );
85997     }
85998   }
85999
86000   /* Update the count of rows that are inserted
86001   */
86002   if( (db->flags & SQLITE_CountRows)!=0 ){
86003     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
86004   }
86005
86006   if( pTrigger ){
86007     /* Code AFTER triggers */
86008     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER, 
86009         pTab, regData-2-pTab->nCol, onError, endOfLoop);
86010   }
86011
86012   /* The bottom of the main insertion loop, if the data source
86013   ** is a SELECT statement.
86014   */
86015   sqlite3VdbeResolveLabel(v, endOfLoop);
86016   if( useTempTable ){
86017     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
86018     sqlite3VdbeJumpHere(v, addrInsTop);
86019     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
86020   }else if( pSelect ){
86021     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
86022     sqlite3VdbeJumpHere(v, addrInsTop);
86023   }
86024
86025   if( !IsVirtual(pTab) && !isView ){
86026     /* Close all tables opened */
86027     sqlite3VdbeAddOp1(v, OP_Close, baseCur);
86028     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
86029       sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
86030     }
86031   }
86032
86033 insert_end:
86034   /* Update the sqlite_sequence table by storing the content of the
86035   ** maximum rowid counter values recorded while inserting into
86036   ** autoincrement tables.
86037   */
86038   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
86039     sqlite3AutoincrementEnd(pParse);
86040   }
86041
86042   /*
86043   ** Return the number of rows inserted. If this routine is 
86044   ** generating code because of a call to sqlite3NestedParse(), do not
86045   ** invoke the callback function.
86046   */
86047   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
86048     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
86049     sqlite3VdbeSetNumCols(v, 1);
86050     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
86051   }
86052
86053 insert_cleanup:
86054   sqlite3SrcListDelete(db, pTabList);
86055   sqlite3ExprListDelete(db, pList);
86056   sqlite3SelectDelete(db, pSelect);
86057   sqlite3IdListDelete(db, pColumn);
86058   sqlite3DbFree(db, aRegIdx);
86059 }
86060
86061 /* Make sure "isView" and other macros defined above are undefined. Otherwise
86062 ** thely may interfere with compilation of other functions in this file
86063 ** (or in another file, if this file becomes part of the amalgamation).  */
86064 #ifdef isView
86065  #undef isView
86066 #endif
86067 #ifdef pTrigger
86068  #undef pTrigger
86069 #endif
86070 #ifdef tmask
86071  #undef tmask
86072 #endif
86073
86074
86075 /*
86076 ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
86077 **
86078 ** The input is a range of consecutive registers as follows:
86079 **
86080 **    1.  The rowid of the row after the update.
86081 **
86082 **    2.  The data in the first column of the entry after the update.
86083 **
86084 **    i.  Data from middle columns...
86085 **
86086 **    N.  The data in the last column of the entry after the update.
86087 **
86088 ** The regRowid parameter is the index of the register containing (1).
86089 **
86090 ** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
86091 ** the address of a register containing the rowid before the update takes
86092 ** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
86093 ** is false, indicating an INSERT statement, then a non-zero rowidChng 
86094 ** indicates that the rowid was explicitly specified as part of the
86095 ** INSERT statement. If rowidChng is false, it means that  the rowid is
86096 ** computed automatically in an insert or that the rowid value is not 
86097 ** modified by an update.
86098 **
86099 ** The code generated by this routine store new index entries into
86100 ** registers identified by aRegIdx[].  No index entry is created for
86101 ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
86102 ** the same as the order of indices on the linked list of indices
86103 ** attached to the table.
86104 **
86105 ** This routine also generates code to check constraints.  NOT NULL,
86106 ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
86107 ** then the appropriate action is performed.  There are five possible
86108 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
86109 **
86110 **  Constraint type  Action       What Happens
86111 **  ---------------  ----------   ----------------------------------------
86112 **  any              ROLLBACK     The current transaction is rolled back and
86113 **                                sqlite3_exec() returns immediately with a
86114 **                                return code of SQLITE_CONSTRAINT.
86115 **
86116 **  any              ABORT        Back out changes from the current command
86117 **                                only (do not do a complete rollback) then
86118 **                                cause sqlite3_exec() to return immediately
86119 **                                with SQLITE_CONSTRAINT.
86120 **
86121 **  any              FAIL         Sqlite_exec() returns immediately with a
86122 **                                return code of SQLITE_CONSTRAINT.  The
86123 **                                transaction is not rolled back and any
86124 **                                prior changes are retained.
86125 **
86126 **  any              IGNORE       The record number and data is popped from
86127 **                                the stack and there is an immediate jump
86128 **                                to label ignoreDest.
86129 **
86130 **  NOT NULL         REPLACE      The NULL value is replace by the default
86131 **                                value for that column.  If the default value
86132 **                                is NULL, the action is the same as ABORT.
86133 **
86134 **  UNIQUE           REPLACE      The other row that conflicts with the row
86135 **                                being inserted is removed.
86136 **
86137 **  CHECK            REPLACE      Illegal.  The results in an exception.
86138 **
86139 ** Which action to take is determined by the overrideError parameter.
86140 ** Or if overrideError==OE_Default, then the pParse->onError parameter
86141 ** is used.  Or if pParse->onError==OE_Default then the onError value
86142 ** for the constraint is used.
86143 **
86144 ** The calling routine must open a read/write cursor for pTab with
86145 ** cursor number "baseCur".  All indices of pTab must also have open
86146 ** read/write cursors with cursor number baseCur+i for the i-th cursor.
86147 ** Except, if there is no possibility of a REPLACE action then
86148 ** cursors do not need to be open for indices where aRegIdx[i]==0.
86149 */
86150 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
86151   Parse *pParse,      /* The parser context */
86152   Table *pTab,        /* the table into which we are inserting */
86153   int baseCur,        /* Index of a read/write cursor pointing at pTab */
86154   int regRowid,       /* Index of the range of input registers */
86155   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
86156   int rowidChng,      /* True if the rowid might collide with existing entry */
86157   int isUpdate,       /* True for UPDATE, False for INSERT */
86158   int overrideError,  /* Override onError to this if not OE_Default */
86159   int ignoreDest,     /* Jump to this label on an OE_Ignore resolution */
86160   int *pbMayReplace   /* OUT: Set to true if constraint may cause a replace */
86161 ){
86162   int i;              /* loop counter */
86163   Vdbe *v;            /* VDBE under constrution */
86164   int nCol;           /* Number of columns */
86165   int onError;        /* Conflict resolution strategy */
86166   int j1;             /* Addresss of jump instruction */
86167   int j2 = 0, j3;     /* Addresses of jump instructions */
86168   int regData;        /* Register containing first data column */
86169   int iCur;           /* Table cursor number */
86170   Index *pIdx;         /* Pointer to one of the indices */
86171   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
86172   int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
86173
86174   v = sqlite3GetVdbe(pParse);
86175   assert( v!=0 );
86176   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
86177   nCol = pTab->nCol;
86178   regData = regRowid + 1;
86179
86180   /* Test all NOT NULL constraints.
86181   */
86182   for(i=0; i<nCol; i++){
86183     if( i==pTab->iPKey ){
86184       continue;
86185     }
86186     onError = pTab->aCol[i].notNull;
86187     if( onError==OE_None ) continue;
86188     if( overrideError!=OE_Default ){
86189       onError = overrideError;
86190     }else if( onError==OE_Default ){
86191       onError = OE_Abort;
86192     }
86193     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
86194       onError = OE_Abort;
86195     }
86196     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
86197         || onError==OE_Ignore || onError==OE_Replace );
86198     switch( onError ){
86199       case OE_Abort:
86200         sqlite3MayAbort(pParse);
86201       case OE_Rollback:
86202       case OE_Fail: {
86203         char *zMsg;
86204         sqlite3VdbeAddOp3(v, OP_HaltIfNull,
86205                                   SQLITE_CONSTRAINT, onError, regData+i);
86206         zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL",
86207                               pTab->zName, pTab->aCol[i].zName);
86208         sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
86209         break;
86210       }
86211       case OE_Ignore: {
86212         sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
86213         break;
86214       }
86215       default: {
86216         assert( onError==OE_Replace );
86217         j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
86218         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
86219         sqlite3VdbeJumpHere(v, j1);
86220         break;
86221       }
86222     }
86223   }
86224
86225   /* Test all CHECK constraints
86226   */
86227 #ifndef SQLITE_OMIT_CHECK
86228   if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
86229     int allOk = sqlite3VdbeMakeLabel(v);
86230     pParse->ckBase = regData;
86231     sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
86232     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
86233     if( onError==OE_Ignore ){
86234       sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
86235     }else{
86236       if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
86237       sqlite3HaltConstraint(pParse, onError, 0, 0);
86238     }
86239     sqlite3VdbeResolveLabel(v, allOk);
86240   }
86241 #endif /* !defined(SQLITE_OMIT_CHECK) */
86242
86243   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
86244   ** of the new record does not previously exist.  Except, if this
86245   ** is an UPDATE and the primary key is not changing, that is OK.
86246   */
86247   if( rowidChng ){
86248     onError = pTab->keyConf;
86249     if( overrideError!=OE_Default ){
86250       onError = overrideError;
86251     }else if( onError==OE_Default ){
86252       onError = OE_Abort;
86253     }
86254     
86255     if( isUpdate ){
86256       j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
86257     }
86258     j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
86259     switch( onError ){
86260       default: {
86261         onError = OE_Abort;
86262         /* Fall thru into the next case */
86263       }
86264       case OE_Rollback:
86265       case OE_Abort:
86266       case OE_Fail: {
86267         sqlite3HaltConstraint(
86268           pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
86269         break;
86270       }
86271       case OE_Replace: {
86272         /* If there are DELETE triggers on this table and the
86273         ** recursive-triggers flag is set, call GenerateRowDelete() to
86274         ** remove the conflicting row from the the table. This will fire
86275         ** the triggers and remove both the table and index b-tree entries.
86276         **
86277         ** Otherwise, if there are no triggers or the recursive-triggers
86278         ** flag is not set, but the table has one or more indexes, call 
86279         ** GenerateRowIndexDelete(). This removes the index b-tree entries 
86280         ** only. The table b-tree entry will be replaced by the new entry 
86281         ** when it is inserted.  
86282         **
86283         ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
86284         ** also invoke MultiWrite() to indicate that this VDBE may require
86285         ** statement rollback (if the statement is aborted after the delete
86286         ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
86287         ** but being more selective here allows statements like:
86288         **
86289         **   REPLACE INTO t(rowid) VALUES($newrowid)
86290         **
86291         ** to run without a statement journal if there are no indexes on the
86292         ** table.
86293         */
86294         Trigger *pTrigger = 0;
86295         if( pParse->db->flags&SQLITE_RecTriggers ){
86296           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
86297         }
86298         if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
86299           sqlite3MultiWrite(pParse);
86300           sqlite3GenerateRowDelete(
86301               pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
86302           );
86303         }else if( pTab->pIndex ){
86304           sqlite3MultiWrite(pParse);
86305           sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
86306         }
86307         seenReplace = 1;
86308         break;
86309       }
86310       case OE_Ignore: {
86311         assert( seenReplace==0 );
86312         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
86313         break;
86314       }
86315     }
86316     sqlite3VdbeJumpHere(v, j3);
86317     if( isUpdate ){
86318       sqlite3VdbeJumpHere(v, j2);
86319     }
86320   }
86321
86322   /* Test all UNIQUE constraints by creating entries for each UNIQUE
86323   ** index and making sure that duplicate entries do not already exist.
86324   ** Add the new records to the indices as we go.
86325   */
86326   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
86327     int regIdx;
86328     int regR;
86329
86330     if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
86331
86332     /* Create a key for accessing the index entry */
86333     regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
86334     for(i=0; i<pIdx->nColumn; i++){
86335       int idx = pIdx->aiColumn[i];
86336       if( idx==pTab->iPKey ){
86337         sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
86338       }else{
86339         sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
86340       }
86341     }
86342     sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
86343     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
86344     sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
86345     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
86346
86347     /* Find out what action to take in case there is an indexing conflict */
86348     onError = pIdx->onError;
86349     if( onError==OE_None ){ 
86350       sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
86351       continue;  /* pIdx is not a UNIQUE index */
86352     }
86353     if( overrideError!=OE_Default ){
86354       onError = overrideError;
86355     }else if( onError==OE_Default ){
86356       onError = OE_Abort;
86357     }
86358     if( seenReplace ){
86359       if( onError==OE_Ignore ) onError = OE_Replace;
86360       else if( onError==OE_Fail ) onError = OE_Abort;
86361     }
86362     
86363     /* Check to see if the new index entry will be unique */
86364     regR = sqlite3GetTempReg(pParse);
86365     sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
86366     j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
86367                            regR, SQLITE_INT_TO_PTR(regIdx),
86368                            P4_INT32);
86369     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
86370
86371     /* Generate code that executes if the new index entry is not unique */
86372     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
86373         || onError==OE_Ignore || onError==OE_Replace );
86374     switch( onError ){
86375       case OE_Rollback:
86376       case OE_Abort:
86377       case OE_Fail: {
86378         int j;
86379         StrAccum errMsg;
86380         const char *zSep;
86381         char *zErr;
86382
86383         sqlite3StrAccumInit(&errMsg, 0, 0, 200);
86384         errMsg.db = pParse->db;
86385         zSep = pIdx->nColumn>1 ? "columns " : "column ";
86386         for(j=0; j<pIdx->nColumn; j++){
86387           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
86388           sqlite3StrAccumAppend(&errMsg, zSep, -1);
86389           zSep = ", ";
86390           sqlite3StrAccumAppend(&errMsg, zCol, -1);
86391         }
86392         sqlite3StrAccumAppend(&errMsg,
86393             pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
86394         zErr = sqlite3StrAccumFinish(&errMsg);
86395         sqlite3HaltConstraint(pParse, onError, zErr, 0);
86396         sqlite3DbFree(errMsg.db, zErr);
86397         break;
86398       }
86399       case OE_Ignore: {
86400         assert( seenReplace==0 );
86401         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
86402         break;
86403       }
86404       default: {
86405         Trigger *pTrigger = 0;
86406         assert( onError==OE_Replace );
86407         sqlite3MultiWrite(pParse);
86408         if( pParse->db->flags&SQLITE_RecTriggers ){
86409           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
86410         }
86411         sqlite3GenerateRowDelete(
86412             pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
86413         );
86414         seenReplace = 1;
86415         break;
86416       }
86417     }
86418     sqlite3VdbeJumpHere(v, j3);
86419     sqlite3ReleaseTempReg(pParse, regR);
86420   }
86421   
86422   if( pbMayReplace ){
86423     *pbMayReplace = seenReplace;
86424   }
86425 }
86426
86427 /*
86428 ** This routine generates code to finish the INSERT or UPDATE operation
86429 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
86430 ** A consecutive range of registers starting at regRowid contains the
86431 ** rowid and the content to be inserted.
86432 **
86433 ** The arguments to this routine should be the same as the first six
86434 ** arguments to sqlite3GenerateConstraintChecks.
86435 */
86436 SQLITE_PRIVATE void sqlite3CompleteInsertion(
86437   Parse *pParse,      /* The parser context */
86438   Table *pTab,        /* the table into which we are inserting */
86439   int baseCur,        /* Index of a read/write cursor pointing at pTab */
86440   int regRowid,       /* Range of content */
86441   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
86442   int isUpdate,       /* True for UPDATE, False for INSERT */
86443   int appendBias,     /* True if this is likely to be an append */
86444   int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
86445 ){
86446   int i;
86447   Vdbe *v;
86448   int nIdx;
86449   Index *pIdx;
86450   u8 pik_flags;
86451   int regData;
86452   int regRec;
86453
86454   v = sqlite3GetVdbe(pParse);
86455   assert( v!=0 );
86456   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
86457   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
86458   for(i=nIdx-1; i>=0; i--){
86459     if( aRegIdx[i]==0 ) continue;
86460     sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
86461     if( useSeekResult ){
86462       sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
86463     }
86464   }
86465   regData = regRowid + 1;
86466   regRec = sqlite3GetTempReg(pParse);
86467   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
86468   sqlite3TableAffinityStr(v, pTab);
86469   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
86470   if( pParse->nested ){
86471     pik_flags = 0;
86472   }else{
86473     pik_flags = OPFLAG_NCHANGE;
86474     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
86475   }
86476   if( appendBias ){
86477     pik_flags |= OPFLAG_APPEND;
86478   }
86479   if( useSeekResult ){
86480     pik_flags |= OPFLAG_USESEEKRESULT;
86481   }
86482   sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
86483   if( !pParse->nested ){
86484     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
86485   }
86486   sqlite3VdbeChangeP5(v, pik_flags);
86487 }
86488
86489 /*
86490 ** Generate code that will open cursors for a table and for all
86491 ** indices of that table.  The "baseCur" parameter is the cursor number used
86492 ** for the table.  Indices are opened on subsequent cursors.
86493 **
86494 ** Return the number of indices on the table.
86495 */
86496 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
86497   Parse *pParse,   /* Parsing context */
86498   Table *pTab,     /* Table to be opened */
86499   int baseCur,     /* Cursor number assigned to the table */
86500   int op           /* OP_OpenRead or OP_OpenWrite */
86501 ){
86502   int i;
86503   int iDb;
86504   Index *pIdx;
86505   Vdbe *v;
86506
86507   if( IsVirtual(pTab) ) return 0;
86508   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
86509   v = sqlite3GetVdbe(pParse);
86510   assert( v!=0 );
86511   sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
86512   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
86513     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
86514     assert( pIdx->pSchema==pTab->pSchema );
86515     sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
86516                       (char*)pKey, P4_KEYINFO_HANDOFF);
86517     VdbeComment((v, "%s", pIdx->zName));
86518   }
86519   if( pParse->nTab<baseCur+i ){
86520     pParse->nTab = baseCur+i;
86521   }
86522   return i-1;
86523 }
86524
86525
86526 #ifdef SQLITE_TEST
86527 /*
86528 ** The following global variable is incremented whenever the
86529 ** transfer optimization is used.  This is used for testing
86530 ** purposes only - to make sure the transfer optimization really
86531 ** is happening when it is suppose to.
86532 */
86533 SQLITE_API int sqlite3_xferopt_count;
86534 #endif /* SQLITE_TEST */
86535
86536
86537 #ifndef SQLITE_OMIT_XFER_OPT
86538 /*
86539 ** Check to collation names to see if they are compatible.
86540 */
86541 static int xferCompatibleCollation(const char *z1, const char *z2){
86542   if( z1==0 ){
86543     return z2==0;
86544   }
86545   if( z2==0 ){
86546     return 0;
86547   }
86548   return sqlite3StrICmp(z1, z2)==0;
86549 }
86550
86551
86552 /*
86553 ** Check to see if index pSrc is compatible as a source of data
86554 ** for index pDest in an insert transfer optimization.  The rules
86555 ** for a compatible index:
86556 **
86557 **    *   The index is over the same set of columns
86558 **    *   The same DESC and ASC markings occurs on all columns
86559 **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
86560 **    *   The same collating sequence on each column
86561 */
86562 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
86563   int i;
86564   assert( pDest && pSrc );
86565   assert( pDest->pTable!=pSrc->pTable );
86566   if( pDest->nColumn!=pSrc->nColumn ){
86567     return 0;   /* Different number of columns */
86568   }
86569   if( pDest->onError!=pSrc->onError ){
86570     return 0;   /* Different conflict resolution strategies */
86571   }
86572   for(i=0; i<pSrc->nColumn; i++){
86573     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
86574       return 0;   /* Different columns indexed */
86575     }
86576     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
86577       return 0;   /* Different sort orders */
86578     }
86579     if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
86580       return 0;   /* Different collating sequences */
86581     }
86582   }
86583
86584   /* If no test above fails then the indices must be compatible */
86585   return 1;
86586 }
86587
86588 /*
86589 ** Attempt the transfer optimization on INSERTs of the form
86590 **
86591 **     INSERT INTO tab1 SELECT * FROM tab2;
86592 **
86593 ** This optimization is only attempted if
86594 **
86595 **    (1)  tab1 and tab2 have identical schemas including all the
86596 **         same indices and constraints
86597 **
86598 **    (2)  tab1 and tab2 are different tables
86599 **
86600 **    (3)  There must be no triggers on tab1
86601 **
86602 **    (4)  The result set of the SELECT statement is "*"
86603 **
86604 **    (5)  The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
86605 **         or LIMIT clause.
86606 **
86607 **    (6)  The SELECT statement is a simple (not a compound) select that
86608 **         contains only tab2 in its FROM clause
86609 **
86610 ** This method for implementing the INSERT transfers raw records from
86611 ** tab2 over to tab1.  The columns are not decoded.  Raw records from
86612 ** the indices of tab2 are transfered to tab1 as well.  In so doing,
86613 ** the resulting tab1 has much less fragmentation.
86614 **
86615 ** This routine returns TRUE if the optimization is attempted.  If any
86616 ** of the conditions above fail so that the optimization should not
86617 ** be attempted, then this routine returns FALSE.
86618 */
86619 static int xferOptimization(
86620   Parse *pParse,        /* Parser context */
86621   Table *pDest,         /* The table we are inserting into */
86622   Select *pSelect,      /* A SELECT statement to use as the data source */
86623   int onError,          /* How to handle constraint errors */
86624   int iDbDest           /* The database of pDest */
86625 ){
86626   ExprList *pEList;                /* The result set of the SELECT */
86627   Table *pSrc;                     /* The table in the FROM clause of SELECT */
86628   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
86629   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
86630   int i;                           /* Loop counter */
86631   int iDbSrc;                      /* The database of pSrc */
86632   int iSrc, iDest;                 /* Cursors from source and destination */
86633   int addr1, addr2;                /* Loop addresses */
86634   int emptyDestTest;               /* Address of test for empty pDest */
86635   int emptySrcTest;                /* Address of test for empty pSrc */
86636   Vdbe *v;                         /* The VDBE we are building */
86637   KeyInfo *pKey;                   /* Key information for an index */
86638   int regAutoinc;                  /* Memory register used by AUTOINC */
86639   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
86640   int regData, regRowid;           /* Registers holding data and rowid */
86641
86642   if( pSelect==0 ){
86643     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
86644   }
86645   if( sqlite3TriggerList(pParse, pDest) ){
86646     return 0;   /* tab1 must not have triggers */
86647   }
86648 #ifndef SQLITE_OMIT_VIRTUALTABLE
86649   if( pDest->tabFlags & TF_Virtual ){
86650     return 0;   /* tab1 must not be a virtual table */
86651   }
86652 #endif
86653   if( onError==OE_Default ){
86654     onError = OE_Abort;
86655   }
86656   if( onError!=OE_Abort && onError!=OE_Rollback ){
86657     return 0;   /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
86658   }
86659   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
86660   if( pSelect->pSrc->nSrc!=1 ){
86661     return 0;   /* FROM clause must have exactly one term */
86662   }
86663   if( pSelect->pSrc->a[0].pSelect ){
86664     return 0;   /* FROM clause cannot contain a subquery */
86665   }
86666   if( pSelect->pWhere ){
86667     return 0;   /* SELECT may not have a WHERE clause */
86668   }
86669   if( pSelect->pOrderBy ){
86670     return 0;   /* SELECT may not have an ORDER BY clause */
86671   }
86672   /* Do not need to test for a HAVING clause.  If HAVING is present but
86673   ** there is no ORDER BY, we will get an error. */
86674   if( pSelect->pGroupBy ){
86675     return 0;   /* SELECT may not have a GROUP BY clause */
86676   }
86677   if( pSelect->pLimit ){
86678     return 0;   /* SELECT may not have a LIMIT clause */
86679   }
86680   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
86681   if( pSelect->pPrior ){
86682     return 0;   /* SELECT may not be a compound query */
86683   }
86684   if( pSelect->selFlags & SF_Distinct ){
86685     return 0;   /* SELECT may not be DISTINCT */
86686   }
86687   pEList = pSelect->pEList;
86688   assert( pEList!=0 );
86689   if( pEList->nExpr!=1 ){
86690     return 0;   /* The result set must have exactly one column */
86691   }
86692   assert( pEList->a[0].pExpr );
86693   if( pEList->a[0].pExpr->op!=TK_ALL ){
86694     return 0;   /* The result set must be the special operator "*" */
86695   }
86696
86697   /* At this point we have established that the statement is of the
86698   ** correct syntactic form to participate in this optimization.  Now
86699   ** we have to check the semantics.
86700   */
86701   pItem = pSelect->pSrc->a;
86702   pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
86703   if( pSrc==0 ){
86704     return 0;   /* FROM clause does not contain a real table */
86705   }
86706   if( pSrc==pDest ){
86707     return 0;   /* tab1 and tab2 may not be the same table */
86708   }
86709 #ifndef SQLITE_OMIT_VIRTUALTABLE
86710   if( pSrc->tabFlags & TF_Virtual ){
86711     return 0;   /* tab2 must not be a virtual table */
86712   }
86713 #endif
86714   if( pSrc->pSelect ){
86715     return 0;   /* tab2 may not be a view */
86716   }
86717   if( pDest->nCol!=pSrc->nCol ){
86718     return 0;   /* Number of columns must be the same in tab1 and tab2 */
86719   }
86720   if( pDest->iPKey!=pSrc->iPKey ){
86721     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
86722   }
86723   for(i=0; i<pDest->nCol; i++){
86724     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
86725       return 0;    /* Affinity must be the same on all columns */
86726     }
86727     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
86728       return 0;    /* Collating sequence must be the same on all columns */
86729     }
86730     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
86731       return 0;    /* tab2 must be NOT NULL if tab1 is */
86732     }
86733   }
86734   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
86735     if( pDestIdx->onError!=OE_None ){
86736       destHasUniqueIdx = 1;
86737     }
86738     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
86739       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
86740     }
86741     if( pSrcIdx==0 ){
86742       return 0;    /* pDestIdx has no corresponding index in pSrc */
86743     }
86744   }
86745 #ifndef SQLITE_OMIT_CHECK
86746   if( pDest->pCheck && sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
86747     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
86748   }
86749 #endif
86750 #ifndef SQLITE_OMIT_FOREIGN_KEY
86751   /* Disallow the transfer optimization if the destination table constains
86752   ** any foreign key constraints.  This is more restrictive than necessary.
86753   ** But the main beneficiary of the transfer optimization is the VACUUM 
86754   ** command, and the VACUUM command disables foreign key constraints.  So
86755   ** the extra complication to make this rule less restrictive is probably
86756   ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
86757   */
86758   if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
86759     return 0;
86760   }
86761 #endif
86762
86763   /* If we get this far, it means either:
86764   **
86765   **    *   We can always do the transfer if the table contains an
86766   **        an integer primary key
86767   **
86768   **    *   We can conditionally do the transfer if the destination
86769   **        table is empty.
86770   */
86771 #ifdef SQLITE_TEST
86772   sqlite3_xferopt_count++;
86773 #endif
86774   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
86775   v = sqlite3GetVdbe(pParse);
86776   sqlite3CodeVerifySchema(pParse, iDbSrc);
86777   iSrc = pParse->nTab++;
86778   iDest = pParse->nTab++;
86779   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
86780   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
86781   if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
86782     /* If tables do not have an INTEGER PRIMARY KEY and there
86783     ** are indices to be copied and the destination is not empty,
86784     ** we have to disallow the transfer optimization because the
86785     ** the rowids might change which will mess up indexing.
86786     **
86787     ** Or if the destination has a UNIQUE index and is not empty,
86788     ** we also disallow the transfer optimization because we cannot
86789     ** insure that all entries in the union of DEST and SRC will be
86790     ** unique.
86791     */
86792     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
86793     emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
86794     sqlite3VdbeJumpHere(v, addr1);
86795   }else{
86796     emptyDestTest = 0;
86797   }
86798   sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
86799   emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
86800   regData = sqlite3GetTempReg(pParse);
86801   regRowid = sqlite3GetTempReg(pParse);
86802   if( pDest->iPKey>=0 ){
86803     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
86804     addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
86805     sqlite3HaltConstraint(
86806         pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
86807     sqlite3VdbeJumpHere(v, addr2);
86808     autoIncStep(pParse, regAutoinc, regRowid);
86809   }else if( pDest->pIndex==0 ){
86810     addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
86811   }else{
86812     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
86813     assert( (pDest->tabFlags & TF_Autoincrement)==0 );
86814   }
86815   sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
86816   sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
86817   sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
86818   sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
86819   sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
86820   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
86821     for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
86822       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
86823     }
86824     assert( pSrcIdx );
86825     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
86826     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
86827     pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
86828     sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
86829                       (char*)pKey, P4_KEYINFO_HANDOFF);
86830     VdbeComment((v, "%s", pSrcIdx->zName));
86831     pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
86832     sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
86833                       (char*)pKey, P4_KEYINFO_HANDOFF);
86834     VdbeComment((v, "%s", pDestIdx->zName));
86835     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
86836     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
86837     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
86838     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
86839     sqlite3VdbeJumpHere(v, addr1);
86840   }
86841   sqlite3VdbeJumpHere(v, emptySrcTest);
86842   sqlite3ReleaseTempReg(pParse, regRowid);
86843   sqlite3ReleaseTempReg(pParse, regData);
86844   sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
86845   sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
86846   if( emptyDestTest ){
86847     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
86848     sqlite3VdbeJumpHere(v, emptyDestTest);
86849     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
86850     return 0;
86851   }else{
86852     return 1;
86853   }
86854 }
86855 #endif /* SQLITE_OMIT_XFER_OPT */
86856
86857 /************** End of insert.c **********************************************/
86858 /************** Begin file legacy.c ******************************************/
86859 /*
86860 ** 2001 September 15
86861 **
86862 ** The author disclaims copyright to this source code.  In place of
86863 ** a legal notice, here is a blessing:
86864 **
86865 **    May you do good and not evil.
86866 **    May you find forgiveness for yourself and forgive others.
86867 **    May you share freely, never taking more than you give.
86868 **
86869 *************************************************************************
86870 ** Main file for the SQLite library.  The routines in this file
86871 ** implement the programmer interface to the library.  Routines in
86872 ** other files are for internal use by SQLite and should not be
86873 ** accessed by users of the library.
86874 */
86875
86876
86877 /*
86878 ** Execute SQL code.  Return one of the SQLITE_ success/failure
86879 ** codes.  Also write an error message into memory obtained from
86880 ** malloc() and make *pzErrMsg point to that message.
86881 **
86882 ** If the SQL is a query, then for each row in the query result
86883 ** the xCallback() function is called.  pArg becomes the first
86884 ** argument to xCallback().  If xCallback=NULL then no callback
86885 ** is invoked, even for queries.
86886 */
86887 SQLITE_API int sqlite3_exec(
86888   sqlite3 *db,                /* The database on which the SQL executes */
86889   const char *zSql,           /* The SQL to be executed */
86890   sqlite3_callback xCallback, /* Invoke this callback routine */
86891   void *pArg,                 /* First argument to xCallback() */
86892   char **pzErrMsg             /* Write error messages here */
86893 ){
86894   int rc = SQLITE_OK;         /* Return code */
86895   const char *zLeftover;      /* Tail of unprocessed SQL */
86896   sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
86897   char **azCols = 0;          /* Names of result columns */
86898   int nRetry = 0;             /* Number of retry attempts */
86899   int callbackIsInit;         /* True if callback data is initialized */
86900
86901   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
86902   if( zSql==0 ) zSql = "";
86903
86904   sqlite3_mutex_enter(db->mutex);
86905   sqlite3Error(db, SQLITE_OK, 0);
86906   while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
86907     int nCol;
86908     char **azVals = 0;
86909
86910     pStmt = 0;
86911     rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);
86912     assert( rc==SQLITE_OK || pStmt==0 );
86913     if( rc!=SQLITE_OK ){
86914       continue;
86915     }
86916     if( !pStmt ){
86917       /* this happens for a comment or white-space */
86918       zSql = zLeftover;
86919       continue;
86920     }
86921
86922     callbackIsInit = 0;
86923     nCol = sqlite3_column_count(pStmt);
86924
86925     while( 1 ){
86926       int i;
86927       rc = sqlite3_step(pStmt);
86928
86929       /* Invoke the callback function if required */
86930       if( xCallback && (SQLITE_ROW==rc || 
86931           (SQLITE_DONE==rc && !callbackIsInit
86932                            && db->flags&SQLITE_NullCallback)) ){
86933         if( !callbackIsInit ){
86934           azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
86935           if( azCols==0 ){
86936             goto exec_out;
86937           }
86938           for(i=0; i<nCol; i++){
86939             azCols[i] = (char *)sqlite3_column_name(pStmt, i);
86940             /* sqlite3VdbeSetColName() installs column names as UTF8
86941             ** strings so there is no way for sqlite3_column_name() to fail. */
86942             assert( azCols[i]!=0 );
86943           }
86944           callbackIsInit = 1;
86945         }
86946         if( rc==SQLITE_ROW ){
86947           azVals = &azCols[nCol];
86948           for(i=0; i<nCol; i++){
86949             azVals[i] = (char *)sqlite3_column_text(pStmt, i);
86950             if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
86951               db->mallocFailed = 1;
86952               goto exec_out;
86953             }
86954           }
86955         }
86956         if( xCallback(pArg, nCol, azVals, azCols) ){
86957           rc = SQLITE_ABORT;
86958           sqlite3VdbeFinalize((Vdbe *)pStmt);
86959           pStmt = 0;
86960           sqlite3Error(db, SQLITE_ABORT, 0);
86961           goto exec_out;
86962         }
86963       }
86964
86965       if( rc!=SQLITE_ROW ){
86966         rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
86967         pStmt = 0;
86968         if( rc!=SQLITE_SCHEMA ){
86969           nRetry = 0;
86970           zSql = zLeftover;
86971           while( sqlite3Isspace(zSql[0]) ) zSql++;
86972         }
86973         break;
86974       }
86975     }
86976
86977     sqlite3DbFree(db, azCols);
86978     azCols = 0;
86979   }
86980
86981 exec_out:
86982   if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
86983   sqlite3DbFree(db, azCols);
86984
86985   rc = sqlite3ApiExit(db, rc);
86986   if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
86987     int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
86988     *pzErrMsg = sqlite3Malloc(nErrMsg);
86989     if( *pzErrMsg ){
86990       memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
86991     }else{
86992       rc = SQLITE_NOMEM;
86993       sqlite3Error(db, SQLITE_NOMEM, 0);
86994     }
86995   }else if( pzErrMsg ){
86996     *pzErrMsg = 0;
86997   }
86998
86999   assert( (rc&db->errMask)==rc );
87000   sqlite3_mutex_leave(db->mutex);
87001   return rc;
87002 }
87003
87004 /************** End of legacy.c **********************************************/
87005 /************** Begin file loadext.c *****************************************/
87006 /*
87007 ** 2006 June 7
87008 **
87009 ** The author disclaims copyright to this source code.  In place of
87010 ** a legal notice, here is a blessing:
87011 **
87012 **    May you do good and not evil.
87013 **    May you find forgiveness for yourself and forgive others.
87014 **    May you share freely, never taking more than you give.
87015 **
87016 *************************************************************************
87017 ** This file contains code used to dynamically load extensions into
87018 ** the SQLite library.
87019 */
87020
87021 #ifndef SQLITE_CORE
87022   #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
87023 #endif
87024 /************** Include sqlite3ext.h in the middle of loadext.c **************/
87025 /************** Begin file sqlite3ext.h **************************************/
87026 /*
87027 ** 2006 June 7
87028 **
87029 ** The author disclaims copyright to this source code.  In place of
87030 ** a legal notice, here is a blessing:
87031 **
87032 **    May you do good and not evil.
87033 **    May you find forgiveness for yourself and forgive others.
87034 **    May you share freely, never taking more than you give.
87035 **
87036 *************************************************************************
87037 ** This header file defines the SQLite interface for use by
87038 ** shared libraries that want to be imported as extensions into
87039 ** an SQLite instance.  Shared libraries that intend to be loaded
87040 ** as extensions by SQLite should #include this file instead of 
87041 ** sqlite3.h.
87042 */
87043 #ifndef _SQLITE3EXT_H_
87044 #define _SQLITE3EXT_H_
87045
87046 typedef struct sqlite3_api_routines sqlite3_api_routines;
87047
87048 /*
87049 ** The following structure holds pointers to all of the SQLite API
87050 ** routines.
87051 **
87052 ** WARNING:  In order to maintain backwards compatibility, add new
87053 ** interfaces to the end of this structure only.  If you insert new
87054 ** interfaces in the middle of this structure, then older different
87055 ** versions of SQLite will not be able to load each others' shared
87056 ** libraries!
87057 */
87058 struct sqlite3_api_routines {
87059   void * (*aggregate_context)(sqlite3_context*,int nBytes);
87060   int  (*aggregate_count)(sqlite3_context*);
87061   int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
87062   int  (*bind_double)(sqlite3_stmt*,int,double);
87063   int  (*bind_int)(sqlite3_stmt*,int,int);
87064   int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
87065   int  (*bind_null)(sqlite3_stmt*,int);
87066   int  (*bind_parameter_count)(sqlite3_stmt*);
87067   int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
87068   const char * (*bind_parameter_name)(sqlite3_stmt*,int);
87069   int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
87070   int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
87071   int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
87072   int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
87073   int  (*busy_timeout)(sqlite3*,int ms);
87074   int  (*changes)(sqlite3*);
87075   int  (*close)(sqlite3*);
87076   int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const char*));
87077   int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const void*));
87078   const void * (*column_blob)(sqlite3_stmt*,int iCol);
87079   int  (*column_bytes)(sqlite3_stmt*,int iCol);
87080   int  (*column_bytes16)(sqlite3_stmt*,int iCol);
87081   int  (*column_count)(sqlite3_stmt*pStmt);
87082   const char * (*column_database_name)(sqlite3_stmt*,int);
87083   const void * (*column_database_name16)(sqlite3_stmt*,int);
87084   const char * (*column_decltype)(sqlite3_stmt*,int i);
87085   const void * (*column_decltype16)(sqlite3_stmt*,int);
87086   double  (*column_double)(sqlite3_stmt*,int iCol);
87087   int  (*column_int)(sqlite3_stmt*,int iCol);
87088   sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
87089   const char * (*column_name)(sqlite3_stmt*,int);
87090   const void * (*column_name16)(sqlite3_stmt*,int);
87091   const char * (*column_origin_name)(sqlite3_stmt*,int);
87092   const void * (*column_origin_name16)(sqlite3_stmt*,int);
87093   const char * (*column_table_name)(sqlite3_stmt*,int);
87094   const void * (*column_table_name16)(sqlite3_stmt*,int);
87095   const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
87096   const void * (*column_text16)(sqlite3_stmt*,int iCol);
87097   int  (*column_type)(sqlite3_stmt*,int iCol);
87098   sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
87099   void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
87100   int  (*complete)(const char*sql);
87101   int  (*complete16)(const void*sql);
87102   int  (*create_collation)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*));
87103   int  (*create_collation16)(sqlite3*,const void*,int,void*,int(*)(void*,int,const void*,int,const void*));
87104   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*));
87105   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*));
87106   int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
87107   int  (*data_count)(sqlite3_stmt*pStmt);
87108   sqlite3 * (*db_handle)(sqlite3_stmt*);
87109   int (*declare_vtab)(sqlite3*,const char*);
87110   int  (*enable_shared_cache)(int);
87111   int  (*errcode)(sqlite3*db);
87112   const char * (*errmsg)(sqlite3*);
87113   const void * (*errmsg16)(sqlite3*);
87114   int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
87115   int  (*expired)(sqlite3_stmt*);
87116   int  (*finalize)(sqlite3_stmt*pStmt);
87117   void  (*free)(void*);
87118   void  (*free_table)(char**result);
87119   int  (*get_autocommit)(sqlite3*);
87120   void * (*get_auxdata)(sqlite3_context*,int);
87121   int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
87122   int  (*global_recover)(void);
87123   void  (*interruptx)(sqlite3*);
87124   sqlite_int64  (*last_insert_rowid)(sqlite3*);
87125   const char * (*libversion)(void);
87126   int  (*libversion_number)(void);
87127   void *(*malloc)(int);
87128   char * (*mprintf)(const char*,...);
87129   int  (*open)(const char*,sqlite3**);
87130   int  (*open16)(const void*,sqlite3**);
87131   int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
87132   int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
87133   void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
87134   void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
87135   void *(*realloc)(void*,int);
87136   int  (*reset)(sqlite3_stmt*pStmt);
87137   void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
87138   void  (*result_double)(sqlite3_context*,double);
87139   void  (*result_error)(sqlite3_context*,const char*,int);
87140   void  (*result_error16)(sqlite3_context*,const void*,int);
87141   void  (*result_int)(sqlite3_context*,int);
87142   void  (*result_int64)(sqlite3_context*,sqlite_int64);
87143   void  (*result_null)(sqlite3_context*);
87144   void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
87145   void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
87146   void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
87147   void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
87148   void  (*result_value)(sqlite3_context*,sqlite3_value*);
87149   void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
87150   int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,const char*,const char*),void*);
87151   void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
87152   char * (*snprintf)(int,char*,const char*,...);
87153   int  (*step)(sqlite3_stmt*);
87154   int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,char const**,char const**,int*,int*,int*);
87155   void  (*thread_cleanup)(void);
87156   int  (*total_changes)(sqlite3*);
87157   void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
87158   int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
87159   void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,sqlite_int64),void*);
87160   void * (*user_data)(sqlite3_context*);
87161   const void * (*value_blob)(sqlite3_value*);
87162   int  (*value_bytes)(sqlite3_value*);
87163   int  (*value_bytes16)(sqlite3_value*);
87164   double  (*value_double)(sqlite3_value*);
87165   int  (*value_int)(sqlite3_value*);
87166   sqlite_int64  (*value_int64)(sqlite3_value*);
87167   int  (*value_numeric_type)(sqlite3_value*);
87168   const unsigned char * (*value_text)(sqlite3_value*);
87169   const void * (*value_text16)(sqlite3_value*);
87170   const void * (*value_text16be)(sqlite3_value*);
87171   const void * (*value_text16le)(sqlite3_value*);
87172   int  (*value_type)(sqlite3_value*);
87173   char *(*vmprintf)(const char*,va_list);
87174   /* Added ??? */
87175   int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
87176   /* Added by 3.3.13 */
87177   int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
87178   int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
87179   int (*clear_bindings)(sqlite3_stmt*);
87180   /* Added by 3.4.1 */
87181   int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,void (*xDestroy)(void *));
87182   /* Added by 3.5.0 */
87183   int (*bind_zeroblob)(sqlite3_stmt*,int,int);
87184   int (*blob_bytes)(sqlite3_blob*);
87185   int (*blob_close)(sqlite3_blob*);
87186   int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,int,sqlite3_blob**);
87187   int (*blob_read)(sqlite3_blob*,void*,int,int);
87188   int (*blob_write)(sqlite3_blob*,const void*,int,int);
87189   int (*create_collation_v2)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*),void(*)(void*));
87190   int (*file_control)(sqlite3*,const char*,int,void*);
87191   sqlite3_int64 (*memory_highwater)(int);
87192   sqlite3_int64 (*memory_used)(void);
87193   sqlite3_mutex *(*mutex_alloc)(int);
87194   void (*mutex_enter)(sqlite3_mutex*);
87195   void (*mutex_free)(sqlite3_mutex*);
87196   void (*mutex_leave)(sqlite3_mutex*);
87197   int (*mutex_try)(sqlite3_mutex*);
87198   int (*open_v2)(const char*,sqlite3**,int,const char*);
87199   int (*release_memory)(int);
87200   void (*result_error_nomem)(sqlite3_context*);
87201   void (*result_error_toobig)(sqlite3_context*);
87202   int (*sleep)(int);
87203   void (*soft_heap_limit)(int);
87204   sqlite3_vfs *(*vfs_find)(const char*);
87205   int (*vfs_register)(sqlite3_vfs*,int);
87206   int (*vfs_unregister)(sqlite3_vfs*);
87207   int (*xthreadsafe)(void);
87208   void (*result_zeroblob)(sqlite3_context*,int);
87209   void (*result_error_code)(sqlite3_context*,int);
87210   int (*test_control)(int, ...);
87211   void (*randomness)(int,void*);
87212   sqlite3 *(*context_db_handle)(sqlite3_context*);
87213   int (*extended_result_codes)(sqlite3*,int);
87214   int (*limit)(sqlite3*,int,int);
87215   sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
87216   const char *(*sql)(sqlite3_stmt*);
87217   int (*status)(int,int*,int*,int);
87218   int (*backup_finish)(sqlite3_backup*);
87219   sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
87220   int (*backup_pagecount)(sqlite3_backup*);
87221   int (*backup_remaining)(sqlite3_backup*);
87222   int (*backup_step)(sqlite3_backup*,int);
87223   const char *(*compileoption_get)(int);
87224   int (*compileoption_used)(const char*);
87225   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*));
87226   int (*db_config)(sqlite3*,int,...);
87227   sqlite3_mutex *(*db_mutex)(sqlite3*);
87228   int (*db_status)(sqlite3*,int,int*,int*,int);
87229   int (*extended_errcode)(sqlite3*);
87230   void (*log)(int,const char*,...);
87231   sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
87232   const char *(*sourceid)(void);
87233   int (*stmt_status)(sqlite3_stmt*,int,int);
87234   int (*strnicmp)(const char*,const char*,int);
87235   int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
87236   int (*wal_autocheckpoint)(sqlite3*,int);
87237   int (*wal_checkpoint)(sqlite3*,const char*);
87238   void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
87239 };
87240
87241 /*
87242 ** The following macros redefine the API routines so that they are
87243 ** redirected throught the global sqlite3_api structure.
87244 **
87245 ** This header file is also used by the loadext.c source file
87246 ** (part of the main SQLite library - not an extension) so that
87247 ** it can get access to the sqlite3_api_routines structure
87248 ** definition.  But the main library does not want to redefine
87249 ** the API.  So the redefinition macros are only valid if the
87250 ** SQLITE_CORE macros is undefined.
87251 */
87252 #ifndef SQLITE_CORE
87253 #define sqlite3_aggregate_context      sqlite3_api->aggregate_context
87254 #ifndef SQLITE_OMIT_DEPRECATED
87255 #define sqlite3_aggregate_count        sqlite3_api->aggregate_count
87256 #endif
87257 #define sqlite3_bind_blob              sqlite3_api->bind_blob
87258 #define sqlite3_bind_double            sqlite3_api->bind_double
87259 #define sqlite3_bind_int               sqlite3_api->bind_int
87260 #define sqlite3_bind_int64             sqlite3_api->bind_int64
87261 #define sqlite3_bind_null              sqlite3_api->bind_null
87262 #define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
87263 #define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
87264 #define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
87265 #define sqlite3_bind_text              sqlite3_api->bind_text
87266 #define sqlite3_bind_text16            sqlite3_api->bind_text16
87267 #define sqlite3_bind_value             sqlite3_api->bind_value
87268 #define sqlite3_busy_handler           sqlite3_api->busy_handler
87269 #define sqlite3_busy_timeout           sqlite3_api->busy_timeout
87270 #define sqlite3_changes                sqlite3_api->changes
87271 #define sqlite3_close                  sqlite3_api->close
87272 #define sqlite3_collation_needed       sqlite3_api->collation_needed
87273 #define sqlite3_collation_needed16     sqlite3_api->collation_needed16
87274 #define sqlite3_column_blob            sqlite3_api->column_blob
87275 #define sqlite3_column_bytes           sqlite3_api->column_bytes
87276 #define sqlite3_column_bytes16         sqlite3_api->column_bytes16
87277 #define sqlite3_column_count           sqlite3_api->column_count
87278 #define sqlite3_column_database_name   sqlite3_api->column_database_name
87279 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
87280 #define sqlite3_column_decltype        sqlite3_api->column_decltype
87281 #define sqlite3_column_decltype16      sqlite3_api->column_decltype16
87282 #define sqlite3_column_double          sqlite3_api->column_double
87283 #define sqlite3_column_int             sqlite3_api->column_int
87284 #define sqlite3_column_int64           sqlite3_api->column_int64
87285 #define sqlite3_column_name            sqlite3_api->column_name
87286 #define sqlite3_column_name16          sqlite3_api->column_name16
87287 #define sqlite3_column_origin_name     sqlite3_api->column_origin_name
87288 #define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
87289 #define sqlite3_column_table_name      sqlite3_api->column_table_name
87290 #define sqlite3_column_table_name16    sqlite3_api->column_table_name16
87291 #define sqlite3_column_text            sqlite3_api->column_text
87292 #define sqlite3_column_text16          sqlite3_api->column_text16
87293 #define sqlite3_column_type            sqlite3_api->column_type
87294 #define sqlite3_column_value           sqlite3_api->column_value
87295 #define sqlite3_commit_hook            sqlite3_api->commit_hook
87296 #define sqlite3_complete               sqlite3_api->complete
87297 #define sqlite3_complete16             sqlite3_api->complete16
87298 #define sqlite3_create_collation       sqlite3_api->create_collation
87299 #define sqlite3_create_collation16     sqlite3_api->create_collation16
87300 #define sqlite3_create_function        sqlite3_api->create_function
87301 #define sqlite3_create_function16      sqlite3_api->create_function16
87302 #define sqlite3_create_module          sqlite3_api->create_module
87303 #define sqlite3_create_module_v2       sqlite3_api->create_module_v2
87304 #define sqlite3_data_count             sqlite3_api->data_count
87305 #define sqlite3_db_handle              sqlite3_api->db_handle
87306 #define sqlite3_declare_vtab           sqlite3_api->declare_vtab
87307 #define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
87308 #define sqlite3_errcode                sqlite3_api->errcode
87309 #define sqlite3_errmsg                 sqlite3_api->errmsg
87310 #define sqlite3_errmsg16               sqlite3_api->errmsg16
87311 #define sqlite3_exec                   sqlite3_api->exec
87312 #ifndef SQLITE_OMIT_DEPRECATED
87313 #define sqlite3_expired                sqlite3_api->expired
87314 #endif
87315 #define sqlite3_finalize               sqlite3_api->finalize
87316 #define sqlite3_free                   sqlite3_api->free
87317 #define sqlite3_free_table             sqlite3_api->free_table
87318 #define sqlite3_get_autocommit         sqlite3_api->get_autocommit
87319 #define sqlite3_get_auxdata            sqlite3_api->get_auxdata
87320 #define sqlite3_get_table              sqlite3_api->get_table
87321 #ifndef SQLITE_OMIT_DEPRECATED
87322 #define sqlite3_global_recover         sqlite3_api->global_recover
87323 #endif
87324 #define sqlite3_interrupt              sqlite3_api->interruptx
87325 #define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
87326 #define sqlite3_libversion             sqlite3_api->libversion
87327 #define sqlite3_libversion_number      sqlite3_api->libversion_number
87328 #define sqlite3_malloc                 sqlite3_api->malloc
87329 #define sqlite3_mprintf                sqlite3_api->mprintf
87330 #define sqlite3_open                   sqlite3_api->open
87331 #define sqlite3_open16                 sqlite3_api->open16
87332 #define sqlite3_prepare                sqlite3_api->prepare
87333 #define sqlite3_prepare16              sqlite3_api->prepare16
87334 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
87335 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
87336 #define sqlite3_profile                sqlite3_api->profile
87337 #define sqlite3_progress_handler       sqlite3_api->progress_handler
87338 #define sqlite3_realloc                sqlite3_api->realloc
87339 #define sqlite3_reset                  sqlite3_api->reset
87340 #define sqlite3_result_blob            sqlite3_api->result_blob
87341 #define sqlite3_result_double          sqlite3_api->result_double
87342 #define sqlite3_result_error           sqlite3_api->result_error
87343 #define sqlite3_result_error16         sqlite3_api->result_error16
87344 #define sqlite3_result_int             sqlite3_api->result_int
87345 #define sqlite3_result_int64           sqlite3_api->result_int64
87346 #define sqlite3_result_null            sqlite3_api->result_null
87347 #define sqlite3_result_text            sqlite3_api->result_text
87348 #define sqlite3_result_text16          sqlite3_api->result_text16
87349 #define sqlite3_result_text16be        sqlite3_api->result_text16be
87350 #define sqlite3_result_text16le        sqlite3_api->result_text16le
87351 #define sqlite3_result_value           sqlite3_api->result_value
87352 #define sqlite3_rollback_hook          sqlite3_api->rollback_hook
87353 #define sqlite3_set_authorizer         sqlite3_api->set_authorizer
87354 #define sqlite3_set_auxdata            sqlite3_api->set_auxdata
87355 #define sqlite3_snprintf               sqlite3_api->snprintf
87356 #define sqlite3_step                   sqlite3_api->step
87357 #define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
87358 #define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
87359 #define sqlite3_total_changes          sqlite3_api->total_changes
87360 #define sqlite3_trace                  sqlite3_api->trace
87361 #ifndef SQLITE_OMIT_DEPRECATED
87362 #define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
87363 #endif
87364 #define sqlite3_update_hook            sqlite3_api->update_hook
87365 #define sqlite3_user_data              sqlite3_api->user_data
87366 #define sqlite3_value_blob             sqlite3_api->value_blob
87367 #define sqlite3_value_bytes            sqlite3_api->value_bytes
87368 #define sqlite3_value_bytes16          sqlite3_api->value_bytes16
87369 #define sqlite3_value_double           sqlite3_api->value_double
87370 #define sqlite3_value_int              sqlite3_api->value_int
87371 #define sqlite3_value_int64            sqlite3_api->value_int64
87372 #define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
87373 #define sqlite3_value_text             sqlite3_api->value_text
87374 #define sqlite3_value_text16           sqlite3_api->value_text16
87375 #define sqlite3_value_text16be         sqlite3_api->value_text16be
87376 #define sqlite3_value_text16le         sqlite3_api->value_text16le
87377 #define sqlite3_value_type             sqlite3_api->value_type
87378 #define sqlite3_vmprintf               sqlite3_api->vmprintf
87379 #define sqlite3_overload_function      sqlite3_api->overload_function
87380 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
87381 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
87382 #define sqlite3_clear_bindings         sqlite3_api->clear_bindings
87383 #define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
87384 #define sqlite3_blob_bytes             sqlite3_api->blob_bytes
87385 #define sqlite3_blob_close             sqlite3_api->blob_close
87386 #define sqlite3_blob_open              sqlite3_api->blob_open
87387 #define sqlite3_blob_read              sqlite3_api->blob_read
87388 #define sqlite3_blob_write             sqlite3_api->blob_write
87389 #define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
87390 #define sqlite3_file_control           sqlite3_api->file_control
87391 #define sqlite3_memory_highwater       sqlite3_api->memory_highwater
87392 #define sqlite3_memory_used            sqlite3_api->memory_used
87393 #define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
87394 #define sqlite3_mutex_enter            sqlite3_api->mutex_enter
87395 #define sqlite3_mutex_free             sqlite3_api->mutex_free
87396 #define sqlite3_mutex_leave            sqlite3_api->mutex_leave
87397 #define sqlite3_mutex_try              sqlite3_api->mutex_try
87398 #define sqlite3_open_v2                sqlite3_api->open_v2
87399 #define sqlite3_release_memory         sqlite3_api->release_memory
87400 #define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
87401 #define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
87402 #define sqlite3_sleep                  sqlite3_api->sleep
87403 #define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
87404 #define sqlite3_vfs_find               sqlite3_api->vfs_find
87405 #define sqlite3_vfs_register           sqlite3_api->vfs_register
87406 #define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
87407 #define sqlite3_threadsafe             sqlite3_api->xthreadsafe
87408 #define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
87409 #define sqlite3_result_error_code      sqlite3_api->result_error_code
87410 #define sqlite3_test_control           sqlite3_api->test_control
87411 #define sqlite3_randomness             sqlite3_api->randomness
87412 #define sqlite3_context_db_handle      sqlite3_api->context_db_handle
87413 #define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
87414 #define sqlite3_limit                  sqlite3_api->limit
87415 #define sqlite3_next_stmt              sqlite3_api->next_stmt
87416 #define sqlite3_sql                    sqlite3_api->sql
87417 #define sqlite3_status                 sqlite3_api->status
87418 #define sqlite3_backup_finish          sqlite3_api->backup_finish
87419 #define sqlite3_backup_init            sqlite3_api->backup_init
87420 #define sqlite3_backup_pagecount       sqlite3_api->backup_pagecount
87421 #define sqlite3_backup_remaining       sqlite3_api->backup_remaining
87422 #define sqlite3_backup_step            sqlite3_api->backup_step
87423 #define sqlite3_compileoption_get      sqlite3_api->compileoption_get
87424 #define sqlite3_compileoption_used     sqlite3_api->compileoption_used
87425 #define sqlite3_create_function_v2     sqlite3_api->create_function_v2
87426 #define sqlite3_db_config              sqlite3_api->db_config
87427 #define sqlite3_db_mutex               sqlite3_api->db_mutex
87428 #define sqlite3_db_status              sqlite3_api->db_status
87429 #define sqlite3_extended_errcode       sqlite3_api->extended_errcode
87430 #define sqlite3_log                    sqlite3_api->log
87431 #define sqlite3_soft_heap_limit64      sqlite3_api->soft_heap_limit64
87432 #define sqlite3_sourceid               sqlite3_api->sourceid
87433 #define sqlite3_stmt_status            sqlite3_api->stmt_status
87434 #define sqlite3_strnicmp               sqlite3_api->strnicmp
87435 #define sqlite3_unlock_notify          sqlite3_api->unlock_notify
87436 #define sqlite3_wal_autocheckpoint     sqlite3_api->wal_autocheckpoint
87437 #define sqlite3_wal_checkpoint         sqlite3_api->wal_checkpoint
87438 #define sqlite3_wal_hook               sqlite3_api->wal_hook
87439 #endif /* SQLITE_CORE */
87440
87441 #define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api = 0;
87442 #define SQLITE_EXTENSION_INIT2(v)  sqlite3_api = v;
87443
87444 #endif /* _SQLITE3EXT_H_ */
87445
87446 /************** End of sqlite3ext.h ******************************************/
87447 /************** Continuing where we left off in loadext.c ********************/
87448
87449 #ifndef SQLITE_OMIT_LOAD_EXTENSION
87450
87451 /*
87452 ** Some API routines are omitted when various features are
87453 ** excluded from a build of SQLite.  Substitute a NULL pointer
87454 ** for any missing APIs.
87455 */
87456 #ifndef SQLITE_ENABLE_COLUMN_METADATA
87457 # define sqlite3_column_database_name   0
87458 # define sqlite3_column_database_name16 0
87459 # define sqlite3_column_table_name      0
87460 # define sqlite3_column_table_name16    0
87461 # define sqlite3_column_origin_name     0
87462 # define sqlite3_column_origin_name16   0
87463 # define sqlite3_table_column_metadata  0
87464 #endif
87465
87466 #ifdef SQLITE_OMIT_AUTHORIZATION
87467 # define sqlite3_set_authorizer         0
87468 #endif
87469
87470 #ifdef SQLITE_OMIT_UTF16
87471 # define sqlite3_bind_text16            0
87472 # define sqlite3_collation_needed16     0
87473 # define sqlite3_column_decltype16      0
87474 # define sqlite3_column_name16          0
87475 # define sqlite3_column_text16          0
87476 # define sqlite3_complete16             0
87477 # define sqlite3_create_collation16     0
87478 # define sqlite3_create_function16      0
87479 # define sqlite3_errmsg16               0
87480 # define sqlite3_open16                 0
87481 # define sqlite3_prepare16              0
87482 # define sqlite3_prepare16_v2           0
87483 # define sqlite3_result_error16         0
87484 # define sqlite3_result_text16          0
87485 # define sqlite3_result_text16be        0
87486 # define sqlite3_result_text16le        0
87487 # define sqlite3_value_text16           0
87488 # define sqlite3_value_text16be         0
87489 # define sqlite3_value_text16le         0
87490 # define sqlite3_column_database_name16 0
87491 # define sqlite3_column_table_name16    0
87492 # define sqlite3_column_origin_name16   0
87493 #endif
87494
87495 #ifdef SQLITE_OMIT_COMPLETE
87496 # define sqlite3_complete 0
87497 # define sqlite3_complete16 0
87498 #endif
87499
87500 #ifdef SQLITE_OMIT_DECLTYPE
87501 # define sqlite3_column_decltype16      0
87502 # define sqlite3_column_decltype        0
87503 #endif
87504
87505 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
87506 # define sqlite3_progress_handler 0
87507 #endif
87508
87509 #ifdef SQLITE_OMIT_VIRTUALTABLE
87510 # define sqlite3_create_module 0
87511 # define sqlite3_create_module_v2 0
87512 # define sqlite3_declare_vtab 0
87513 #endif
87514
87515 #ifdef SQLITE_OMIT_SHARED_CACHE
87516 # define sqlite3_enable_shared_cache 0
87517 #endif
87518
87519 #ifdef SQLITE_OMIT_TRACE
87520 # define sqlite3_profile       0
87521 # define sqlite3_trace         0
87522 #endif
87523
87524 #ifdef SQLITE_OMIT_GET_TABLE
87525 # define sqlite3_free_table    0
87526 # define sqlite3_get_table     0
87527 #endif
87528
87529 #ifdef SQLITE_OMIT_INCRBLOB
87530 #define sqlite3_bind_zeroblob  0
87531 #define sqlite3_blob_bytes     0
87532 #define sqlite3_blob_close     0
87533 #define sqlite3_blob_open      0
87534 #define sqlite3_blob_read      0
87535 #define sqlite3_blob_write     0
87536 #endif
87537
87538 /*
87539 ** The following structure contains pointers to all SQLite API routines.
87540 ** A pointer to this structure is passed into extensions when they are
87541 ** loaded so that the extension can make calls back into the SQLite
87542 ** library.
87543 **
87544 ** When adding new APIs, add them to the bottom of this structure
87545 ** in order to preserve backwards compatibility.
87546 **
87547 ** Extensions that use newer APIs should first call the
87548 ** sqlite3_libversion_number() to make sure that the API they
87549 ** intend to use is supported by the library.  Extensions should
87550 ** also check to make sure that the pointer to the function is
87551 ** not NULL before calling it.
87552 */
87553 static const sqlite3_api_routines sqlite3Apis = {
87554   sqlite3_aggregate_context,
87555 #ifndef SQLITE_OMIT_DEPRECATED
87556   sqlite3_aggregate_count,
87557 #else
87558   0,
87559 #endif
87560   sqlite3_bind_blob,
87561   sqlite3_bind_double,
87562   sqlite3_bind_int,
87563   sqlite3_bind_int64,
87564   sqlite3_bind_null,
87565   sqlite3_bind_parameter_count,
87566   sqlite3_bind_parameter_index,
87567   sqlite3_bind_parameter_name,
87568   sqlite3_bind_text,
87569   sqlite3_bind_text16,
87570   sqlite3_bind_value,
87571   sqlite3_busy_handler,
87572   sqlite3_busy_timeout,
87573   sqlite3_changes,
87574   sqlite3_close,
87575   sqlite3_collation_needed,
87576   sqlite3_collation_needed16,
87577   sqlite3_column_blob,
87578   sqlite3_column_bytes,
87579   sqlite3_column_bytes16,
87580   sqlite3_column_count,
87581   sqlite3_column_database_name,
87582   sqlite3_column_database_name16,
87583   sqlite3_column_decltype,
87584   sqlite3_column_decltype16,
87585   sqlite3_column_double,
87586   sqlite3_column_int,
87587   sqlite3_column_int64,
87588   sqlite3_column_name,
87589   sqlite3_column_name16,
87590   sqlite3_column_origin_name,
87591   sqlite3_column_origin_name16,
87592   sqlite3_column_table_name,
87593   sqlite3_column_table_name16,
87594   sqlite3_column_text,
87595   sqlite3_column_text16,
87596   sqlite3_column_type,
87597   sqlite3_column_value,
87598   sqlite3_commit_hook,
87599   sqlite3_complete,
87600   sqlite3_complete16,
87601   sqlite3_create_collation,
87602   sqlite3_create_collation16,
87603   sqlite3_create_function,
87604   sqlite3_create_function16,
87605   sqlite3_create_module,
87606   sqlite3_data_count,
87607   sqlite3_db_handle,
87608   sqlite3_declare_vtab,
87609   sqlite3_enable_shared_cache,
87610   sqlite3_errcode,
87611   sqlite3_errmsg,
87612   sqlite3_errmsg16,
87613   sqlite3_exec,
87614 #ifndef SQLITE_OMIT_DEPRECATED
87615   sqlite3_expired,
87616 #else
87617   0,
87618 #endif
87619   sqlite3_finalize,
87620   sqlite3_free,
87621   sqlite3_free_table,
87622   sqlite3_get_autocommit,
87623   sqlite3_get_auxdata,
87624   sqlite3_get_table,
87625   0,     /* Was sqlite3_global_recover(), but that function is deprecated */
87626   sqlite3_interrupt,
87627   sqlite3_last_insert_rowid,
87628   sqlite3_libversion,
87629   sqlite3_libversion_number,
87630   sqlite3_malloc,
87631   sqlite3_mprintf,
87632   sqlite3_open,
87633   sqlite3_open16,
87634   sqlite3_prepare,
87635   sqlite3_prepare16,
87636   sqlite3_profile,
87637   sqlite3_progress_handler,
87638   sqlite3_realloc,
87639   sqlite3_reset,
87640   sqlite3_result_blob,
87641   sqlite3_result_double,
87642   sqlite3_result_error,
87643   sqlite3_result_error16,
87644   sqlite3_result_int,
87645   sqlite3_result_int64,
87646   sqlite3_result_null,
87647   sqlite3_result_text,
87648   sqlite3_result_text16,
87649   sqlite3_result_text16be,
87650   sqlite3_result_text16le,
87651   sqlite3_result_value,
87652   sqlite3_rollback_hook,
87653   sqlite3_set_authorizer,
87654   sqlite3_set_auxdata,
87655   sqlite3_snprintf,
87656   sqlite3_step,
87657   sqlite3_table_column_metadata,
87658 #ifndef SQLITE_OMIT_DEPRECATED
87659   sqlite3_thread_cleanup,
87660 #else
87661   0,
87662 #endif
87663   sqlite3_total_changes,
87664   sqlite3_trace,
87665 #ifndef SQLITE_OMIT_DEPRECATED
87666   sqlite3_transfer_bindings,
87667 #else
87668   0,
87669 #endif
87670   sqlite3_update_hook,
87671   sqlite3_user_data,
87672   sqlite3_value_blob,
87673   sqlite3_value_bytes,
87674   sqlite3_value_bytes16,
87675   sqlite3_value_double,
87676   sqlite3_value_int,
87677   sqlite3_value_int64,
87678   sqlite3_value_numeric_type,
87679   sqlite3_value_text,
87680   sqlite3_value_text16,
87681   sqlite3_value_text16be,
87682   sqlite3_value_text16le,
87683   sqlite3_value_type,
87684   sqlite3_vmprintf,
87685   /*
87686   ** The original API set ends here.  All extensions can call any
87687   ** of the APIs above provided that the pointer is not NULL.  But
87688   ** before calling APIs that follow, extension should check the
87689   ** sqlite3_libversion_number() to make sure they are dealing with
87690   ** a library that is new enough to support that API.
87691   *************************************************************************
87692   */
87693   sqlite3_overload_function,
87694
87695   /*
87696   ** Added after 3.3.13
87697   */
87698   sqlite3_prepare_v2,
87699   sqlite3_prepare16_v2,
87700   sqlite3_clear_bindings,
87701
87702   /*
87703   ** Added for 3.4.1
87704   */
87705   sqlite3_create_module_v2,
87706
87707   /*
87708   ** Added for 3.5.0
87709   */
87710   sqlite3_bind_zeroblob,
87711   sqlite3_blob_bytes,
87712   sqlite3_blob_close,
87713   sqlite3_blob_open,
87714   sqlite3_blob_read,
87715   sqlite3_blob_write,
87716   sqlite3_create_collation_v2,
87717   sqlite3_file_control,
87718   sqlite3_memory_highwater,
87719   sqlite3_memory_used,
87720 #ifdef SQLITE_MUTEX_OMIT
87721   0, 
87722   0, 
87723   0,
87724   0,
87725   0,
87726 #else
87727   sqlite3_mutex_alloc,
87728   sqlite3_mutex_enter,
87729   sqlite3_mutex_free,
87730   sqlite3_mutex_leave,
87731   sqlite3_mutex_try,
87732 #endif
87733   sqlite3_open_v2,
87734   sqlite3_release_memory,
87735   sqlite3_result_error_nomem,
87736   sqlite3_result_error_toobig,
87737   sqlite3_sleep,
87738   sqlite3_soft_heap_limit,
87739   sqlite3_vfs_find,
87740   sqlite3_vfs_register,
87741   sqlite3_vfs_unregister,
87742
87743   /*
87744   ** Added for 3.5.8
87745   */
87746   sqlite3_threadsafe,
87747   sqlite3_result_zeroblob,
87748   sqlite3_result_error_code,
87749   sqlite3_test_control,
87750   sqlite3_randomness,
87751   sqlite3_context_db_handle,
87752
87753   /*
87754   ** Added for 3.6.0
87755   */
87756   sqlite3_extended_result_codes,
87757   sqlite3_limit,
87758   sqlite3_next_stmt,
87759   sqlite3_sql,
87760   sqlite3_status,
87761
87762   /*
87763   ** Added for 3.7.4
87764   */
87765   sqlite3_backup_finish,
87766   sqlite3_backup_init,
87767   sqlite3_backup_pagecount,
87768   sqlite3_backup_remaining,
87769   sqlite3_backup_step,
87770 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
87771   sqlite3_compileoption_get,
87772   sqlite3_compileoption_used,
87773 #else
87774   0,
87775   0,
87776 #endif
87777   sqlite3_create_function_v2,
87778   sqlite3_db_config,
87779   sqlite3_db_mutex,
87780   sqlite3_db_status,
87781   sqlite3_extended_errcode,
87782   sqlite3_log,
87783   sqlite3_soft_heap_limit64,
87784   sqlite3_sourceid,
87785   sqlite3_stmt_status,
87786   sqlite3_strnicmp,
87787 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
87788   sqlite3_unlock_notify,
87789 #else
87790   0,
87791 #endif
87792 #ifndef SQLITE_OMIT_WAL
87793   sqlite3_wal_autocheckpoint,
87794   sqlite3_wal_checkpoint,
87795   sqlite3_wal_hook,
87796 #else
87797   0,
87798   0,
87799   0,
87800 #endif
87801 };
87802
87803 /*
87804 ** Attempt to load an SQLite extension library contained in the file
87805 ** zFile.  The entry point is zProc.  zProc may be 0 in which case a
87806 ** default entry point name (sqlite3_extension_init) is used.  Use
87807 ** of the default name is recommended.
87808 **
87809 ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
87810 **
87811 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with 
87812 ** error message text.  The calling function should free this memory
87813 ** by calling sqlite3DbFree(db, ).
87814 */
87815 static int sqlite3LoadExtension(
87816   sqlite3 *db,          /* Load the extension into this database connection */
87817   const char *zFile,    /* Name of the shared library containing extension */
87818   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
87819   char **pzErrMsg       /* Put error message here if not 0 */
87820 ){
87821   sqlite3_vfs *pVfs = db->pVfs;
87822   void *handle;
87823   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
87824   char *zErrmsg = 0;
87825   void **aHandle;
87826   const int nMsg = 300;
87827
87828   if( pzErrMsg ) *pzErrMsg = 0;
87829
87830   /* Ticket #1863.  To avoid a creating security problems for older
87831   ** applications that relink against newer versions of SQLite, the
87832   ** ability to run load_extension is turned off by default.  One
87833   ** must call sqlite3_enable_load_extension() to turn on extension
87834   ** loading.  Otherwise you get the following error.
87835   */
87836   if( (db->flags & SQLITE_LoadExtension)==0 ){
87837     if( pzErrMsg ){
87838       *pzErrMsg = sqlite3_mprintf("not authorized");
87839     }
87840     return SQLITE_ERROR;
87841   }
87842
87843   if( zProc==0 ){
87844     zProc = "sqlite3_extension_init";
87845   }
87846
87847   handle = sqlite3OsDlOpen(pVfs, zFile);
87848   if( handle==0 ){
87849     if( pzErrMsg ){
87850       *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
87851       if( zErrmsg ){
87852         sqlite3_snprintf(nMsg, zErrmsg, 
87853             "unable to open shared library [%s]", zFile);
87854         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
87855       }
87856     }
87857     return SQLITE_ERROR;
87858   }
87859   xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
87860                    sqlite3OsDlSym(pVfs, handle, zProc);
87861   if( xInit==0 ){
87862     if( pzErrMsg ){
87863       *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
87864       if( zErrmsg ){
87865         sqlite3_snprintf(nMsg, zErrmsg,
87866             "no entry point [%s] in shared library [%s]", zProc,zFile);
87867         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
87868       }
87869       sqlite3OsDlClose(pVfs, handle);
87870     }
87871     return SQLITE_ERROR;
87872   }else if( xInit(db, &zErrmsg, &sqlite3Apis) ){
87873     if( pzErrMsg ){
87874       *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
87875     }
87876     sqlite3_free(zErrmsg);
87877     sqlite3OsDlClose(pVfs, handle);
87878     return SQLITE_ERROR;
87879   }
87880
87881   /* Append the new shared library handle to the db->aExtension array. */
87882   aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
87883   if( aHandle==0 ){
87884     return SQLITE_NOMEM;
87885   }
87886   if( db->nExtension>0 ){
87887     memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
87888   }
87889   sqlite3DbFree(db, db->aExtension);
87890   db->aExtension = aHandle;
87891
87892   db->aExtension[db->nExtension++] = handle;
87893   return SQLITE_OK;
87894 }
87895 SQLITE_API int sqlite3_load_extension(
87896   sqlite3 *db,          /* Load the extension into this database connection */
87897   const char *zFile,    /* Name of the shared library containing extension */
87898   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
87899   char **pzErrMsg       /* Put error message here if not 0 */
87900 ){
87901   int rc;
87902   sqlite3_mutex_enter(db->mutex);
87903   rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
87904   rc = sqlite3ApiExit(db, rc);
87905   sqlite3_mutex_leave(db->mutex);
87906   return rc;
87907 }
87908
87909 /*
87910 ** Call this routine when the database connection is closing in order
87911 ** to clean up loaded extensions
87912 */
87913 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
87914   int i;
87915   assert( sqlite3_mutex_held(db->mutex) );
87916   for(i=0; i<db->nExtension; i++){
87917     sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
87918   }
87919   sqlite3DbFree(db, db->aExtension);
87920 }
87921
87922 /*
87923 ** Enable or disable extension loading.  Extension loading is disabled by
87924 ** default so as not to open security holes in older applications.
87925 */
87926 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
87927   sqlite3_mutex_enter(db->mutex);
87928   if( onoff ){
87929     db->flags |= SQLITE_LoadExtension;
87930   }else{
87931     db->flags &= ~SQLITE_LoadExtension;
87932   }
87933   sqlite3_mutex_leave(db->mutex);
87934   return SQLITE_OK;
87935 }
87936
87937 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
87938
87939 /*
87940 ** The auto-extension code added regardless of whether or not extension
87941 ** loading is supported.  We need a dummy sqlite3Apis pointer for that
87942 ** code if regular extension loading is not available.  This is that
87943 ** dummy pointer.
87944 */
87945 #ifdef SQLITE_OMIT_LOAD_EXTENSION
87946 static const sqlite3_api_routines sqlite3Apis = { 0 };
87947 #endif
87948
87949
87950 /*
87951 ** The following object holds the list of automatically loaded
87952 ** extensions.
87953 **
87954 ** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
87955 ** mutex must be held while accessing this list.
87956 */
87957 typedef struct sqlite3AutoExtList sqlite3AutoExtList;
87958 static SQLITE_WSD struct sqlite3AutoExtList {
87959   int nExt;              /* Number of entries in aExt[] */          
87960   void (**aExt)(void);   /* Pointers to the extension init functions */
87961 } sqlite3Autoext = { 0, 0 };
87962
87963 /* The "wsdAutoext" macro will resolve to the autoextension
87964 ** state vector.  If writable static data is unsupported on the target,
87965 ** we have to locate the state vector at run-time.  In the more common
87966 ** case where writable static data is supported, wsdStat can refer directly
87967 ** to the "sqlite3Autoext" state vector declared above.
87968 */
87969 #ifdef SQLITE_OMIT_WSD
87970 # define wsdAutoextInit \
87971   sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
87972 # define wsdAutoext x[0]
87973 #else
87974 # define wsdAutoextInit
87975 # define wsdAutoext sqlite3Autoext
87976 #endif
87977
87978
87979 /*
87980 ** Register a statically linked extension that is automatically
87981 ** loaded by every new database connection.
87982 */
87983 SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
87984   int rc = SQLITE_OK;
87985 #ifndef SQLITE_OMIT_AUTOINIT
87986   rc = sqlite3_initialize();
87987   if( rc ){
87988     return rc;
87989   }else
87990 #endif
87991   {
87992     int i;
87993 #if SQLITE_THREADSAFE
87994     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
87995 #endif
87996     wsdAutoextInit;
87997     sqlite3_mutex_enter(mutex);
87998     for(i=0; i<wsdAutoext.nExt; i++){
87999       if( wsdAutoext.aExt[i]==xInit ) break;
88000     }
88001     if( i==wsdAutoext.nExt ){
88002       int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
88003       void (**aNew)(void);
88004       aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
88005       if( aNew==0 ){
88006         rc = SQLITE_NOMEM;
88007       }else{
88008         wsdAutoext.aExt = aNew;
88009         wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
88010         wsdAutoext.nExt++;
88011       }
88012     }
88013     sqlite3_mutex_leave(mutex);
88014     assert( (rc&0xff)==rc );
88015     return rc;
88016   }
88017 }
88018
88019 /*
88020 ** Reset the automatic extension loading mechanism.
88021 */
88022 SQLITE_API void sqlite3_reset_auto_extension(void){
88023 #ifndef SQLITE_OMIT_AUTOINIT
88024   if( sqlite3_initialize()==SQLITE_OK )
88025 #endif
88026   {
88027 #if SQLITE_THREADSAFE
88028     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
88029 #endif
88030     wsdAutoextInit;
88031     sqlite3_mutex_enter(mutex);
88032     sqlite3_free(wsdAutoext.aExt);
88033     wsdAutoext.aExt = 0;
88034     wsdAutoext.nExt = 0;
88035     sqlite3_mutex_leave(mutex);
88036   }
88037 }
88038
88039 /*
88040 ** Load all automatic extensions.
88041 **
88042 ** If anything goes wrong, set an error in the database connection.
88043 */
88044 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
88045   int i;
88046   int go = 1;
88047   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
88048
88049   wsdAutoextInit;
88050   if( wsdAutoext.nExt==0 ){
88051     /* Common case: early out without every having to acquire a mutex */
88052     return;
88053   }
88054   for(i=0; go; i++){
88055     char *zErrmsg;
88056 #if SQLITE_THREADSAFE
88057     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
88058 #endif
88059     sqlite3_mutex_enter(mutex);
88060     if( i>=wsdAutoext.nExt ){
88061       xInit = 0;
88062       go = 0;
88063     }else{
88064       xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
88065               wsdAutoext.aExt[i];
88066     }
88067     sqlite3_mutex_leave(mutex);
88068     zErrmsg = 0;
88069     if( xInit && xInit(db, &zErrmsg, &sqlite3Apis) ){
88070       sqlite3Error(db, SQLITE_ERROR,
88071             "automatic extension loading failed: %s", zErrmsg);
88072       go = 0;
88073     }
88074     sqlite3_free(zErrmsg);
88075   }
88076 }
88077
88078 /************** End of loadext.c *********************************************/
88079 /************** Begin file pragma.c ******************************************/
88080 /*
88081 ** 2003 April 6
88082 **
88083 ** The author disclaims copyright to this source code.  In place of
88084 ** a legal notice, here is a blessing:
88085 **
88086 **    May you do good and not evil.
88087 **    May you find forgiveness for yourself and forgive others.
88088 **    May you share freely, never taking more than you give.
88089 **
88090 *************************************************************************
88091 ** This file contains code used to implement the PRAGMA command.
88092 */
88093
88094 /*
88095 ** Interpret the given string as a safety level.  Return 0 for OFF,
88096 ** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or 
88097 ** unrecognized string argument.
88098 **
88099 ** Note that the values returned are one less that the values that
88100 ** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
88101 ** to support legacy SQL code.  The safety level used to be boolean
88102 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
88103 */
88104 static u8 getSafetyLevel(const char *z){
88105                              /* 123456789 123456789 */
88106   static const char zText[] = "onoffalseyestruefull";
88107   static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
88108   static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
88109   static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
88110   int i, n;
88111   if( sqlite3Isdigit(*z) ){
88112     return (u8)sqlite3Atoi(z);
88113   }
88114   n = sqlite3Strlen30(z);
88115   for(i=0; i<ArraySize(iLength); i++){
88116     if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
88117       return iValue[i];
88118     }
88119   }
88120   return 1;
88121 }
88122
88123 /*
88124 ** Interpret the given string as a boolean value.
88125 */
88126 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z){
88127   return getSafetyLevel(z)&1;
88128 }
88129
88130 /* The sqlite3GetBoolean() function is used by other modules but the
88131 ** remainder of this file is specific to PRAGMA processing.  So omit
88132 ** the rest of the file if PRAGMAs are omitted from the build.
88133 */
88134 #if !defined(SQLITE_OMIT_PRAGMA)
88135
88136 /*
88137 ** Interpret the given string as a locking mode value.
88138 */
88139 static int getLockingMode(const char *z){
88140   if( z ){
88141     if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
88142     if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
88143   }
88144   return PAGER_LOCKINGMODE_QUERY;
88145 }
88146
88147 #ifndef SQLITE_OMIT_AUTOVACUUM
88148 /*
88149 ** Interpret the given string as an auto-vacuum mode value.
88150 **
88151 ** The following strings, "none", "full" and "incremental" are 
88152 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
88153 */
88154 static int getAutoVacuum(const char *z){
88155   int i;
88156   if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
88157   if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
88158   if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
88159   i = sqlite3Atoi(z);
88160   return (u8)((i>=0&&i<=2)?i:0);
88161 }
88162 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
88163
88164 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
88165 /*
88166 ** Interpret the given string as a temp db location. Return 1 for file
88167 ** backed temporary databases, 2 for the Red-Black tree in memory database
88168 ** and 0 to use the compile-time default.
88169 */
88170 static int getTempStore(const char *z){
88171   if( z[0]>='0' && z[0]<='2' ){
88172     return z[0] - '0';
88173   }else if( sqlite3StrICmp(z, "file")==0 ){
88174     return 1;
88175   }else if( sqlite3StrICmp(z, "memory")==0 ){
88176     return 2;
88177   }else{
88178     return 0;
88179   }
88180 }
88181 #endif /* SQLITE_PAGER_PRAGMAS */
88182
88183 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
88184 /*
88185 ** Invalidate temp storage, either when the temp storage is changed
88186 ** from default, or when 'file' and the temp_store_directory has changed
88187 */
88188 static int invalidateTempStorage(Parse *pParse){
88189   sqlite3 *db = pParse->db;
88190   if( db->aDb[1].pBt!=0 ){
88191     if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
88192       sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
88193         "from within a transaction");
88194       return SQLITE_ERROR;
88195     }
88196     sqlite3BtreeClose(db->aDb[1].pBt);
88197     db->aDb[1].pBt = 0;
88198     sqlite3ResetInternalSchema(db, -1);
88199   }
88200   return SQLITE_OK;
88201 }
88202 #endif /* SQLITE_PAGER_PRAGMAS */
88203
88204 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
88205 /*
88206 ** If the TEMP database is open, close it and mark the database schema
88207 ** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
88208 ** or DEFAULT_TEMP_STORE pragmas.
88209 */
88210 static int changeTempStorage(Parse *pParse, const char *zStorageType){
88211   int ts = getTempStore(zStorageType);
88212   sqlite3 *db = pParse->db;
88213   if( db->temp_store==ts ) return SQLITE_OK;
88214   if( invalidateTempStorage( pParse ) != SQLITE_OK ){
88215     return SQLITE_ERROR;
88216   }
88217   db->temp_store = (u8)ts;
88218   return SQLITE_OK;
88219 }
88220 #endif /* SQLITE_PAGER_PRAGMAS */
88221
88222 /*
88223 ** Generate code to return a single integer value.
88224 */
88225 static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
88226   Vdbe *v = sqlite3GetVdbe(pParse);
88227   int mem = ++pParse->nMem;
88228   i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
88229   if( pI64 ){
88230     memcpy(pI64, &value, sizeof(value));
88231   }
88232   sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
88233   sqlite3VdbeSetNumCols(v, 1);
88234   sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
88235   sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
88236 }
88237
88238 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
88239 /*
88240 ** Check to see if zRight and zLeft refer to a pragma that queries
88241 ** or changes one of the flags in db->flags.  Return 1 if so and 0 if not.
88242 ** Also, implement the pragma.
88243 */
88244 static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
88245   static const struct sPragmaType {
88246     const char *zName;  /* Name of the pragma */
88247     int mask;           /* Mask for the db->flags value */
88248   } aPragma[] = {
88249     { "full_column_names",        SQLITE_FullColNames  },
88250     { "short_column_names",       SQLITE_ShortColNames },
88251     { "count_changes",            SQLITE_CountRows     },
88252     { "empty_result_callbacks",   SQLITE_NullCallback  },
88253     { "legacy_file_format",       SQLITE_LegacyFileFmt },
88254     { "fullfsync",                SQLITE_FullFSync     },
88255     { "checkpoint_fullfsync",     SQLITE_CkptFullFSync },
88256     { "reverse_unordered_selects", SQLITE_ReverseOrder  },
88257 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
88258     { "automatic_index",          SQLITE_AutoIndex     },
88259 #endif
88260 #ifdef SQLITE_DEBUG
88261     { "sql_trace",                SQLITE_SqlTrace      },
88262     { "vdbe_listing",             SQLITE_VdbeListing   },
88263     { "vdbe_trace",               SQLITE_VdbeTrace     },
88264 #endif
88265 #ifndef SQLITE_OMIT_CHECK
88266     { "ignore_check_constraints", SQLITE_IgnoreChecks  },
88267 #endif
88268     /* The following is VERY experimental */
88269     { "writable_schema",          SQLITE_WriteSchema|SQLITE_RecoveryMode },
88270     { "omit_readlock",            SQLITE_NoReadlock    },
88271
88272     /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
88273     ** flag if there are any active statements. */
88274     { "read_uncommitted",         SQLITE_ReadUncommitted },
88275     { "recursive_triggers",       SQLITE_RecTriggers },
88276
88277     /* This flag may only be set if both foreign-key and trigger support
88278     ** are present in the build.  */
88279 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
88280     { "foreign_keys",             SQLITE_ForeignKeys },
88281 #endif
88282   };
88283   int i;
88284   const struct sPragmaType *p;
88285   for(i=0, p=aPragma; i<ArraySize(aPragma); i++, p++){
88286     if( sqlite3StrICmp(zLeft, p->zName)==0 ){
88287       sqlite3 *db = pParse->db;
88288       Vdbe *v;
88289       v = sqlite3GetVdbe(pParse);
88290       assert( v!=0 );  /* Already allocated by sqlite3Pragma() */
88291       if( ALWAYS(v) ){
88292         if( zRight==0 ){
88293           returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
88294         }else{
88295           int mask = p->mask;          /* Mask of bits to set or clear. */
88296           if( db->autoCommit==0 ){
88297             /* Foreign key support may not be enabled or disabled while not
88298             ** in auto-commit mode.  */
88299             mask &= ~(SQLITE_ForeignKeys);
88300           }
88301
88302           if( sqlite3GetBoolean(zRight) ){
88303             db->flags |= mask;
88304           }else{
88305             db->flags &= ~mask;
88306           }
88307
88308           /* Many of the flag-pragmas modify the code generated by the SQL 
88309           ** compiler (eg. count_changes). So add an opcode to expire all
88310           ** compiled SQL statements after modifying a pragma value.
88311           */
88312           sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
88313         }
88314       }
88315
88316       return 1;
88317     }
88318   }
88319   return 0;
88320 }
88321 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
88322
88323 /*
88324 ** Return a human-readable name for a constraint resolution action.
88325 */
88326 #ifndef SQLITE_OMIT_FOREIGN_KEY
88327 static const char *actionName(u8 action){
88328   const char *zName;
88329   switch( action ){
88330     case OE_SetNull:  zName = "SET NULL";        break;
88331     case OE_SetDflt:  zName = "SET DEFAULT";     break;
88332     case OE_Cascade:  zName = "CASCADE";         break;
88333     case OE_Restrict: zName = "RESTRICT";        break;
88334     default:          zName = "NO ACTION";  
88335                       assert( action==OE_None ); break;
88336   }
88337   return zName;
88338 }
88339 #endif
88340
88341
88342 /*
88343 ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
88344 ** defined in pager.h. This function returns the associated lowercase
88345 ** journal-mode name.
88346 */
88347 SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
88348   static char * const azModeName[] = {
88349     "delete", "persist", "off", "truncate", "memory"
88350 #ifndef SQLITE_OMIT_WAL
88351      , "wal"
88352 #endif
88353   };
88354   assert( PAGER_JOURNALMODE_DELETE==0 );
88355   assert( PAGER_JOURNALMODE_PERSIST==1 );
88356   assert( PAGER_JOURNALMODE_OFF==2 );
88357   assert( PAGER_JOURNALMODE_TRUNCATE==3 );
88358   assert( PAGER_JOURNALMODE_MEMORY==4 );
88359   assert( PAGER_JOURNALMODE_WAL==5 );
88360   assert( eMode>=0 && eMode<=ArraySize(azModeName) );
88361
88362   if( eMode==ArraySize(azModeName) ) return 0;
88363   return azModeName[eMode];
88364 }
88365
88366 /*
88367 ** Process a pragma statement.  
88368 **
88369 ** Pragmas are of this form:
88370 **
88371 **      PRAGMA [database.]id [= value]
88372 **
88373 ** The identifier might also be a string.  The value is a string, and
88374 ** identifier, or a number.  If minusFlag is true, then the value is
88375 ** a number that was preceded by a minus sign.
88376 **
88377 ** If the left side is "database.id" then pId1 is the database name
88378 ** and pId2 is the id.  If the left side is just "id" then pId1 is the
88379 ** id and pId2 is any empty string.
88380 */
88381 SQLITE_PRIVATE void sqlite3Pragma(
88382   Parse *pParse, 
88383   Token *pId1,        /* First part of [database.]id field */
88384   Token *pId2,        /* Second part of [database.]id field, or NULL */
88385   Token *pValue,      /* Token for <value>, or NULL */
88386   int minusFlag       /* True if a '-' sign preceded <value> */
88387 ){
88388   char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
88389   char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
88390   const char *zDb = 0;   /* The database name */
88391   Token *pId;            /* Pointer to <id> token */
88392   int iDb;               /* Database index for <database> */
88393   sqlite3 *db = pParse->db;
88394   Db *pDb;
88395   Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(db);
88396   if( v==0 ) return;
88397   sqlite3VdbeRunOnlyOnce(v);
88398   pParse->nMem = 2;
88399
88400   /* Interpret the [database.] part of the pragma statement. iDb is the
88401   ** index of the database this pragma is being applied to in db.aDb[]. */
88402   iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
88403   if( iDb<0 ) return;
88404   pDb = &db->aDb[iDb];
88405
88406   /* If the temp database has been explicitly named as part of the 
88407   ** pragma, make sure it is open. 
88408   */
88409   if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
88410     return;
88411   }
88412
88413   zLeft = sqlite3NameFromToken(db, pId);
88414   if( !zLeft ) return;
88415   if( minusFlag ){
88416     zRight = sqlite3MPrintf(db, "-%T", pValue);
88417   }else{
88418     zRight = sqlite3NameFromToken(db, pValue);
88419   }
88420
88421   assert( pId2 );
88422   zDb = pId2->n>0 ? pDb->zName : 0;
88423   if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
88424     goto pragma_out;
88425   }
88426  
88427 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
88428   /*
88429   **  PRAGMA [database.]default_cache_size
88430   **  PRAGMA [database.]default_cache_size=N
88431   **
88432   ** The first form reports the current persistent setting for the
88433   ** page cache size.  The value returned is the maximum number of
88434   ** pages in the page cache.  The second form sets both the current
88435   ** page cache size value and the persistent page cache size value
88436   ** stored in the database file.
88437   **
88438   ** Older versions of SQLite would set the default cache size to a
88439   ** negative number to indicate synchronous=OFF.  These days, synchronous
88440   ** is always on by default regardless of the sign of the default cache
88441   ** size.  But continue to take the absolute value of the default cache
88442   ** size of historical compatibility.
88443   */
88444   if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
88445     static const VdbeOpList getCacheSize[] = {
88446       { OP_Transaction, 0, 0,        0},                         /* 0 */
88447       { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
88448       { OP_IfPos,       1, 7,        0},
88449       { OP_Integer,     0, 2,        0},
88450       { OP_Subtract,    1, 2,        1},
88451       { OP_IfPos,       1, 7,        0},
88452       { OP_Integer,     0, 1,        0},                         /* 6 */
88453       { OP_ResultRow,   1, 1,        0},
88454     };
88455     int addr;
88456     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88457     sqlite3VdbeUsesBtree(v, iDb);
88458     if( !zRight ){
88459       sqlite3VdbeSetNumCols(v, 1);
88460       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
88461       pParse->nMem += 2;
88462       addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
88463       sqlite3VdbeChangeP1(v, addr, iDb);
88464       sqlite3VdbeChangeP1(v, addr+1, iDb);
88465       sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
88466     }else{
88467       int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
88468       sqlite3BeginWriteOperation(pParse, 0, iDb);
88469       sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
88470       sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
88471       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
88472       pDb->pSchema->cache_size = size;
88473       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
88474     }
88475   }else
88476
88477   /*
88478   **  PRAGMA [database.]page_size
88479   **  PRAGMA [database.]page_size=N
88480   **
88481   ** The first form reports the current setting for the
88482   ** database page size in bytes.  The second form sets the
88483   ** database page size value.  The value can only be set if
88484   ** the database has not yet been created.
88485   */
88486   if( sqlite3StrICmp(zLeft,"page_size")==0 ){
88487     Btree *pBt = pDb->pBt;
88488     assert( pBt!=0 );
88489     if( !zRight ){
88490       int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
88491       returnSingleInt(pParse, "page_size", size);
88492     }else{
88493       /* Malloc may fail when setting the page-size, as there is an internal
88494       ** buffer that the pager module resizes using sqlite3_realloc().
88495       */
88496       db->nextPagesize = sqlite3Atoi(zRight);
88497       if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
88498         db->mallocFailed = 1;
88499       }
88500     }
88501   }else
88502
88503   /*
88504   **  PRAGMA [database.]secure_delete
88505   **  PRAGMA [database.]secure_delete=ON/OFF
88506   **
88507   ** The first form reports the current setting for the
88508   ** secure_delete flag.  The second form changes the secure_delete
88509   ** flag setting and reports thenew value.
88510   */
88511   if( sqlite3StrICmp(zLeft,"secure_delete")==0 ){
88512     Btree *pBt = pDb->pBt;
88513     int b = -1;
88514     assert( pBt!=0 );
88515     if( zRight ){
88516       b = sqlite3GetBoolean(zRight);
88517     }
88518     if( pId2->n==0 && b>=0 ){
88519       int ii;
88520       for(ii=0; ii<db->nDb; ii++){
88521         sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
88522       }
88523     }
88524     b = sqlite3BtreeSecureDelete(pBt, b);
88525     returnSingleInt(pParse, "secure_delete", b);
88526   }else
88527
88528   /*
88529   **  PRAGMA [database.]max_page_count
88530   **  PRAGMA [database.]max_page_count=N
88531   **
88532   ** The first form reports the current setting for the
88533   ** maximum number of pages in the database file.  The 
88534   ** second form attempts to change this setting.  Both
88535   ** forms return the current setting.
88536   **
88537   **  PRAGMA [database.]page_count
88538   **
88539   ** Return the number of pages in the specified database.
88540   */
88541   if( sqlite3StrICmp(zLeft,"page_count")==0
88542    || sqlite3StrICmp(zLeft,"max_page_count")==0
88543   ){
88544     int iReg;
88545     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88546     sqlite3CodeVerifySchema(pParse, iDb);
88547     iReg = ++pParse->nMem;
88548     if( zLeft[0]=='p' ){
88549       sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
88550     }else{
88551       sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg, sqlite3Atoi(zRight));
88552     }
88553     sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
88554     sqlite3VdbeSetNumCols(v, 1);
88555     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
88556   }else
88557
88558   /*
88559   **  PRAGMA [database.]locking_mode
88560   **  PRAGMA [database.]locking_mode = (normal|exclusive)
88561   */
88562   if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
88563     const char *zRet = "normal";
88564     int eMode = getLockingMode(zRight);
88565
88566     if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
88567       /* Simple "PRAGMA locking_mode;" statement. This is a query for
88568       ** the current default locking mode (which may be different to
88569       ** the locking-mode of the main database).
88570       */
88571       eMode = db->dfltLockMode;
88572     }else{
88573       Pager *pPager;
88574       if( pId2->n==0 ){
88575         /* This indicates that no database name was specified as part
88576         ** of the PRAGMA command. In this case the locking-mode must be
88577         ** set on all attached databases, as well as the main db file.
88578         **
88579         ** Also, the sqlite3.dfltLockMode variable is set so that
88580         ** any subsequently attached databases also use the specified
88581         ** locking mode.
88582         */
88583         int ii;
88584         assert(pDb==&db->aDb[0]);
88585         for(ii=2; ii<db->nDb; ii++){
88586           pPager = sqlite3BtreePager(db->aDb[ii].pBt);
88587           sqlite3PagerLockingMode(pPager, eMode);
88588         }
88589         db->dfltLockMode = (u8)eMode;
88590       }
88591       pPager = sqlite3BtreePager(pDb->pBt);
88592       eMode = sqlite3PagerLockingMode(pPager, eMode);
88593     }
88594
88595     assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
88596     if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
88597       zRet = "exclusive";
88598     }
88599     sqlite3VdbeSetNumCols(v, 1);
88600     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
88601     sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
88602     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
88603   }else
88604
88605   /*
88606   **  PRAGMA [database.]journal_mode
88607   **  PRAGMA [database.]journal_mode =
88608   **                      (delete|persist|off|truncate|memory|wal|off)
88609   */
88610   if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
88611     int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */
88612     int ii;           /* Loop counter */
88613
88614     /* Force the schema to be loaded on all databases.  This cases all
88615     ** database files to be opened and the journal_modes set. */
88616     if( sqlite3ReadSchema(pParse) ){
88617       goto pragma_out;
88618     }
88619
88620     sqlite3VdbeSetNumCols(v, 1);
88621     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
88622
88623     if( zRight==0 ){
88624       /* If there is no "=MODE" part of the pragma, do a query for the
88625       ** current mode */
88626       eMode = PAGER_JOURNALMODE_QUERY;
88627     }else{
88628       const char *zMode;
88629       int n = sqlite3Strlen30(zRight);
88630       for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
88631         if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
88632       }
88633       if( !zMode ){
88634         /* If the "=MODE" part does not match any known journal mode,
88635         ** then do a query */
88636         eMode = PAGER_JOURNALMODE_QUERY;
88637       }
88638     }
88639     if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
88640       /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
88641       iDb = 0;
88642       pId2->n = 1;
88643     }
88644     for(ii=db->nDb-1; ii>=0; ii--){
88645       if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
88646         sqlite3VdbeUsesBtree(v, ii);
88647         sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
88648       }
88649     }
88650     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
88651   }else
88652
88653   /*
88654   **  PRAGMA [database.]journal_size_limit
88655   **  PRAGMA [database.]journal_size_limit=N
88656   **
88657   ** Get or set the size limit on rollback journal files.
88658   */
88659   if( sqlite3StrICmp(zLeft,"journal_size_limit")==0 ){
88660     Pager *pPager = sqlite3BtreePager(pDb->pBt);
88661     i64 iLimit = -2;
88662     if( zRight ){
88663       sqlite3Atoi64(zRight, &iLimit, 1000000, SQLITE_UTF8);
88664       if( iLimit<-1 ) iLimit = -1;
88665     }
88666     iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
88667     returnSingleInt(pParse, "journal_size_limit", iLimit);
88668   }else
88669
88670 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
88671
88672   /*
88673   **  PRAGMA [database.]auto_vacuum
88674   **  PRAGMA [database.]auto_vacuum=N
88675   **
88676   ** Get or set the value of the database 'auto-vacuum' parameter.
88677   ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
88678   */
88679 #ifndef SQLITE_OMIT_AUTOVACUUM
88680   if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
88681     Btree *pBt = pDb->pBt;
88682     assert( pBt!=0 );
88683     if( sqlite3ReadSchema(pParse) ){
88684       goto pragma_out;
88685     }
88686     if( !zRight ){
88687       int auto_vacuum;
88688       if( ALWAYS(pBt) ){
88689          auto_vacuum = sqlite3BtreeGetAutoVacuum(pBt);
88690       }else{
88691          auto_vacuum = SQLITE_DEFAULT_AUTOVACUUM;
88692       }
88693       returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
88694     }else{
88695       int eAuto = getAutoVacuum(zRight);
88696       assert( eAuto>=0 && eAuto<=2 );
88697       db->nextAutovac = (u8)eAuto;
88698       if( ALWAYS(eAuto>=0) ){
88699         /* Call SetAutoVacuum() to set initialize the internal auto and
88700         ** incr-vacuum flags. This is required in case this connection
88701         ** creates the database file. It is important that it is created
88702         ** as an auto-vacuum capable db.
88703         */
88704         int rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
88705         if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
88706           /* When setting the auto_vacuum mode to either "full" or 
88707           ** "incremental", write the value of meta[6] in the database
88708           ** file. Before writing to meta[6], check that meta[3] indicates
88709           ** that this really is an auto-vacuum capable database.
88710           */
88711           static const VdbeOpList setMeta6[] = {
88712             { OP_Transaction,    0,         1,                 0},    /* 0 */
88713             { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
88714             { OP_If,             1,         0,                 0},    /* 2 */
88715             { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
88716             { OP_Integer,        0,         1,                 0},    /* 4 */
88717             { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 1},    /* 5 */
88718           };
88719           int iAddr;
88720           iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
88721           sqlite3VdbeChangeP1(v, iAddr, iDb);
88722           sqlite3VdbeChangeP1(v, iAddr+1, iDb);
88723           sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
88724           sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
88725           sqlite3VdbeChangeP1(v, iAddr+5, iDb);
88726           sqlite3VdbeUsesBtree(v, iDb);
88727         }
88728       }
88729     }
88730   }else
88731 #endif
88732
88733   /*
88734   **  PRAGMA [database.]incremental_vacuum(N)
88735   **
88736   ** Do N steps of incremental vacuuming on a database.
88737   */
88738 #ifndef SQLITE_OMIT_AUTOVACUUM
88739   if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
88740     int iLimit, addr;
88741     if( sqlite3ReadSchema(pParse) ){
88742       goto pragma_out;
88743     }
88744     if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
88745       iLimit = 0x7fffffff;
88746     }
88747     sqlite3BeginWriteOperation(pParse, 0, iDb);
88748     sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
88749     addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
88750     sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
88751     sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
88752     sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
88753     sqlite3VdbeJumpHere(v, addr);
88754   }else
88755 #endif
88756
88757 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
88758   /*
88759   **  PRAGMA [database.]cache_size
88760   **  PRAGMA [database.]cache_size=N
88761   **
88762   ** The first form reports the current local setting for the
88763   ** page cache size.  The local setting can be different from
88764   ** the persistent cache size value that is stored in the database
88765   ** file itself.  The value returned is the maximum number of
88766   ** pages in the page cache.  The second form sets the local
88767   ** page cache size value.  It does not change the persistent
88768   ** cache size stored on the disk so the cache size will revert
88769   ** to its default value when the database is closed and reopened.
88770   ** N should be a positive integer.
88771   */
88772   if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
88773     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88774     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
88775     if( !zRight ){
88776       returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
88777     }else{
88778       int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
88779       pDb->pSchema->cache_size = size;
88780       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
88781     }
88782   }else
88783
88784   /*
88785   **   PRAGMA temp_store
88786   **   PRAGMA temp_store = "default"|"memory"|"file"
88787   **
88788   ** Return or set the local value of the temp_store flag.  Changing
88789   ** the local value does not make changes to the disk file and the default
88790   ** value will be restored the next time the database is opened.
88791   **
88792   ** Note that it is possible for the library compile-time options to
88793   ** override this setting
88794   */
88795   if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
88796     if( !zRight ){
88797       returnSingleInt(pParse, "temp_store", db->temp_store);
88798     }else{
88799       changeTempStorage(pParse, zRight);
88800     }
88801   }else
88802
88803   /*
88804   **   PRAGMA temp_store_directory
88805   **   PRAGMA temp_store_directory = ""|"directory_name"
88806   **
88807   ** Return or set the local value of the temp_store_directory flag.  Changing
88808   ** the value sets a specific directory to be used for temporary files.
88809   ** Setting to a null string reverts to the default temporary directory search.
88810   ** If temporary directory is changed, then invalidateTempStorage.
88811   **
88812   */
88813   if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
88814     if( !zRight ){
88815       if( sqlite3_temp_directory ){
88816         sqlite3VdbeSetNumCols(v, 1);
88817         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
88818             "temp_store_directory", SQLITE_STATIC);
88819         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
88820         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
88821       }
88822     }else{
88823 #ifndef SQLITE_OMIT_WSD
88824       if( zRight[0] ){
88825         int rc;
88826         int res;
88827         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
88828         if( rc!=SQLITE_OK || res==0 ){
88829           sqlite3ErrorMsg(pParse, "not a writable directory");
88830           goto pragma_out;
88831         }
88832       }
88833       if( SQLITE_TEMP_STORE==0
88834        || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
88835        || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
88836       ){
88837         invalidateTempStorage(pParse);
88838       }
88839       sqlite3_free(sqlite3_temp_directory);
88840       if( zRight[0] ){
88841         sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
88842       }else{
88843         sqlite3_temp_directory = 0;
88844       }
88845 #endif /* SQLITE_OMIT_WSD */
88846     }
88847   }else
88848
88849 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
88850 #  if defined(__APPLE__)
88851 #    define SQLITE_ENABLE_LOCKING_STYLE 1
88852 #  else
88853 #    define SQLITE_ENABLE_LOCKING_STYLE 0
88854 #  endif
88855 #endif
88856 #if SQLITE_ENABLE_LOCKING_STYLE
88857   /*
88858    **   PRAGMA [database.]lock_proxy_file
88859    **   PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
88860    **
88861    ** Return or set the value of the lock_proxy_file flag.  Changing
88862    ** the value sets a specific file to be used for database access locks.
88863    **
88864    */
88865   if( sqlite3StrICmp(zLeft, "lock_proxy_file")==0 ){
88866     if( !zRight ){
88867       Pager *pPager = sqlite3BtreePager(pDb->pBt);
88868       char *proxy_file_path = NULL;
88869       sqlite3_file *pFile = sqlite3PagerFile(pPager);
88870       sqlite3OsFileControl(pFile, SQLITE_GET_LOCKPROXYFILE, 
88871                            &proxy_file_path);
88872       
88873       if( proxy_file_path ){
88874         sqlite3VdbeSetNumCols(v, 1);
88875         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
88876                               "lock_proxy_file", SQLITE_STATIC);
88877         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
88878         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
88879       }
88880     }else{
88881       Pager *pPager = sqlite3BtreePager(pDb->pBt);
88882       sqlite3_file *pFile = sqlite3PagerFile(pPager);
88883       int res;
88884       if( zRight[0] ){
88885         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
88886                                      zRight);
88887       } else {
88888         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
88889                                      NULL);
88890       }
88891       if( res!=SQLITE_OK ){
88892         sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
88893         goto pragma_out;
88894       }
88895     }
88896   }else
88897 #endif /* SQLITE_ENABLE_LOCKING_STYLE */      
88898     
88899   /*
88900   **   PRAGMA [database.]synchronous
88901   **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
88902   **
88903   ** Return or set the local value of the synchronous flag.  Changing
88904   ** the local value does not make changes to the disk file and the
88905   ** default value will be restored the next time the database is
88906   ** opened.
88907   */
88908   if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
88909     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88910     if( !zRight ){
88911       returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
88912     }else{
88913       if( !db->autoCommit ){
88914         sqlite3ErrorMsg(pParse, 
88915             "Safety level may not be changed inside a transaction");
88916       }else{
88917         pDb->safety_level = getSafetyLevel(zRight)+1;
88918       }
88919     }
88920   }else
88921 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
88922
88923 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
88924   if( flagPragma(pParse, zLeft, zRight) ){
88925     /* The flagPragma() subroutine also generates any necessary code
88926     ** there is nothing more to do here */
88927   }else
88928 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
88929
88930 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
88931   /*
88932   **   PRAGMA table_info(<table>)
88933   **
88934   ** Return a single row for each column of the named table. The columns of
88935   ** the returned data set are:
88936   **
88937   ** cid:        Column id (numbered from left to right, starting at 0)
88938   ** name:       Column name
88939   ** type:       Column declaration type.
88940   ** notnull:    True if 'NOT NULL' is part of column declaration
88941   ** dflt_value: The default value for the column, if any.
88942   */
88943   if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
88944     Table *pTab;
88945     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88946     pTab = sqlite3FindTable(db, zRight, zDb);
88947     if( pTab ){
88948       int i;
88949       int nHidden = 0;
88950       Column *pCol;
88951       sqlite3VdbeSetNumCols(v, 6);
88952       pParse->nMem = 6;
88953       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
88954       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
88955       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
88956       sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
88957       sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
88958       sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
88959       sqlite3ViewGetColumnNames(pParse, pTab);
88960       for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
88961         if( IsHiddenColumn(pCol) ){
88962           nHidden++;
88963           continue;
88964         }
88965         sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
88966         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
88967         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
88968            pCol->zType ? pCol->zType : "", 0);
88969         sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
88970         if( pCol->zDflt ){
88971           sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
88972         }else{
88973           sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
88974         }
88975         sqlite3VdbeAddOp2(v, OP_Integer, pCol->isPrimKey, 6);
88976         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
88977       }
88978     }
88979   }else
88980
88981   if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
88982     Index *pIdx;
88983     Table *pTab;
88984     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
88985     pIdx = sqlite3FindIndex(db, zRight, zDb);
88986     if( pIdx ){
88987       int i;
88988       pTab = pIdx->pTable;
88989       sqlite3VdbeSetNumCols(v, 3);
88990       pParse->nMem = 3;
88991       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
88992       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
88993       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
88994       for(i=0; i<pIdx->nColumn; i++){
88995         int cnum = pIdx->aiColumn[i];
88996         sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
88997         sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
88998         assert( pTab->nCol>cnum );
88999         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
89000         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
89001       }
89002     }
89003   }else
89004
89005   if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
89006     Index *pIdx;
89007     Table *pTab;
89008     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
89009     pTab = sqlite3FindTable(db, zRight, zDb);
89010     if( pTab ){
89011       v = sqlite3GetVdbe(pParse);
89012       pIdx = pTab->pIndex;
89013       if( pIdx ){
89014         int i = 0; 
89015         sqlite3VdbeSetNumCols(v, 3);
89016         pParse->nMem = 3;
89017         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
89018         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
89019         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
89020         while(pIdx){
89021           sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
89022           sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
89023           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
89024           sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
89025           ++i;
89026           pIdx = pIdx->pNext;
89027         }
89028       }
89029     }
89030   }else
89031
89032   if( sqlite3StrICmp(zLeft, "database_list")==0 ){
89033     int i;
89034     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
89035     sqlite3VdbeSetNumCols(v, 3);
89036     pParse->nMem = 3;
89037     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
89038     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
89039     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
89040     for(i=0; i<db->nDb; i++){
89041       if( db->aDb[i].pBt==0 ) continue;
89042       assert( db->aDb[i].zName!=0 );
89043       sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
89044       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
89045       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
89046            sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
89047       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
89048     }
89049   }else
89050
89051   if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
89052     int i = 0;
89053     HashElem *p;
89054     sqlite3VdbeSetNumCols(v, 2);
89055     pParse->nMem = 2;
89056     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
89057     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
89058     for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
89059       CollSeq *pColl = (CollSeq *)sqliteHashData(p);
89060       sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
89061       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
89062       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
89063     }
89064   }else
89065 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
89066
89067 #ifndef SQLITE_OMIT_FOREIGN_KEY
89068   if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
89069     FKey *pFK;
89070     Table *pTab;
89071     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
89072     pTab = sqlite3FindTable(db, zRight, zDb);
89073     if( pTab ){
89074       v = sqlite3GetVdbe(pParse);
89075       pFK = pTab->pFKey;
89076       if( pFK ){
89077         int i = 0; 
89078         sqlite3VdbeSetNumCols(v, 8);
89079         pParse->nMem = 8;
89080         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
89081         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
89082         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
89083         sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
89084         sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
89085         sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
89086         sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
89087         sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
89088         while(pFK){
89089           int j;
89090           for(j=0; j<pFK->nCol; j++){
89091             char *zCol = pFK->aCol[j].zCol;
89092             char *zOnDelete = (char *)actionName(pFK->aAction[0]);
89093             char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
89094             sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
89095             sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
89096             sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
89097             sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
89098                               pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
89099             sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
89100             sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
89101             sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
89102             sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
89103             sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
89104           }
89105           ++i;
89106           pFK = pFK->pNextFrom;
89107         }
89108       }
89109     }
89110   }else
89111 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
89112
89113 #ifndef NDEBUG
89114   if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
89115     if( zRight ){
89116       if( sqlite3GetBoolean(zRight) ){
89117         sqlite3ParserTrace(stderr, "parser: ");
89118       }else{
89119         sqlite3ParserTrace(0, 0);
89120       }
89121     }
89122   }else
89123 #endif
89124
89125   /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
89126   ** used will be case sensitive or not depending on the RHS.
89127   */
89128   if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
89129     if( zRight ){
89130       sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight));
89131     }
89132   }else
89133
89134 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
89135 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
89136 #endif
89137
89138 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
89139   /* Pragma "quick_check" is an experimental reduced version of 
89140   ** integrity_check designed to detect most database corruption
89141   ** without most of the overhead of a full integrity-check.
89142   */
89143   if( sqlite3StrICmp(zLeft, "integrity_check")==0
89144    || sqlite3StrICmp(zLeft, "quick_check")==0 
89145   ){
89146     int i, j, addr, mxErr;
89147
89148     /* Code that appears at the end of the integrity check.  If no error
89149     ** messages have been generated, output OK.  Otherwise output the
89150     ** error message
89151     */
89152     static const VdbeOpList endCode[] = {
89153       { OP_AddImm,      1, 0,        0},    /* 0 */
89154       { OP_IfNeg,       1, 0,        0},    /* 1 */
89155       { OP_String8,     0, 3,        0},    /* 2 */
89156       { OP_ResultRow,   3, 1,        0},
89157     };
89158
89159     int isQuick = (zLeft[0]=='q');
89160
89161     /* Initialize the VDBE program */
89162     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
89163     pParse->nMem = 6;
89164     sqlite3VdbeSetNumCols(v, 1);
89165     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
89166
89167     /* Set the maximum error count */
89168     mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
89169     if( zRight ){
89170       sqlite3GetInt32(zRight, &mxErr);
89171       if( mxErr<=0 ){
89172         mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
89173       }
89174     }
89175     sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
89176
89177     /* Do an integrity check on each database file */
89178     for(i=0; i<db->nDb; i++){
89179       HashElem *x;
89180       Hash *pTbls;
89181       int cnt = 0;
89182
89183       if( OMIT_TEMPDB && i==1 ) continue;
89184
89185       sqlite3CodeVerifySchema(pParse, i);
89186       addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
89187       sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
89188       sqlite3VdbeJumpHere(v, addr);
89189
89190       /* Do an integrity check of the B-Tree
89191       **
89192       ** Begin by filling registers 2, 3, ... with the root pages numbers
89193       ** for all tables and indices in the database.
89194       */
89195       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
89196       pTbls = &db->aDb[i].pSchema->tblHash;
89197       for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
89198         Table *pTab = sqliteHashData(x);
89199         Index *pIdx;
89200         sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
89201         cnt++;
89202         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
89203           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
89204           cnt++;
89205         }
89206       }
89207
89208       /* Make sure sufficient number of registers have been allocated */
89209       if( pParse->nMem < cnt+4 ){
89210         pParse->nMem = cnt+4;
89211       }
89212
89213       /* Do the b-tree integrity checks */
89214       sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
89215       sqlite3VdbeChangeP5(v, (u8)i);
89216       addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
89217       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
89218          sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
89219          P4_DYNAMIC);
89220       sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
89221       sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
89222       sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
89223       sqlite3VdbeJumpHere(v, addr);
89224
89225       /* Make sure all the indices are constructed correctly.
89226       */
89227       for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
89228         Table *pTab = sqliteHashData(x);
89229         Index *pIdx;
89230         int loopTop;
89231
89232         if( pTab->pIndex==0 ) continue;
89233         addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
89234         sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
89235         sqlite3VdbeJumpHere(v, addr);
89236         sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
89237         sqlite3VdbeAddOp2(v, OP_Integer, 0, 2);  /* reg(2) will count entries */
89238         loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0);
89239         sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1);   /* increment entry count */
89240         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
89241           int jmp2;
89242           int r1;
89243           static const VdbeOpList idxErr[] = {
89244             { OP_AddImm,      1, -1,  0},
89245             { OP_String8,     0,  3,  0},    /* 1 */
89246             { OP_Rowid,       1,  4,  0},
89247             { OP_String8,     0,  5,  0},    /* 3 */
89248             { OP_String8,     0,  6,  0},    /* 4 */
89249             { OP_Concat,      4,  3,  3},
89250             { OP_Concat,      5,  3,  3},
89251             { OP_Concat,      6,  3,  3},
89252             { OP_ResultRow,   3,  1,  0},
89253             { OP_IfPos,       1,  0,  0},    /* 9 */
89254             { OP_Halt,        0,  0,  0},
89255           };
89256           r1 = sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 0);
89257           jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1);
89258           addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
89259           sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
89260           sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
89261           sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_TRANSIENT);
89262           sqlite3VdbeJumpHere(v, addr+9);
89263           sqlite3VdbeJumpHere(v, jmp2);
89264         }
89265         sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
89266         sqlite3VdbeJumpHere(v, loopTop);
89267         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
89268           static const VdbeOpList cntIdx[] = {
89269              { OP_Integer,      0,  3,  0},
89270              { OP_Rewind,       0,  0,  0},  /* 1 */
89271              { OP_AddImm,       3,  1,  0},
89272              { OP_Next,         0,  0,  0},  /* 3 */
89273              { OP_Eq,           2,  0,  3},  /* 4 */
89274              { OP_AddImm,       1, -1,  0},
89275              { OP_String8,      0,  2,  0},  /* 6 */
89276              { OP_String8,      0,  3,  0},  /* 7 */
89277              { OP_Concat,       3,  2,  2},
89278              { OP_ResultRow,    2,  1,  0},
89279           };
89280           addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
89281           sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
89282           sqlite3VdbeJumpHere(v, addr);
89283           addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
89284           sqlite3VdbeChangeP1(v, addr+1, j+2);
89285           sqlite3VdbeChangeP2(v, addr+1, addr+4);
89286           sqlite3VdbeChangeP1(v, addr+3, j+2);
89287           sqlite3VdbeChangeP2(v, addr+3, addr+2);
89288           sqlite3VdbeJumpHere(v, addr+4);
89289           sqlite3VdbeChangeP4(v, addr+6, 
89290                      "wrong # of entries in index ", P4_STATIC);
89291           sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_TRANSIENT);
89292         }
89293       } 
89294     }
89295     addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
89296     sqlite3VdbeChangeP2(v, addr, -mxErr);
89297     sqlite3VdbeJumpHere(v, addr+1);
89298     sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
89299   }else
89300 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
89301
89302 #ifndef SQLITE_OMIT_UTF16
89303   /*
89304   **   PRAGMA encoding
89305   **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
89306   **
89307   ** In its first form, this pragma returns the encoding of the main
89308   ** database. If the database is not initialized, it is initialized now.
89309   **
89310   ** The second form of this pragma is a no-op if the main database file
89311   ** has not already been initialized. In this case it sets the default
89312   ** encoding that will be used for the main database file if a new file
89313   ** is created. If an existing main database file is opened, then the
89314   ** default text encoding for the existing database is used.
89315   ** 
89316   ** In all cases new databases created using the ATTACH command are
89317   ** created to use the same default text encoding as the main database. If
89318   ** the main database has not been initialized and/or created when ATTACH
89319   ** is executed, this is done before the ATTACH operation.
89320   **
89321   ** In the second form this pragma sets the text encoding to be used in
89322   ** new database files created using this database handle. It is only
89323   ** useful if invoked immediately after the main database i
89324   */
89325   if( sqlite3StrICmp(zLeft, "encoding")==0 ){
89326     static const struct EncName {
89327       char *zName;
89328       u8 enc;
89329     } encnames[] = {
89330       { "UTF8",     SQLITE_UTF8        },
89331       { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
89332       { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
89333       { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
89334       { "UTF16le",  SQLITE_UTF16LE     },
89335       { "UTF16be",  SQLITE_UTF16BE     },
89336       { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
89337       { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
89338       { 0, 0 }
89339     };
89340     const struct EncName *pEnc;
89341     if( !zRight ){    /* "PRAGMA encoding" */
89342       if( sqlite3ReadSchema(pParse) ) goto pragma_out;
89343       sqlite3VdbeSetNumCols(v, 1);
89344       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
89345       sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
89346       assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
89347       assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
89348       assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
89349       sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
89350       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
89351     }else{                        /* "PRAGMA encoding = XXX" */
89352       /* Only change the value of sqlite.enc if the database handle is not
89353       ** initialized. If the main database exists, the new sqlite.enc value
89354       ** will be overwritten when the schema is next loaded. If it does not
89355       ** already exists, it will be created to use the new encoding value.
89356       */
89357       if( 
89358         !(DbHasProperty(db, 0, DB_SchemaLoaded)) || 
89359         DbHasProperty(db, 0, DB_Empty) 
89360       ){
89361         for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
89362           if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
89363             ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
89364             break;
89365           }
89366         }
89367         if( !pEnc->zName ){
89368           sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
89369         }
89370       }
89371     }
89372   }else
89373 #endif /* SQLITE_OMIT_UTF16 */
89374
89375 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
89376   /*
89377   **   PRAGMA [database.]schema_version
89378   **   PRAGMA [database.]schema_version = <integer>
89379   **
89380   **   PRAGMA [database.]user_version
89381   **   PRAGMA [database.]user_version = <integer>
89382   **
89383   ** The pragma's schema_version and user_version are used to set or get
89384   ** the value of the schema-version and user-version, respectively. Both
89385   ** the schema-version and the user-version are 32-bit signed integers
89386   ** stored in the database header.
89387   **
89388   ** The schema-cookie is usually only manipulated internally by SQLite. It
89389   ** is incremented by SQLite whenever the database schema is modified (by
89390   ** creating or dropping a table or index). The schema version is used by
89391   ** SQLite each time a query is executed to ensure that the internal cache
89392   ** of the schema used when compiling the SQL query matches the schema of
89393   ** the database against which the compiled query is actually executed.
89394   ** Subverting this mechanism by using "PRAGMA schema_version" to modify
89395   ** the schema-version is potentially dangerous and may lead to program
89396   ** crashes or database corruption. Use with caution!
89397   **
89398   ** The user-version is not used internally by SQLite. It may be used by
89399   ** applications for any purpose.
89400   */
89401   if( sqlite3StrICmp(zLeft, "schema_version")==0 
89402    || sqlite3StrICmp(zLeft, "user_version")==0 
89403    || sqlite3StrICmp(zLeft, "freelist_count")==0 
89404   ){
89405     int iCookie;   /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
89406     sqlite3VdbeUsesBtree(v, iDb);
89407     switch( zLeft[0] ){
89408       case 'f': case 'F':
89409         iCookie = BTREE_FREE_PAGE_COUNT;
89410         break;
89411       case 's': case 'S':
89412         iCookie = BTREE_SCHEMA_VERSION;
89413         break;
89414       default:
89415         iCookie = BTREE_USER_VERSION;
89416         break;
89417     }
89418
89419     if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
89420       /* Write the specified cookie value */
89421       static const VdbeOpList setCookie[] = {
89422         { OP_Transaction,    0,  1,  0},    /* 0 */
89423         { OP_Integer,        0,  1,  0},    /* 1 */
89424         { OP_SetCookie,      0,  0,  1},    /* 2 */
89425       };
89426       int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
89427       sqlite3VdbeChangeP1(v, addr, iDb);
89428       sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
89429       sqlite3VdbeChangeP1(v, addr+2, iDb);
89430       sqlite3VdbeChangeP2(v, addr+2, iCookie);
89431     }else{
89432       /* Read the specified cookie value */
89433       static const VdbeOpList readCookie[] = {
89434         { OP_Transaction,     0,  0,  0},    /* 0 */
89435         { OP_ReadCookie,      0,  1,  0},    /* 1 */
89436         { OP_ResultRow,       1,  1,  0}
89437       };
89438       int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
89439       sqlite3VdbeChangeP1(v, addr, iDb);
89440       sqlite3VdbeChangeP1(v, addr+1, iDb);
89441       sqlite3VdbeChangeP3(v, addr+1, iCookie);
89442       sqlite3VdbeSetNumCols(v, 1);
89443       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
89444     }
89445   }else
89446 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
89447
89448 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
89449   /*
89450   **   PRAGMA compile_options
89451   **
89452   ** Return the names of all compile-time options used in this build,
89453   ** one option per row.
89454   */
89455   if( sqlite3StrICmp(zLeft, "compile_options")==0 ){
89456     int i = 0;
89457     const char *zOpt;
89458     sqlite3VdbeSetNumCols(v, 1);
89459     pParse->nMem = 1;
89460     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
89461     while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
89462       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
89463       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
89464     }
89465   }else
89466 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
89467
89468 #ifndef SQLITE_OMIT_WAL
89469   /*
89470   **   PRAGMA [database.]wal_checkpoint = passive|full|restart
89471   **
89472   ** Checkpoint the database.
89473   */
89474   if( sqlite3StrICmp(zLeft, "wal_checkpoint")==0 ){
89475     int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
89476     int eMode = SQLITE_CHECKPOINT_PASSIVE;
89477     if( zRight ){
89478       if( sqlite3StrICmp(zRight, "full")==0 ){
89479         eMode = SQLITE_CHECKPOINT_FULL;
89480       }else if( sqlite3StrICmp(zRight, "restart")==0 ){
89481         eMode = SQLITE_CHECKPOINT_RESTART;
89482       }
89483     }
89484     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
89485     sqlite3VdbeSetNumCols(v, 3);
89486     pParse->nMem = 3;
89487     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "busy", SQLITE_STATIC);
89488     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "log", SQLITE_STATIC);
89489     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "checkpointed", SQLITE_STATIC);
89490
89491     sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
89492     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
89493   }else
89494
89495   /*
89496   **   PRAGMA wal_autocheckpoint
89497   **   PRAGMA wal_autocheckpoint = N
89498   **
89499   ** Configure a database connection to automatically checkpoint a database
89500   ** after accumulating N frames in the log. Or query for the current value
89501   ** of N.
89502   */
89503   if( sqlite3StrICmp(zLeft, "wal_autocheckpoint")==0 ){
89504     if( zRight ){
89505       sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
89506     }
89507     returnSingleInt(pParse, "wal_autocheckpoint", 
89508        db->xWalCallback==sqlite3WalDefaultHook ? 
89509            SQLITE_PTR_TO_INT(db->pWalArg) : 0);
89510   }else
89511 #endif
89512
89513 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
89514   /*
89515   ** Report the current state of file logs for all databases
89516   */
89517   if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
89518     static const char *const azLockName[] = {
89519       "unlocked", "shared", "reserved", "pending", "exclusive"
89520     };
89521     int i;
89522     sqlite3VdbeSetNumCols(v, 2);
89523     pParse->nMem = 2;
89524     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
89525     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
89526     for(i=0; i<db->nDb; i++){
89527       Btree *pBt;
89528       Pager *pPager;
89529       const char *zState = "unknown";
89530       int j;
89531       if( db->aDb[i].zName==0 ) continue;
89532       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
89533       pBt = db->aDb[i].pBt;
89534       if( pBt==0 || (pPager = sqlite3BtreePager(pBt))==0 ){
89535         zState = "closed";
89536       }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0, 
89537                                      SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
89538          zState = azLockName[j];
89539       }
89540       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
89541       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
89542     }
89543
89544   }else
89545 #endif
89546
89547 #ifdef SQLITE_HAS_CODEC
89548   if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){
89549     sqlite3_key(db, zRight, sqlite3Strlen30(zRight));
89550   }else
89551   if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){
89552     sqlite3_rekey(db, zRight, sqlite3Strlen30(zRight));
89553   }else
89554   if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 ||
89555                  sqlite3StrICmp(zLeft, "hexrekey")==0) ){
89556     int i, h1, h2;
89557     char zKey[40];
89558     for(i=0; (h1 = zRight[i])!=0 && (h2 = zRight[i+1])!=0; i+=2){
89559       h1 += 9*(1&(h1>>6));
89560       h2 += 9*(1&(h2>>6));
89561       zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
89562     }
89563     if( (zLeft[3] & 0xf)==0xb ){
89564       sqlite3_key(db, zKey, i/2);
89565     }else{
89566       sqlite3_rekey(db, zKey, i/2);
89567     }
89568   }else
89569 #endif
89570 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
89571   if( sqlite3StrICmp(zLeft, "activate_extensions")==0 ){
89572 #ifdef SQLITE_HAS_CODEC
89573     if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
89574       sqlite3_activate_see(&zRight[4]);
89575     }
89576 #endif
89577 #ifdef SQLITE_ENABLE_CEROD
89578     if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
89579       sqlite3_activate_cerod(&zRight[6]);
89580     }
89581 #endif
89582   }else
89583 #endif
89584
89585  
89586   {/* Empty ELSE clause */}
89587
89588   /*
89589   ** Reset the safety level, in case the fullfsync flag or synchronous
89590   ** setting changed.
89591   */
89592 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
89593   if( db->autoCommit ){
89594     sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
89595                (db->flags&SQLITE_FullFSync)!=0,
89596                (db->flags&SQLITE_CkptFullFSync)!=0);
89597   }
89598 #endif
89599 pragma_out:
89600   sqlite3DbFree(db, zLeft);
89601   sqlite3DbFree(db, zRight);
89602 }
89603
89604 #endif /* SQLITE_OMIT_PRAGMA */
89605
89606 /************** End of pragma.c **********************************************/
89607 /************** Begin file prepare.c *****************************************/
89608 /*
89609 ** 2005 May 25
89610 **
89611 ** The author disclaims copyright to this source code.  In place of
89612 ** a legal notice, here is a blessing:
89613 **
89614 **    May you do good and not evil.
89615 **    May you find forgiveness for yourself and forgive others.
89616 **    May you share freely, never taking more than you give.
89617 **
89618 *************************************************************************
89619 ** This file contains the implementation of the sqlite3_prepare()
89620 ** interface, and routines that contribute to loading the database schema
89621 ** from disk.
89622 */
89623
89624 /*
89625 ** Fill the InitData structure with an error message that indicates
89626 ** that the database is corrupt.
89627 */
89628 static void corruptSchema(
89629   InitData *pData,     /* Initialization context */
89630   const char *zObj,    /* Object being parsed at the point of error */
89631   const char *zExtra   /* Error information */
89632 ){
89633   sqlite3 *db = pData->db;
89634   if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
89635     if( zObj==0 ) zObj = "?";
89636     sqlite3SetString(pData->pzErrMsg, db,
89637       "malformed database schema (%s)", zObj);
89638     if( zExtra ){
89639       *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg, 
89640                                  "%s - %s", *pData->pzErrMsg, zExtra);
89641     }
89642   }
89643   pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;
89644 }
89645
89646 /*
89647 ** This is the callback routine for the code that initializes the
89648 ** database.  See sqlite3Init() below for additional information.
89649 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
89650 **
89651 ** Each callback contains the following information:
89652 **
89653 **     argv[0] = name of thing being created
89654 **     argv[1] = root page number for table or index. 0 for trigger or view.
89655 **     argv[2] = SQL text for the CREATE statement.
89656 **
89657 */
89658 SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
89659   InitData *pData = (InitData*)pInit;
89660   sqlite3 *db = pData->db;
89661   int iDb = pData->iDb;
89662
89663   assert( argc==3 );
89664   UNUSED_PARAMETER2(NotUsed, argc);
89665   assert( sqlite3_mutex_held(db->mutex) );
89666   DbClearProperty(db, iDb, DB_Empty);
89667   if( db->mallocFailed ){
89668     corruptSchema(pData, argv[0], 0);
89669     return 1;
89670   }
89671
89672   assert( iDb>=0 && iDb<db->nDb );
89673   if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
89674   if( argv[1]==0 ){
89675     corruptSchema(pData, argv[0], 0);
89676   }else if( argv[2] && argv[2][0] ){
89677     /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
89678     ** But because db->init.busy is set to 1, no VDBE code is generated
89679     ** or executed.  All the parser does is build the internal data
89680     ** structures that describe the table, index, or view.
89681     */
89682     int rc;
89683     sqlite3_stmt *pStmt;
89684     TESTONLY(int rcp);            /* Return code from sqlite3_prepare() */
89685
89686     assert( db->init.busy );
89687     db->init.iDb = iDb;
89688     db->init.newTnum = sqlite3Atoi(argv[1]);
89689     db->init.orphanTrigger = 0;
89690     TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
89691     rc = db->errCode;
89692     assert( (rc&0xFF)==(rcp&0xFF) );
89693     db->init.iDb = 0;
89694     if( SQLITE_OK!=rc ){
89695       if( db->init.orphanTrigger ){
89696         assert( iDb==1 );
89697       }else{
89698         pData->rc = rc;
89699         if( rc==SQLITE_NOMEM ){
89700           db->mallocFailed = 1;
89701         }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
89702           corruptSchema(pData, argv[0], sqlite3_errmsg(db));
89703         }
89704       }
89705     }
89706     sqlite3_finalize(pStmt);
89707   }else if( argv[0]==0 ){
89708     corruptSchema(pData, 0, 0);
89709   }else{
89710     /* If the SQL column is blank it means this is an index that
89711     ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
89712     ** constraint for a CREATE TABLE.  The index should have already
89713     ** been created when we processed the CREATE TABLE.  All we have
89714     ** to do here is record the root page number for that index.
89715     */
89716     Index *pIndex;
89717     pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
89718     if( pIndex==0 ){
89719       /* This can occur if there exists an index on a TEMP table which
89720       ** has the same name as another index on a permanent index.  Since
89721       ** the permanent table is hidden by the TEMP table, we can also
89722       ** safely ignore the index on the permanent table.
89723       */
89724       /* Do Nothing */;
89725     }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
89726       corruptSchema(pData, argv[0], "invalid rootpage");
89727     }
89728   }
89729   return 0;
89730 }
89731
89732 /*
89733 ** Attempt to read the database schema and initialize internal
89734 ** data structures for a single database file.  The index of the
89735 ** database file is given by iDb.  iDb==0 is used for the main
89736 ** database.  iDb==1 should never be used.  iDb>=2 is used for
89737 ** auxiliary databases.  Return one of the SQLITE_ error codes to
89738 ** indicate success or failure.
89739 */
89740 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
89741   int rc;
89742   int i;
89743   int size;
89744   Table *pTab;
89745   Db *pDb;
89746   char const *azArg[4];
89747   int meta[5];
89748   InitData initData;
89749   char const *zMasterSchema;
89750   char const *zMasterName;
89751   int openedTransaction = 0;
89752
89753   /*
89754   ** The master database table has a structure like this
89755   */
89756   static const char master_schema[] = 
89757      "CREATE TABLE sqlite_master(\n"
89758      "  type text,\n"
89759      "  name text,\n"
89760      "  tbl_name text,\n"
89761      "  rootpage integer,\n"
89762      "  sql text\n"
89763      ")"
89764   ;
89765 #ifndef SQLITE_OMIT_TEMPDB
89766   static const char temp_master_schema[] = 
89767      "CREATE TEMP TABLE sqlite_temp_master(\n"
89768      "  type text,\n"
89769      "  name text,\n"
89770      "  tbl_name text,\n"
89771      "  rootpage integer,\n"
89772      "  sql text\n"
89773      ")"
89774   ;
89775 #else
89776   #define temp_master_schema 0
89777 #endif
89778
89779   assert( iDb>=0 && iDb<db->nDb );
89780   assert( db->aDb[iDb].pSchema );
89781   assert( sqlite3_mutex_held(db->mutex) );
89782   assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
89783
89784   /* zMasterSchema and zInitScript are set to point at the master schema
89785   ** and initialisation script appropriate for the database being
89786   ** initialised. zMasterName is the name of the master table.
89787   */
89788   if( !OMIT_TEMPDB && iDb==1 ){
89789     zMasterSchema = temp_master_schema;
89790   }else{
89791     zMasterSchema = master_schema;
89792   }
89793   zMasterName = SCHEMA_TABLE(iDb);
89794
89795   /* Construct the schema tables.  */
89796   azArg[0] = zMasterName;
89797   azArg[1] = "1";
89798   azArg[2] = zMasterSchema;
89799   azArg[3] = 0;
89800   initData.db = db;
89801   initData.iDb = iDb;
89802   initData.rc = SQLITE_OK;
89803   initData.pzErrMsg = pzErrMsg;
89804   sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
89805   if( initData.rc ){
89806     rc = initData.rc;
89807     goto error_out;
89808   }
89809   pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
89810   if( ALWAYS(pTab) ){
89811     pTab->tabFlags |= TF_Readonly;
89812   }
89813
89814   /* Create a cursor to hold the database open
89815   */
89816   pDb = &db->aDb[iDb];
89817   if( pDb->pBt==0 ){
89818     if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
89819       DbSetProperty(db, 1, DB_SchemaLoaded);
89820     }
89821     return SQLITE_OK;
89822   }
89823
89824   /* If there is not already a read-only (or read-write) transaction opened
89825   ** on the b-tree database, open one now. If a transaction is opened, it 
89826   ** will be closed before this function returns.  */
89827   sqlite3BtreeEnter(pDb->pBt);
89828   if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
89829     rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
89830     if( rc!=SQLITE_OK ){
89831       sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
89832       goto initone_error_out;
89833     }
89834     openedTransaction = 1;
89835   }
89836
89837   /* Get the database meta information.
89838   **
89839   ** Meta values are as follows:
89840   **    meta[0]   Schema cookie.  Changes with each schema change.
89841   **    meta[1]   File format of schema layer.
89842   **    meta[2]   Size of the page cache.
89843   **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
89844   **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
89845   **    meta[5]   User version
89846   **    meta[6]   Incremental vacuum mode
89847   **    meta[7]   unused
89848   **    meta[8]   unused
89849   **    meta[9]   unused
89850   **
89851   ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
89852   ** the possible values of meta[4].
89853   */
89854   for(i=0; i<ArraySize(meta); i++){
89855     sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
89856   }
89857   pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
89858
89859   /* If opening a non-empty database, check the text encoding. For the
89860   ** main database, set sqlite3.enc to the encoding of the main database.
89861   ** For an attached db, it is an error if the encoding is not the same
89862   ** as sqlite3.enc.
89863   */
89864   if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
89865     if( iDb==0 ){
89866       u8 encoding;
89867       /* If opening the main database, set ENC(db). */
89868       encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
89869       if( encoding==0 ) encoding = SQLITE_UTF8;
89870       ENC(db) = encoding;
89871       db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
89872     }else{
89873       /* If opening an attached database, the encoding much match ENC(db) */
89874       if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
89875         sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
89876             " text encoding as main database");
89877         rc = SQLITE_ERROR;
89878         goto initone_error_out;
89879       }
89880     }
89881   }else{
89882     DbSetProperty(db, iDb, DB_Empty);
89883   }
89884   pDb->pSchema->enc = ENC(db);
89885
89886   if( pDb->pSchema->cache_size==0 ){
89887     size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
89888     if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
89889     pDb->pSchema->cache_size = size;
89890     sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
89891   }
89892
89893   /*
89894   ** file_format==1    Version 3.0.0.
89895   ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
89896   ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
89897   ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
89898   */
89899   pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
89900   if( pDb->pSchema->file_format==0 ){
89901     pDb->pSchema->file_format = 1;
89902   }
89903   if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
89904     sqlite3SetString(pzErrMsg, db, "unsupported file format");
89905     rc = SQLITE_ERROR;
89906     goto initone_error_out;
89907   }
89908
89909   /* Ticket #2804:  When we open a database in the newer file format,
89910   ** clear the legacy_file_format pragma flag so that a VACUUM will
89911   ** not downgrade the database and thus invalidate any descending
89912   ** indices that the user might have created.
89913   */
89914   if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
89915     db->flags &= ~SQLITE_LegacyFileFmt;
89916   }
89917
89918   /* Read the schema information out of the schema tables
89919   */
89920   assert( db->init.busy );
89921   {
89922     char *zSql;
89923     zSql = sqlite3MPrintf(db, 
89924         "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
89925         db->aDb[iDb].zName, zMasterName);
89926 #ifndef SQLITE_OMIT_AUTHORIZATION
89927     {
89928       int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
89929       xAuth = db->xAuth;
89930       db->xAuth = 0;
89931 #endif
89932       rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
89933 #ifndef SQLITE_OMIT_AUTHORIZATION
89934       db->xAuth = xAuth;
89935     }
89936 #endif
89937     if( rc==SQLITE_OK ) rc = initData.rc;
89938     sqlite3DbFree(db, zSql);
89939 #ifndef SQLITE_OMIT_ANALYZE
89940     if( rc==SQLITE_OK ){
89941       sqlite3AnalysisLoad(db, iDb);
89942     }
89943 #endif
89944   }
89945   if( db->mallocFailed ){
89946     rc = SQLITE_NOMEM;
89947     sqlite3ResetInternalSchema(db, -1);
89948   }
89949   if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
89950     /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
89951     ** the schema loaded, even if errors occurred. In this situation the 
89952     ** current sqlite3_prepare() operation will fail, but the following one
89953     ** will attempt to compile the supplied statement against whatever subset
89954     ** of the schema was loaded before the error occurred. The primary
89955     ** purpose of this is to allow access to the sqlite_master table
89956     ** even when its contents have been corrupted.
89957     */
89958     DbSetProperty(db, iDb, DB_SchemaLoaded);
89959     rc = SQLITE_OK;
89960   }
89961
89962   /* Jump here for an error that occurs after successfully allocating
89963   ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
89964   ** before that point, jump to error_out.
89965   */
89966 initone_error_out:
89967   if( openedTransaction ){
89968     sqlite3BtreeCommit(pDb->pBt);
89969   }
89970   sqlite3BtreeLeave(pDb->pBt);
89971
89972 error_out:
89973   if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
89974     db->mallocFailed = 1;
89975   }
89976   return rc;
89977 }
89978
89979 /*
89980 ** Initialize all database files - the main database file, the file
89981 ** used to store temporary tables, and any additional database files
89982 ** created using ATTACH statements.  Return a success code.  If an
89983 ** error occurs, write an error message into *pzErrMsg.
89984 **
89985 ** After a database is initialized, the DB_SchemaLoaded bit is set
89986 ** bit is set in the flags field of the Db structure. If the database
89987 ** file was of zero-length, then the DB_Empty flag is also set.
89988 */
89989 SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
89990   int i, rc;
89991   int commit_internal = !(db->flags&SQLITE_InternChanges);
89992   
89993   assert( sqlite3_mutex_held(db->mutex) );
89994   rc = SQLITE_OK;
89995   db->init.busy = 1;
89996   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
89997     if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
89998     rc = sqlite3InitOne(db, i, pzErrMsg);
89999     if( rc ){
90000       sqlite3ResetInternalSchema(db, i);
90001     }
90002   }
90003
90004   /* Once all the other databases have been initialised, load the schema
90005   ** for the TEMP database. This is loaded last, as the TEMP database
90006   ** schema may contain references to objects in other databases.
90007   */
90008 #ifndef SQLITE_OMIT_TEMPDB
90009   if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
90010                     && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
90011     rc = sqlite3InitOne(db, 1, pzErrMsg);
90012     if( rc ){
90013       sqlite3ResetInternalSchema(db, 1);
90014     }
90015   }
90016 #endif
90017
90018   db->init.busy = 0;
90019   if( rc==SQLITE_OK && commit_internal ){
90020     sqlite3CommitInternalChanges(db);
90021   }
90022
90023   return rc; 
90024 }
90025
90026 /*
90027 ** This routine is a no-op if the database schema is already initialised.
90028 ** Otherwise, the schema is loaded. An error code is returned.
90029 */
90030 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
90031   int rc = SQLITE_OK;
90032   sqlite3 *db = pParse->db;
90033   assert( sqlite3_mutex_held(db->mutex) );
90034   if( !db->init.busy ){
90035     rc = sqlite3Init(db, &pParse->zErrMsg);
90036   }
90037   if( rc!=SQLITE_OK ){
90038     pParse->rc = rc;
90039     pParse->nErr++;
90040   }
90041   return rc;
90042 }
90043
90044
90045 /*
90046 ** Check schema cookies in all databases.  If any cookie is out
90047 ** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
90048 ** make no changes to pParse->rc.
90049 */
90050 static void schemaIsValid(Parse *pParse){
90051   sqlite3 *db = pParse->db;
90052   int iDb;
90053   int rc;
90054   int cookie;
90055
90056   assert( pParse->checkSchema );
90057   assert( sqlite3_mutex_held(db->mutex) );
90058   for(iDb=0; iDb<db->nDb; iDb++){
90059     int openedTransaction = 0;         /* True if a transaction is opened */
90060     Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
90061     if( pBt==0 ) continue;
90062
90063     /* If there is not already a read-only (or read-write) transaction opened
90064     ** on the b-tree database, open one now. If a transaction is opened, it 
90065     ** will be closed immediately after reading the meta-value. */
90066     if( !sqlite3BtreeIsInReadTrans(pBt) ){
90067       rc = sqlite3BtreeBeginTrans(pBt, 0);
90068       if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
90069         db->mallocFailed = 1;
90070       }
90071       if( rc!=SQLITE_OK ) return;
90072       openedTransaction = 1;
90073     }
90074
90075     /* Read the schema cookie from the database. If it does not match the 
90076     ** value stored as part of the in-memory schema representation,
90077     ** set Parse.rc to SQLITE_SCHEMA. */
90078     sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
90079     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
90080     if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
90081       sqlite3ResetInternalSchema(db, iDb);
90082       pParse->rc = SQLITE_SCHEMA;
90083     }
90084
90085     /* Close the transaction, if one was opened. */
90086     if( openedTransaction ){
90087       sqlite3BtreeCommit(pBt);
90088     }
90089   }
90090 }
90091
90092 /*
90093 ** Convert a schema pointer into the iDb index that indicates
90094 ** which database file in db->aDb[] the schema refers to.
90095 **
90096 ** If the same database is attached more than once, the first
90097 ** attached database is returned.
90098 */
90099 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
90100   int i = -1000000;
90101
90102   /* If pSchema is NULL, then return -1000000. This happens when code in 
90103   ** expr.c is trying to resolve a reference to a transient table (i.e. one
90104   ** created by a sub-select). In this case the return value of this 
90105   ** function should never be used.
90106   **
90107   ** We return -1000000 instead of the more usual -1 simply because using
90108   ** -1000000 as the incorrect index into db->aDb[] is much 
90109   ** more likely to cause a segfault than -1 (of course there are assert()
90110   ** statements too, but it never hurts to play the odds).
90111   */
90112   assert( sqlite3_mutex_held(db->mutex) );
90113   if( pSchema ){
90114     for(i=0; ALWAYS(i<db->nDb); i++){
90115       if( db->aDb[i].pSchema==pSchema ){
90116         break;
90117       }
90118     }
90119     assert( i>=0 && i<db->nDb );
90120   }
90121   return i;
90122 }
90123
90124 /*
90125 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
90126 */
90127 static int sqlite3Prepare(
90128   sqlite3 *db,              /* Database handle. */
90129   const char *zSql,         /* UTF-8 encoded SQL statement. */
90130   int nBytes,               /* Length of zSql in bytes. */
90131   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
90132   Vdbe *pReprepare,         /* VM being reprepared */
90133   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
90134   const char **pzTail       /* OUT: End of parsed string */
90135 ){
90136   Parse *pParse;            /* Parsing context */
90137   char *zErrMsg = 0;        /* Error message */
90138   int rc = SQLITE_OK;       /* Result code */
90139   int i;                    /* Loop counter */
90140
90141   /* Allocate the parsing context */
90142   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
90143   if( pParse==0 ){
90144     rc = SQLITE_NOMEM;
90145     goto end_prepare;
90146   }
90147   pParse->pReprepare = pReprepare;
90148   assert( ppStmt && *ppStmt==0 );
90149   assert( !db->mallocFailed );
90150   assert( sqlite3_mutex_held(db->mutex) );
90151
90152   /* Check to verify that it is possible to get a read lock on all
90153   ** database schemas.  The inability to get a read lock indicates that
90154   ** some other database connection is holding a write-lock, which in
90155   ** turn means that the other connection has made uncommitted changes
90156   ** to the schema.
90157   **
90158   ** Were we to proceed and prepare the statement against the uncommitted
90159   ** schema changes and if those schema changes are subsequently rolled
90160   ** back and different changes are made in their place, then when this
90161   ** prepared statement goes to run the schema cookie would fail to detect
90162   ** the schema change.  Disaster would follow.
90163   **
90164   ** This thread is currently holding mutexes on all Btrees (because
90165   ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
90166   ** is not possible for another thread to start a new schema change
90167   ** while this routine is running.  Hence, we do not need to hold 
90168   ** locks on the schema, we just need to make sure nobody else is 
90169   ** holding them.
90170   **
90171   ** Note that setting READ_UNCOMMITTED overrides most lock detection,
90172   ** but it does *not* override schema lock detection, so this all still
90173   ** works even if READ_UNCOMMITTED is set.
90174   */
90175   for(i=0; i<db->nDb; i++) {
90176     Btree *pBt = db->aDb[i].pBt;
90177     if( pBt ){
90178       assert( sqlite3BtreeHoldsMutex(pBt) );
90179       rc = sqlite3BtreeSchemaLocked(pBt);
90180       if( rc ){
90181         const char *zDb = db->aDb[i].zName;
90182         sqlite3Error(db, rc, "database schema is locked: %s", zDb);
90183         testcase( db->flags & SQLITE_ReadUncommitted );
90184         goto end_prepare;
90185       }
90186     }
90187   }
90188
90189   sqlite3VtabUnlockList(db);
90190
90191   pParse->db = db;
90192   pParse->nQueryLoop = (double)1;
90193   if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
90194     char *zSqlCopy;
90195     int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
90196     testcase( nBytes==mxLen );
90197     testcase( nBytes==mxLen+1 );
90198     if( nBytes>mxLen ){
90199       sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
90200       rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
90201       goto end_prepare;
90202     }
90203     zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
90204     if( zSqlCopy ){
90205       sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
90206       sqlite3DbFree(db, zSqlCopy);
90207       pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
90208     }else{
90209       pParse->zTail = &zSql[nBytes];
90210     }
90211   }else{
90212     sqlite3RunParser(pParse, zSql, &zErrMsg);
90213   }
90214   assert( 1==(int)pParse->nQueryLoop );
90215
90216   if( db->mallocFailed ){
90217     pParse->rc = SQLITE_NOMEM;
90218   }
90219   if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
90220   if( pParse->checkSchema ){
90221     schemaIsValid(pParse);
90222   }
90223   if( db->mallocFailed ){
90224     pParse->rc = SQLITE_NOMEM;
90225   }
90226   if( pzTail ){
90227     *pzTail = pParse->zTail;
90228   }
90229   rc = pParse->rc;
90230
90231 #ifndef SQLITE_OMIT_EXPLAIN
90232   if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
90233     static const char * const azColName[] = {
90234        "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
90235        "selectid", "order", "from", "detail"
90236     };
90237     int iFirst, mx;
90238     if( pParse->explain==2 ){
90239       sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
90240       iFirst = 8;
90241       mx = 12;
90242     }else{
90243       sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
90244       iFirst = 0;
90245       mx = 8;
90246     }
90247     for(i=iFirst; i<mx; i++){
90248       sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
90249                             azColName[i], SQLITE_STATIC);
90250     }
90251   }
90252 #endif
90253
90254   assert( db->init.busy==0 || saveSqlFlag==0 );
90255   if( db->init.busy==0 ){
90256     Vdbe *pVdbe = pParse->pVdbe;
90257     sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
90258   }
90259   if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
90260     sqlite3VdbeFinalize(pParse->pVdbe);
90261     assert(!(*ppStmt));
90262   }else{
90263     *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
90264   }
90265
90266   if( zErrMsg ){
90267     sqlite3Error(db, rc, "%s", zErrMsg);
90268     sqlite3DbFree(db, zErrMsg);
90269   }else{
90270     sqlite3Error(db, rc, 0);
90271   }
90272
90273   /* Delete any TriggerPrg structures allocated while parsing this statement. */
90274   while( pParse->pTriggerPrg ){
90275     TriggerPrg *pT = pParse->pTriggerPrg;
90276     pParse->pTriggerPrg = pT->pNext;
90277     sqlite3DbFree(db, pT);
90278   }
90279
90280 end_prepare:
90281
90282   sqlite3StackFree(db, pParse);
90283   rc = sqlite3ApiExit(db, rc);
90284   assert( (rc&db->errMask)==rc );
90285   return rc;
90286 }
90287 static int sqlite3LockAndPrepare(
90288   sqlite3 *db,              /* Database handle. */
90289   const char *zSql,         /* UTF-8 encoded SQL statement. */
90290   int nBytes,               /* Length of zSql in bytes. */
90291   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
90292   Vdbe *pOld,               /* VM being reprepared */
90293   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
90294   const char **pzTail       /* OUT: End of parsed string */
90295 ){
90296   int rc;
90297   assert( ppStmt!=0 );
90298   *ppStmt = 0;
90299   if( !sqlite3SafetyCheckOk(db) ){
90300     return SQLITE_MISUSE_BKPT;
90301   }
90302   sqlite3_mutex_enter(db->mutex);
90303   sqlite3BtreeEnterAll(db);
90304   rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
90305   if( rc==SQLITE_SCHEMA ){
90306     sqlite3_finalize(*ppStmt);
90307     rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
90308   }
90309   sqlite3BtreeLeaveAll(db);
90310   sqlite3_mutex_leave(db->mutex);
90311   return rc;
90312 }
90313
90314 /*
90315 ** Rerun the compilation of a statement after a schema change.
90316 **
90317 ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
90318 ** if the statement cannot be recompiled because another connection has
90319 ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
90320 ** occurs, return SQLITE_SCHEMA.
90321 */
90322 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
90323   int rc;
90324   sqlite3_stmt *pNew;
90325   const char *zSql;
90326   sqlite3 *db;
90327
90328   assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
90329   zSql = sqlite3_sql((sqlite3_stmt *)p);
90330   assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
90331   db = sqlite3VdbeDb(p);
90332   assert( sqlite3_mutex_held(db->mutex) );
90333   rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
90334   if( rc ){
90335     if( rc==SQLITE_NOMEM ){
90336       db->mallocFailed = 1;
90337     }
90338     assert( pNew==0 );
90339     return rc;
90340   }else{
90341     assert( pNew!=0 );
90342   }
90343   sqlite3VdbeSwap((Vdbe*)pNew, p);
90344   sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
90345   sqlite3VdbeResetStepResult((Vdbe*)pNew);
90346   sqlite3VdbeFinalize((Vdbe*)pNew);
90347   return SQLITE_OK;
90348 }
90349
90350
90351 /*
90352 ** Two versions of the official API.  Legacy and new use.  In the legacy
90353 ** version, the original SQL text is not saved in the prepared statement
90354 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
90355 ** sqlite3_step().  In the new version, the original SQL text is retained
90356 ** and the statement is automatically recompiled if an schema change
90357 ** occurs.
90358 */
90359 SQLITE_API int sqlite3_prepare(
90360   sqlite3 *db,              /* Database handle. */
90361   const char *zSql,         /* UTF-8 encoded SQL statement. */
90362   int nBytes,               /* Length of zSql in bytes. */
90363   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
90364   const char **pzTail       /* OUT: End of parsed string */
90365 ){
90366   int rc;
90367   rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
90368   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
90369   return rc;
90370 }
90371 SQLITE_API int sqlite3_prepare_v2(
90372   sqlite3 *db,              /* Database handle. */
90373   const char *zSql,         /* UTF-8 encoded SQL statement. */
90374   int nBytes,               /* Length of zSql in bytes. */
90375   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
90376   const char **pzTail       /* OUT: End of parsed string */
90377 ){
90378   int rc;
90379   rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
90380   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
90381   return rc;
90382 }
90383
90384
90385 #ifndef SQLITE_OMIT_UTF16
90386 /*
90387 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
90388 */
90389 static int sqlite3Prepare16(
90390   sqlite3 *db,              /* Database handle. */ 
90391   const void *zSql,         /* UTF-16 encoded SQL statement. */
90392   int nBytes,               /* Length of zSql in bytes. */
90393   int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
90394   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
90395   const void **pzTail       /* OUT: End of parsed string */
90396 ){
90397   /* This function currently works by first transforming the UTF-16
90398   ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
90399   ** tricky bit is figuring out the pointer to return in *pzTail.
90400   */
90401   char *zSql8;
90402   const char *zTail8 = 0;
90403   int rc = SQLITE_OK;
90404
90405   assert( ppStmt );
90406   *ppStmt = 0;
90407   if( !sqlite3SafetyCheckOk(db) ){
90408     return SQLITE_MISUSE_BKPT;
90409   }
90410   sqlite3_mutex_enter(db->mutex);
90411   zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
90412   if( zSql8 ){
90413     rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
90414   }
90415
90416   if( zTail8 && pzTail ){
90417     /* If sqlite3_prepare returns a tail pointer, we calculate the
90418     ** equivalent pointer into the UTF-16 string by counting the unicode
90419     ** characters between zSql8 and zTail8, and then returning a pointer
90420     ** the same number of characters into the UTF-16 string.
90421     */
90422     int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
90423     *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
90424   }
90425   sqlite3DbFree(db, zSql8); 
90426   rc = sqlite3ApiExit(db, rc);
90427   sqlite3_mutex_leave(db->mutex);
90428   return rc;
90429 }
90430
90431 /*
90432 ** Two versions of the official API.  Legacy and new use.  In the legacy
90433 ** version, the original SQL text is not saved in the prepared statement
90434 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
90435 ** sqlite3_step().  In the new version, the original SQL text is retained
90436 ** and the statement is automatically recompiled if an schema change
90437 ** occurs.
90438 */
90439 SQLITE_API int sqlite3_prepare16(
90440   sqlite3 *db,              /* Database handle. */ 
90441   const void *zSql,         /* UTF-16 encoded SQL statement. */
90442   int nBytes,               /* Length of zSql in bytes. */
90443   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
90444   const void **pzTail       /* OUT: End of parsed string */
90445 ){
90446   int rc;
90447   rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
90448   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
90449   return rc;
90450 }
90451 SQLITE_API int sqlite3_prepare16_v2(
90452   sqlite3 *db,              /* Database handle. */ 
90453   const void *zSql,         /* UTF-16 encoded SQL statement. */
90454   int nBytes,               /* Length of zSql in bytes. */
90455   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
90456   const void **pzTail       /* OUT: End of parsed string */
90457 ){
90458   int rc;
90459   rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
90460   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
90461   return rc;
90462 }
90463
90464 #endif /* SQLITE_OMIT_UTF16 */
90465
90466 /************** End of prepare.c *********************************************/
90467 /************** Begin file select.c ******************************************/
90468 /*
90469 ** 2001 September 15
90470 **
90471 ** The author disclaims copyright to this source code.  In place of
90472 ** a legal notice, here is a blessing:
90473 **
90474 **    May you do good and not evil.
90475 **    May you find forgiveness for yourself and forgive others.
90476 **    May you share freely, never taking more than you give.
90477 **
90478 *************************************************************************
90479 ** This file contains C code routines that are called by the parser
90480 ** to handle SELECT statements in SQLite.
90481 */
90482
90483
90484 /*
90485 ** Delete all the content of a Select structure but do not deallocate
90486 ** the select structure itself.
90487 */
90488 static void clearSelect(sqlite3 *db, Select *p){
90489   sqlite3ExprListDelete(db, p->pEList);
90490   sqlite3SrcListDelete(db, p->pSrc);
90491   sqlite3ExprDelete(db, p->pWhere);
90492   sqlite3ExprListDelete(db, p->pGroupBy);
90493   sqlite3ExprDelete(db, p->pHaving);
90494   sqlite3ExprListDelete(db, p->pOrderBy);
90495   sqlite3SelectDelete(db, p->pPrior);
90496   sqlite3ExprDelete(db, p->pLimit);
90497   sqlite3ExprDelete(db, p->pOffset);
90498 }
90499
90500 /*
90501 ** Initialize a SelectDest structure.
90502 */
90503 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
90504   pDest->eDest = (u8)eDest;
90505   pDest->iParm = iParm;
90506   pDest->affinity = 0;
90507   pDest->iMem = 0;
90508   pDest->nMem = 0;
90509 }
90510
90511
90512 /*
90513 ** Allocate a new Select structure and return a pointer to that
90514 ** structure.
90515 */
90516 SQLITE_PRIVATE Select *sqlite3SelectNew(
90517   Parse *pParse,        /* Parsing context */
90518   ExprList *pEList,     /* which columns to include in the result */
90519   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
90520   Expr *pWhere,         /* the WHERE clause */
90521   ExprList *pGroupBy,   /* the GROUP BY clause */
90522   Expr *pHaving,        /* the HAVING clause */
90523   ExprList *pOrderBy,   /* the ORDER BY clause */
90524   int isDistinct,       /* true if the DISTINCT keyword is present */
90525   Expr *pLimit,         /* LIMIT value.  NULL means not used */
90526   Expr *pOffset         /* OFFSET value.  NULL means no offset */
90527 ){
90528   Select *pNew;
90529   Select standin;
90530   sqlite3 *db = pParse->db;
90531   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
90532   assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
90533   if( pNew==0 ){
90534     pNew = &standin;
90535     memset(pNew, 0, sizeof(*pNew));
90536   }
90537   if( pEList==0 ){
90538     pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
90539   }
90540   pNew->pEList = pEList;
90541   pNew->pSrc = pSrc;
90542   pNew->pWhere = pWhere;
90543   pNew->pGroupBy = pGroupBy;
90544   pNew->pHaving = pHaving;
90545   pNew->pOrderBy = pOrderBy;
90546   pNew->selFlags = isDistinct ? SF_Distinct : 0;
90547   pNew->op = TK_SELECT;
90548   pNew->pLimit = pLimit;
90549   pNew->pOffset = pOffset;
90550   assert( pOffset==0 || pLimit!=0 );
90551   pNew->addrOpenEphm[0] = -1;
90552   pNew->addrOpenEphm[1] = -1;
90553   pNew->addrOpenEphm[2] = -1;
90554   if( db->mallocFailed ) {
90555     clearSelect(db, pNew);
90556     if( pNew!=&standin ) sqlite3DbFree(db, pNew);
90557     pNew = 0;
90558   }
90559   return pNew;
90560 }
90561
90562 /*
90563 ** Delete the given Select structure and all of its substructures.
90564 */
90565 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
90566   if( p ){
90567     clearSelect(db, p);
90568     sqlite3DbFree(db, p);
90569   }
90570 }
90571
90572 /*
90573 ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
90574 ** type of join.  Return an integer constant that expresses that type
90575 ** in terms of the following bit values:
90576 **
90577 **     JT_INNER
90578 **     JT_CROSS
90579 **     JT_OUTER
90580 **     JT_NATURAL
90581 **     JT_LEFT
90582 **     JT_RIGHT
90583 **
90584 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
90585 **
90586 ** If an illegal or unsupported join type is seen, then still return
90587 ** a join type, but put an error in the pParse structure.
90588 */
90589 SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
90590   int jointype = 0;
90591   Token *apAll[3];
90592   Token *p;
90593                              /*   0123456789 123456789 123456789 123 */
90594   static const char zKeyText[] = "naturaleftouterightfullinnercross";
90595   static const struct {
90596     u8 i;        /* Beginning of keyword text in zKeyText[] */
90597     u8 nChar;    /* Length of the keyword in characters */
90598     u8 code;     /* Join type mask */
90599   } aKeyword[] = {
90600     /* natural */ { 0,  7, JT_NATURAL                },
90601     /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
90602     /* outer   */ { 10, 5, JT_OUTER                  },
90603     /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
90604     /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
90605     /* inner   */ { 23, 5, JT_INNER                  },
90606     /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
90607   };
90608   int i, j;
90609   apAll[0] = pA;
90610   apAll[1] = pB;
90611   apAll[2] = pC;
90612   for(i=0; i<3 && apAll[i]; i++){
90613     p = apAll[i];
90614     for(j=0; j<ArraySize(aKeyword); j++){
90615       if( p->n==aKeyword[j].nChar 
90616           && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
90617         jointype |= aKeyword[j].code;
90618         break;
90619       }
90620     }
90621     testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
90622     if( j>=ArraySize(aKeyword) ){
90623       jointype |= JT_ERROR;
90624       break;
90625     }
90626   }
90627   if(
90628      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
90629      (jointype & JT_ERROR)!=0
90630   ){
90631     const char *zSp = " ";
90632     assert( pB!=0 );
90633     if( pC==0 ){ zSp++; }
90634     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
90635        "%T %T%s%T", pA, pB, zSp, pC);
90636     jointype = JT_INNER;
90637   }else if( (jointype & JT_OUTER)!=0 
90638          && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
90639     sqlite3ErrorMsg(pParse, 
90640       "RIGHT and FULL OUTER JOINs are not currently supported");
90641     jointype = JT_INNER;
90642   }
90643   return jointype;
90644 }
90645
90646 /*
90647 ** Return the index of a column in a table.  Return -1 if the column
90648 ** is not contained in the table.
90649 */
90650 static int columnIndex(Table *pTab, const char *zCol){
90651   int i;
90652   for(i=0; i<pTab->nCol; i++){
90653     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
90654   }
90655   return -1;
90656 }
90657
90658 /*
90659 ** Search the first N tables in pSrc, from left to right, looking for a
90660 ** table that has a column named zCol.  
90661 **
90662 ** When found, set *piTab and *piCol to the table index and column index
90663 ** of the matching column and return TRUE.
90664 **
90665 ** If not found, return FALSE.
90666 */
90667 static int tableAndColumnIndex(
90668   SrcList *pSrc,       /* Array of tables to search */
90669   int N,               /* Number of tables in pSrc->a[] to search */
90670   const char *zCol,    /* Name of the column we are looking for */
90671   int *piTab,          /* Write index of pSrc->a[] here */
90672   int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
90673 ){
90674   int i;               /* For looping over tables in pSrc */
90675   int iCol;            /* Index of column matching zCol */
90676
90677   assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
90678   for(i=0; i<N; i++){
90679     iCol = columnIndex(pSrc->a[i].pTab, zCol);
90680     if( iCol>=0 ){
90681       if( piTab ){
90682         *piTab = i;
90683         *piCol = iCol;
90684       }
90685       return 1;
90686     }
90687   }
90688   return 0;
90689 }
90690
90691 /*
90692 ** This function is used to add terms implied by JOIN syntax to the
90693 ** WHERE clause expression of a SELECT statement. The new term, which
90694 ** is ANDed with the existing WHERE clause, is of the form:
90695 **
90696 **    (tab1.col1 = tab2.col2)
90697 **
90698 ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the 
90699 ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
90700 ** column iColRight of tab2.
90701 */
90702 static void addWhereTerm(
90703   Parse *pParse,                  /* Parsing context */
90704   SrcList *pSrc,                  /* List of tables in FROM clause */
90705   int iLeft,                      /* Index of first table to join in pSrc */
90706   int iColLeft,                   /* Index of column in first table */
90707   int iRight,                     /* Index of second table in pSrc */
90708   int iColRight,                  /* Index of column in second table */
90709   int isOuterJoin,                /* True if this is an OUTER join */
90710   Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
90711 ){
90712   sqlite3 *db = pParse->db;
90713   Expr *pE1;
90714   Expr *pE2;
90715   Expr *pEq;
90716
90717   assert( iLeft<iRight );
90718   assert( pSrc->nSrc>iRight );
90719   assert( pSrc->a[iLeft].pTab );
90720   assert( pSrc->a[iRight].pTab );
90721
90722   pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
90723   pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
90724
90725   pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
90726   if( pEq && isOuterJoin ){
90727     ExprSetProperty(pEq, EP_FromJoin);
90728     assert( !ExprHasAnyProperty(pEq, EP_TokenOnly|EP_Reduced) );
90729     ExprSetIrreducible(pEq);
90730     pEq->iRightJoinTable = (i16)pE2->iTable;
90731   }
90732   *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
90733 }
90734
90735 /*
90736 ** Set the EP_FromJoin property on all terms of the given expression.
90737 ** And set the Expr.iRightJoinTable to iTable for every term in the
90738 ** expression.
90739 **
90740 ** The EP_FromJoin property is used on terms of an expression to tell
90741 ** the LEFT OUTER JOIN processing logic that this term is part of the
90742 ** join restriction specified in the ON or USING clause and not a part
90743 ** of the more general WHERE clause.  These terms are moved over to the
90744 ** WHERE clause during join processing but we need to remember that they
90745 ** originated in the ON or USING clause.
90746 **
90747 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
90748 ** expression depends on table iRightJoinTable even if that table is not
90749 ** explicitly mentioned in the expression.  That information is needed
90750 ** for cases like this:
90751 **
90752 **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
90753 **
90754 ** The where clause needs to defer the handling of the t1.x=5
90755 ** term until after the t2 loop of the join.  In that way, a
90756 ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
90757 ** defer the handling of t1.x=5, it will be processed immediately
90758 ** after the t1 loop and rows with t1.x!=5 will never appear in
90759 ** the output, which is incorrect.
90760 */
90761 static void setJoinExpr(Expr *p, int iTable){
90762   while( p ){
90763     ExprSetProperty(p, EP_FromJoin);
90764     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
90765     ExprSetIrreducible(p);
90766     p->iRightJoinTable = (i16)iTable;
90767     setJoinExpr(p->pLeft, iTable);
90768     p = p->pRight;
90769   } 
90770 }
90771
90772 /*
90773 ** This routine processes the join information for a SELECT statement.
90774 ** ON and USING clauses are converted into extra terms of the WHERE clause.
90775 ** NATURAL joins also create extra WHERE clause terms.
90776 **
90777 ** The terms of a FROM clause are contained in the Select.pSrc structure.
90778 ** The left most table is the first entry in Select.pSrc.  The right-most
90779 ** table is the last entry.  The join operator is held in the entry to
90780 ** the left.  Thus entry 0 contains the join operator for the join between
90781 ** entries 0 and 1.  Any ON or USING clauses associated with the join are
90782 ** also attached to the left entry.
90783 **
90784 ** This routine returns the number of errors encountered.
90785 */
90786 static int sqliteProcessJoin(Parse *pParse, Select *p){
90787   SrcList *pSrc;                  /* All tables in the FROM clause */
90788   int i, j;                       /* Loop counters */
90789   struct SrcList_item *pLeft;     /* Left table being joined */
90790   struct SrcList_item *pRight;    /* Right table being joined */
90791
90792   pSrc = p->pSrc;
90793   pLeft = &pSrc->a[0];
90794   pRight = &pLeft[1];
90795   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
90796     Table *pLeftTab = pLeft->pTab;
90797     Table *pRightTab = pRight->pTab;
90798     int isOuter;
90799
90800     if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
90801     isOuter = (pRight->jointype & JT_OUTER)!=0;
90802
90803     /* When the NATURAL keyword is present, add WHERE clause terms for
90804     ** every column that the two tables have in common.
90805     */
90806     if( pRight->jointype & JT_NATURAL ){
90807       if( pRight->pOn || pRight->pUsing ){
90808         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
90809            "an ON or USING clause", 0);
90810         return 1;
90811       }
90812       for(j=0; j<pRightTab->nCol; j++){
90813         char *zName;   /* Name of column in the right table */
90814         int iLeft;     /* Matching left table */
90815         int iLeftCol;  /* Matching column in the left table */
90816
90817         zName = pRightTab->aCol[j].zName;
90818         if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
90819           addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
90820                        isOuter, &p->pWhere);
90821         }
90822       }
90823     }
90824
90825     /* Disallow both ON and USING clauses in the same join
90826     */
90827     if( pRight->pOn && pRight->pUsing ){
90828       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
90829         "clauses in the same join");
90830       return 1;
90831     }
90832
90833     /* Add the ON clause to the end of the WHERE clause, connected by
90834     ** an AND operator.
90835     */
90836     if( pRight->pOn ){
90837       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
90838       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
90839       pRight->pOn = 0;
90840     }
90841
90842     /* Create extra terms on the WHERE clause for each column named
90843     ** in the USING clause.  Example: If the two tables to be joined are 
90844     ** A and B and the USING clause names X, Y, and Z, then add this
90845     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
90846     ** Report an error if any column mentioned in the USING clause is
90847     ** not contained in both tables to be joined.
90848     */
90849     if( pRight->pUsing ){
90850       IdList *pList = pRight->pUsing;
90851       for(j=0; j<pList->nId; j++){
90852         char *zName;     /* Name of the term in the USING clause */
90853         int iLeft;       /* Table on the left with matching column name */
90854         int iLeftCol;    /* Column number of matching column on the left */
90855         int iRightCol;   /* Column number of matching column on the right */
90856
90857         zName = pList->a[j].zName;
90858         iRightCol = columnIndex(pRightTab, zName);
90859         if( iRightCol<0
90860          || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
90861         ){
90862           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
90863             "not present in both tables", zName);
90864           return 1;
90865         }
90866         addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
90867                      isOuter, &p->pWhere);
90868       }
90869     }
90870   }
90871   return 0;
90872 }
90873
90874 /*
90875 ** Insert code into "v" that will push the record on the top of the
90876 ** stack into the sorter.
90877 */
90878 static void pushOntoSorter(
90879   Parse *pParse,         /* Parser context */
90880   ExprList *pOrderBy,    /* The ORDER BY clause */
90881   Select *pSelect,       /* The whole SELECT statement */
90882   int regData            /* Register holding data to be sorted */
90883 ){
90884   Vdbe *v = pParse->pVdbe;
90885   int nExpr = pOrderBy->nExpr;
90886   int regBase = sqlite3GetTempRange(pParse, nExpr+2);
90887   int regRecord = sqlite3GetTempReg(pParse);
90888   sqlite3ExprCacheClear(pParse);
90889   sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
90890   sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
90891   sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
90892   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
90893   sqlite3VdbeAddOp2(v, OP_IdxInsert, pOrderBy->iECursor, regRecord);
90894   sqlite3ReleaseTempReg(pParse, regRecord);
90895   sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
90896   if( pSelect->iLimit ){
90897     int addr1, addr2;
90898     int iLimit;
90899     if( pSelect->iOffset ){
90900       iLimit = pSelect->iOffset+1;
90901     }else{
90902       iLimit = pSelect->iLimit;
90903     }
90904     addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
90905     sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
90906     addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
90907     sqlite3VdbeJumpHere(v, addr1);
90908     sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
90909     sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
90910     sqlite3VdbeJumpHere(v, addr2);
90911   }
90912 }
90913
90914 /*
90915 ** Add code to implement the OFFSET
90916 */
90917 static void codeOffset(
90918   Vdbe *v,          /* Generate code into this VM */
90919   Select *p,        /* The SELECT statement being coded */
90920   int iContinue     /* Jump here to skip the current record */
90921 ){
90922   if( p->iOffset && iContinue!=0 ){
90923     int addr;
90924     sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
90925     addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
90926     sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
90927     VdbeComment((v, "skip OFFSET records"));
90928     sqlite3VdbeJumpHere(v, addr);
90929   }
90930 }
90931
90932 /*
90933 ** Add code that will check to make sure the N registers starting at iMem
90934 ** form a distinct entry.  iTab is a sorting index that holds previously
90935 ** seen combinations of the N values.  A new entry is made in iTab
90936 ** if the current N values are new.
90937 **
90938 ** A jump to addrRepeat is made and the N+1 values are popped from the
90939 ** stack if the top N elements are not distinct.
90940 */
90941 static void codeDistinct(
90942   Parse *pParse,     /* Parsing and code generating context */
90943   int iTab,          /* A sorting index used to test for distinctness */
90944   int addrRepeat,    /* Jump to here if not distinct */
90945   int N,             /* Number of elements */
90946   int iMem           /* First element */
90947 ){
90948   Vdbe *v;
90949   int r1;
90950
90951   v = pParse->pVdbe;
90952   r1 = sqlite3GetTempReg(pParse);
90953   sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
90954   sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
90955   sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
90956   sqlite3ReleaseTempReg(pParse, r1);
90957 }
90958
90959 #ifndef SQLITE_OMIT_SUBQUERY
90960 /*
90961 ** Generate an error message when a SELECT is used within a subexpression
90962 ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
90963 ** column.  We do this in a subroutine because the error used to occur
90964 ** in multiple places.  (The error only occurs in one place now, but we
90965 ** retain the subroutine to minimize code disruption.)
90966 */
90967 static int checkForMultiColumnSelectError(
90968   Parse *pParse,       /* Parse context. */
90969   SelectDest *pDest,   /* Destination of SELECT results */
90970   int nExpr            /* Number of result columns returned by SELECT */
90971 ){
90972   int eDest = pDest->eDest;
90973   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
90974     sqlite3ErrorMsg(pParse, "only a single result allowed for "
90975        "a SELECT that is part of an expression");
90976     return 1;
90977   }else{
90978     return 0;
90979   }
90980 }
90981 #endif
90982
90983 /*
90984 ** This routine generates the code for the inside of the inner loop
90985 ** of a SELECT.
90986 **
90987 ** If srcTab and nColumn are both zero, then the pEList expressions
90988 ** are evaluated in order to get the data for this row.  If nColumn>0
90989 ** then data is pulled from srcTab and pEList is used only to get the
90990 ** datatypes for each column.
90991 */
90992 static void selectInnerLoop(
90993   Parse *pParse,          /* The parser context */
90994   Select *p,              /* The complete select statement being coded */
90995   ExprList *pEList,       /* List of values being extracted */
90996   int srcTab,             /* Pull data from this table */
90997   int nColumn,            /* Number of columns in the source table */
90998   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
90999   int distinct,           /* If >=0, make sure results are distinct */
91000   SelectDest *pDest,      /* How to dispose of the results */
91001   int iContinue,          /* Jump here to continue with next row */
91002   int iBreak              /* Jump here to break out of the inner loop */
91003 ){
91004   Vdbe *v = pParse->pVdbe;
91005   int i;
91006   int hasDistinct;        /* True if the DISTINCT keyword is present */
91007   int regResult;              /* Start of memory holding result set */
91008   int eDest = pDest->eDest;   /* How to dispose of results */
91009   int iParm = pDest->iParm;   /* First argument to disposal method */
91010   int nResultCol;             /* Number of result columns */
91011
91012   assert( v );
91013   if( NEVER(v==0) ) return;
91014   assert( pEList!=0 );
91015   hasDistinct = distinct>=0;
91016   if( pOrderBy==0 && !hasDistinct ){
91017     codeOffset(v, p, iContinue);
91018   }
91019
91020   /* Pull the requested columns.
91021   */
91022   if( nColumn>0 ){
91023     nResultCol = nColumn;
91024   }else{
91025     nResultCol = pEList->nExpr;
91026   }
91027   if( pDest->iMem==0 ){
91028     pDest->iMem = pParse->nMem+1;
91029     pDest->nMem = nResultCol;
91030     pParse->nMem += nResultCol;
91031   }else{ 
91032     assert( pDest->nMem==nResultCol );
91033   }
91034   regResult = pDest->iMem;
91035   if( nColumn>0 ){
91036     for(i=0; i<nColumn; i++){
91037       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
91038     }
91039   }else if( eDest!=SRT_Exists ){
91040     /* If the destination is an EXISTS(...) expression, the actual
91041     ** values returned by the SELECT are not required.
91042     */
91043     sqlite3ExprCacheClear(pParse);
91044     sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
91045   }
91046   nColumn = nResultCol;
91047
91048   /* If the DISTINCT keyword was present on the SELECT statement
91049   ** and this row has been seen before, then do not make this row
91050   ** part of the result.
91051   */
91052   if( hasDistinct ){
91053     assert( pEList!=0 );
91054     assert( pEList->nExpr==nColumn );
91055     codeDistinct(pParse, distinct, iContinue, nColumn, regResult);
91056     if( pOrderBy==0 ){
91057       codeOffset(v, p, iContinue);
91058     }
91059   }
91060
91061   switch( eDest ){
91062     /* In this mode, write each query result to the key of the temporary
91063     ** table iParm.
91064     */
91065 #ifndef SQLITE_OMIT_COMPOUND_SELECT
91066     case SRT_Union: {
91067       int r1;
91068       r1 = sqlite3GetTempReg(pParse);
91069       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
91070       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
91071       sqlite3ReleaseTempReg(pParse, r1);
91072       break;
91073     }
91074
91075     /* Construct a record from the query result, but instead of
91076     ** saving that record, use it as a key to delete elements from
91077     ** the temporary table iParm.
91078     */
91079     case SRT_Except: {
91080       sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
91081       break;
91082     }
91083 #endif
91084
91085     /* Store the result as data using a unique key.
91086     */
91087     case SRT_Table:
91088     case SRT_EphemTab: {
91089       int r1 = sqlite3GetTempReg(pParse);
91090       testcase( eDest==SRT_Table );
91091       testcase( eDest==SRT_EphemTab );
91092       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
91093       if( pOrderBy ){
91094         pushOntoSorter(pParse, pOrderBy, p, r1);
91095       }else{
91096         int r2 = sqlite3GetTempReg(pParse);
91097         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
91098         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
91099         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
91100         sqlite3ReleaseTempReg(pParse, r2);
91101       }
91102       sqlite3ReleaseTempReg(pParse, r1);
91103       break;
91104     }
91105
91106 #ifndef SQLITE_OMIT_SUBQUERY
91107     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
91108     ** then there should be a single item on the stack.  Write this
91109     ** item into the set table with bogus data.
91110     */
91111     case SRT_Set: {
91112       assert( nColumn==1 );
91113       p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity);
91114       if( pOrderBy ){
91115         /* At first glance you would think we could optimize out the
91116         ** ORDER BY in this case since the order of entries in the set
91117         ** does not matter.  But there might be a LIMIT clause, in which
91118         ** case the order does matter */
91119         pushOntoSorter(pParse, pOrderBy, p, regResult);
91120       }else{
91121         int r1 = sqlite3GetTempReg(pParse);
91122         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);
91123         sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
91124         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
91125         sqlite3ReleaseTempReg(pParse, r1);
91126       }
91127       break;
91128     }
91129
91130     /* If any row exist in the result set, record that fact and abort.
91131     */
91132     case SRT_Exists: {
91133       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
91134       /* The LIMIT clause will terminate the loop for us */
91135       break;
91136     }
91137
91138     /* If this is a scalar select that is part of an expression, then
91139     ** store the results in the appropriate memory cell and break out
91140     ** of the scan loop.
91141     */
91142     case SRT_Mem: {
91143       assert( nColumn==1 );
91144       if( pOrderBy ){
91145         pushOntoSorter(pParse, pOrderBy, p, regResult);
91146       }else{
91147         sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
91148         /* The LIMIT clause will jump out of the loop for us */
91149       }
91150       break;
91151     }
91152 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
91153
91154     /* Send the data to the callback function or to a subroutine.  In the
91155     ** case of a subroutine, the subroutine itself is responsible for
91156     ** popping the data from the stack.
91157     */
91158     case SRT_Coroutine:
91159     case SRT_Output: {
91160       testcase( eDest==SRT_Coroutine );
91161       testcase( eDest==SRT_Output );
91162       if( pOrderBy ){
91163         int r1 = sqlite3GetTempReg(pParse);
91164         sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
91165         pushOntoSorter(pParse, pOrderBy, p, r1);
91166         sqlite3ReleaseTempReg(pParse, r1);
91167       }else if( eDest==SRT_Coroutine ){
91168         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
91169       }else{
91170         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
91171         sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
91172       }
91173       break;
91174     }
91175
91176 #if !defined(SQLITE_OMIT_TRIGGER)
91177     /* Discard the results.  This is used for SELECT statements inside
91178     ** the body of a TRIGGER.  The purpose of such selects is to call
91179     ** user-defined functions that have side effects.  We do not care
91180     ** about the actual results of the select.
91181     */
91182     default: {
91183       assert( eDest==SRT_Discard );
91184       break;
91185     }
91186 #endif
91187   }
91188
91189   /* Jump to the end of the loop if the LIMIT is reached.  Except, if
91190   ** there is a sorter, in which case the sorter has already limited
91191   ** the output for us.
91192   */
91193   if( pOrderBy==0 && p->iLimit ){
91194     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
91195   }
91196 }
91197
91198 /*
91199 ** Given an expression list, generate a KeyInfo structure that records
91200 ** the collating sequence for each expression in that expression list.
91201 **
91202 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
91203 ** KeyInfo structure is appropriate for initializing a virtual index to
91204 ** implement that clause.  If the ExprList is the result set of a SELECT
91205 ** then the KeyInfo structure is appropriate for initializing a virtual
91206 ** index to implement a DISTINCT test.
91207 **
91208 ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
91209 ** function is responsible for seeing that this structure is eventually
91210 ** freed.  Add the KeyInfo structure to the P4 field of an opcode using
91211 ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
91212 */
91213 static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
91214   sqlite3 *db = pParse->db;
91215   int nExpr;
91216   KeyInfo *pInfo;
91217   struct ExprList_item *pItem;
91218   int i;
91219
91220   nExpr = pList->nExpr;
91221   pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
91222   if( pInfo ){
91223     pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
91224     pInfo->nField = (u16)nExpr;
91225     pInfo->enc = ENC(db);
91226     pInfo->db = db;
91227     for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
91228       CollSeq *pColl;
91229       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
91230       if( !pColl ){
91231         pColl = db->pDfltColl;
91232       }
91233       pInfo->aColl[i] = pColl;
91234       pInfo->aSortOrder[i] = pItem->sortOrder;
91235     }
91236   }
91237   return pInfo;
91238 }
91239
91240 #ifndef SQLITE_OMIT_COMPOUND_SELECT
91241 /*
91242 ** Name of the connection operator, used for error messages.
91243 */
91244 static const char *selectOpName(int id){
91245   char *z;
91246   switch( id ){
91247     case TK_ALL:       z = "UNION ALL";   break;
91248     case TK_INTERSECT: z = "INTERSECT";   break;
91249     case TK_EXCEPT:    z = "EXCEPT";      break;
91250     default:           z = "UNION";       break;
91251   }
91252   return z;
91253 }
91254 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
91255
91256 #ifndef SQLITE_OMIT_EXPLAIN
91257 /*
91258 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
91259 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
91260 ** where the caption is of the form:
91261 **
91262 **   "USE TEMP B-TREE FOR xxx"
91263 **
91264 ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
91265 ** is determined by the zUsage argument.
91266 */
91267 static void explainTempTable(Parse *pParse, const char *zUsage){
91268   if( pParse->explain==2 ){
91269     Vdbe *v = pParse->pVdbe;
91270     char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
91271     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
91272   }
91273 }
91274
91275 /*
91276 ** Assign expression b to lvalue a. A second, no-op, version of this macro
91277 ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
91278 ** in sqlite3Select() to assign values to structure member variables that
91279 ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
91280 ** code with #ifndef directives.
91281 */
91282 # define explainSetInteger(a, b) a = b
91283
91284 #else
91285 /* No-op versions of the explainXXX() functions and macros. */
91286 # define explainTempTable(y,z)
91287 # define explainSetInteger(y,z)
91288 #endif
91289
91290 #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
91291 /*
91292 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
91293 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
91294 ** where the caption is of one of the two forms:
91295 **
91296 **   "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
91297 **   "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
91298 **
91299 ** where iSub1 and iSub2 are the integers passed as the corresponding
91300 ** function parameters, and op is the text representation of the parameter
91301 ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
91302 ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is 
91303 ** false, or the second form if it is true.
91304 */
91305 static void explainComposite(
91306   Parse *pParse,                  /* Parse context */
91307   int op,                         /* One of TK_UNION, TK_EXCEPT etc. */
91308   int iSub1,                      /* Subquery id 1 */
91309   int iSub2,                      /* Subquery id 2 */
91310   int bUseTmp                     /* True if a temp table was used */
91311 ){
91312   assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
91313   if( pParse->explain==2 ){
91314     Vdbe *v = pParse->pVdbe;
91315     char *zMsg = sqlite3MPrintf(
91316         pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
91317         bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
91318     );
91319     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
91320   }
91321 }
91322 #else
91323 /* No-op versions of the explainXXX() functions and macros. */
91324 # define explainComposite(v,w,x,y,z)
91325 #endif
91326
91327 /*
91328 ** If the inner loop was generated using a non-null pOrderBy argument,
91329 ** then the results were placed in a sorter.  After the loop is terminated
91330 ** we need to run the sorter and output the results.  The following
91331 ** routine generates the code needed to do that.
91332 */
91333 static void generateSortTail(
91334   Parse *pParse,    /* Parsing context */
91335   Select *p,        /* The SELECT statement */
91336   Vdbe *v,          /* Generate code into this VDBE */
91337   int nColumn,      /* Number of columns of data */
91338   SelectDest *pDest /* Write the sorted results here */
91339 ){
91340   int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */
91341   int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
91342   int addr;
91343   int iTab;
91344   int pseudoTab = 0;
91345   ExprList *pOrderBy = p->pOrderBy;
91346
91347   int eDest = pDest->eDest;
91348   int iParm = pDest->iParm;
91349
91350   int regRow;
91351   int regRowid;
91352
91353   iTab = pOrderBy->iECursor;
91354   regRow = sqlite3GetTempReg(pParse);
91355   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
91356     pseudoTab = pParse->nTab++;
91357     sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
91358     regRowid = 0;
91359   }else{
91360     regRowid = sqlite3GetTempReg(pParse);
91361   }
91362   addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
91363   codeOffset(v, p, addrContinue);
91364   sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr + 1, regRow);
91365   switch( eDest ){
91366     case SRT_Table:
91367     case SRT_EphemTab: {
91368       testcase( eDest==SRT_Table );
91369       testcase( eDest==SRT_EphemTab );
91370       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
91371       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
91372       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
91373       break;
91374     }
91375 #ifndef SQLITE_OMIT_SUBQUERY
91376     case SRT_Set: {
91377       assert( nColumn==1 );
91378       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);
91379       sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
91380       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
91381       break;
91382     }
91383     case SRT_Mem: {
91384       assert( nColumn==1 );
91385       sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
91386       /* The LIMIT clause will terminate the loop for us */
91387       break;
91388     }
91389 #endif
91390     default: {
91391       int i;
91392       assert( eDest==SRT_Output || eDest==SRT_Coroutine ); 
91393       testcase( eDest==SRT_Output );
91394       testcase( eDest==SRT_Coroutine );
91395       for(i=0; i<nColumn; i++){
91396         assert( regRow!=pDest->iMem+i );
91397         sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i);
91398         if( i==0 ){
91399           sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
91400         }
91401       }
91402       if( eDest==SRT_Output ){
91403         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn);
91404         sqlite3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn);
91405       }else{
91406         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
91407       }
91408       break;
91409     }
91410   }
91411   sqlite3ReleaseTempReg(pParse, regRow);
91412   sqlite3ReleaseTempReg(pParse, regRowid);
91413
91414   /* The bottom of the loop
91415   */
91416   sqlite3VdbeResolveLabel(v, addrContinue);
91417   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
91418   sqlite3VdbeResolveLabel(v, addrBreak);
91419   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
91420     sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
91421   }
91422 }
91423
91424 /*
91425 ** Return a pointer to a string containing the 'declaration type' of the
91426 ** expression pExpr. The string may be treated as static by the caller.
91427 **
91428 ** The declaration type is the exact datatype definition extracted from the
91429 ** original CREATE TABLE statement if the expression is a column. The
91430 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
91431 ** is considered a column can be complex in the presence of subqueries. The
91432 ** result-set expression in all of the following SELECT statements is 
91433 ** considered a column by this function.
91434 **
91435 **   SELECT col FROM tbl;
91436 **   SELECT (SELECT col FROM tbl;
91437 **   SELECT (SELECT col FROM tbl);
91438 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
91439 ** 
91440 ** The declaration type for any expression other than a column is NULL.
91441 */
91442 static const char *columnType(
91443   NameContext *pNC, 
91444   Expr *pExpr,
91445   const char **pzOriginDb,
91446   const char **pzOriginTab,
91447   const char **pzOriginCol
91448 ){
91449   char const *zType = 0;
91450   char const *zOriginDb = 0;
91451   char const *zOriginTab = 0;
91452   char const *zOriginCol = 0;
91453   int j;
91454   if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
91455
91456   switch( pExpr->op ){
91457     case TK_AGG_COLUMN:
91458     case TK_COLUMN: {
91459       /* The expression is a column. Locate the table the column is being
91460       ** extracted from in NameContext.pSrcList. This table may be real
91461       ** database table or a subquery.
91462       */
91463       Table *pTab = 0;            /* Table structure column is extracted from */
91464       Select *pS = 0;             /* Select the column is extracted from */
91465       int iCol = pExpr->iColumn;  /* Index of column in pTab */
91466       testcase( pExpr->op==TK_AGG_COLUMN );
91467       testcase( pExpr->op==TK_COLUMN );
91468       while( pNC && !pTab ){
91469         SrcList *pTabList = pNC->pSrcList;
91470         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
91471         if( j<pTabList->nSrc ){
91472           pTab = pTabList->a[j].pTab;
91473           pS = pTabList->a[j].pSelect;
91474         }else{
91475           pNC = pNC->pNext;
91476         }
91477       }
91478
91479       if( pTab==0 ){
91480         /* At one time, code such as "SELECT new.x" within a trigger would
91481         ** cause this condition to run.  Since then, we have restructured how
91482         ** trigger code is generated and so this condition is no longer 
91483         ** possible. However, it can still be true for statements like
91484         ** the following:
91485         **
91486         **   CREATE TABLE t1(col INTEGER);
91487         **   SELECT (SELECT t1.col) FROM FROM t1;
91488         **
91489         ** when columnType() is called on the expression "t1.col" in the 
91490         ** sub-select. In this case, set the column type to NULL, even
91491         ** though it should really be "INTEGER".
91492         **
91493         ** This is not a problem, as the column type of "t1.col" is never
91494         ** used. When columnType() is called on the expression 
91495         ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
91496         ** branch below.  */
91497         break;
91498       }
91499
91500       assert( pTab && pExpr->pTab==pTab );
91501       if( pS ){
91502         /* The "table" is actually a sub-select or a view in the FROM clause
91503         ** of the SELECT statement. Return the declaration type and origin
91504         ** data for the result-set column of the sub-select.
91505         */
91506         if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
91507           /* If iCol is less than zero, then the expression requests the
91508           ** rowid of the sub-select or view. This expression is legal (see 
91509           ** test case misc2.2.2) - it always evaluates to NULL.
91510           */
91511           NameContext sNC;
91512           Expr *p = pS->pEList->a[iCol].pExpr;
91513           sNC.pSrcList = pS->pSrc;
91514           sNC.pNext = pNC;
91515           sNC.pParse = pNC->pParse;
91516           zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
91517         }
91518       }else if( ALWAYS(pTab->pSchema) ){
91519         /* A real table */
91520         assert( !pS );
91521         if( iCol<0 ) iCol = pTab->iPKey;
91522         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
91523         if( iCol<0 ){
91524           zType = "INTEGER";
91525           zOriginCol = "rowid";
91526         }else{
91527           zType = pTab->aCol[iCol].zType;
91528           zOriginCol = pTab->aCol[iCol].zName;
91529         }
91530         zOriginTab = pTab->zName;
91531         if( pNC->pParse ){
91532           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
91533           zOriginDb = pNC->pParse->db->aDb[iDb].zName;
91534         }
91535       }
91536       break;
91537     }
91538 #ifndef SQLITE_OMIT_SUBQUERY
91539     case TK_SELECT: {
91540       /* The expression is a sub-select. Return the declaration type and
91541       ** origin info for the single column in the result set of the SELECT
91542       ** statement.
91543       */
91544       NameContext sNC;
91545       Select *pS = pExpr->x.pSelect;
91546       Expr *p = pS->pEList->a[0].pExpr;
91547       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
91548       sNC.pSrcList = pS->pSrc;
91549       sNC.pNext = pNC;
91550       sNC.pParse = pNC->pParse;
91551       zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
91552       break;
91553     }
91554 #endif
91555   }
91556   
91557   if( pzOriginDb ){
91558     assert( pzOriginTab && pzOriginCol );
91559     *pzOriginDb = zOriginDb;
91560     *pzOriginTab = zOriginTab;
91561     *pzOriginCol = zOriginCol;
91562   }
91563   return zType;
91564 }
91565
91566 /*
91567 ** Generate code that will tell the VDBE the declaration types of columns
91568 ** in the result set.
91569 */
91570 static void generateColumnTypes(
91571   Parse *pParse,      /* Parser context */
91572   SrcList *pTabList,  /* List of tables */
91573   ExprList *pEList    /* Expressions defining the result set */
91574 ){
91575 #ifndef SQLITE_OMIT_DECLTYPE
91576   Vdbe *v = pParse->pVdbe;
91577   int i;
91578   NameContext sNC;
91579   sNC.pSrcList = pTabList;
91580   sNC.pParse = pParse;
91581   for(i=0; i<pEList->nExpr; i++){
91582     Expr *p = pEList->a[i].pExpr;
91583     const char *zType;
91584 #ifdef SQLITE_ENABLE_COLUMN_METADATA
91585     const char *zOrigDb = 0;
91586     const char *zOrigTab = 0;
91587     const char *zOrigCol = 0;
91588     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
91589
91590     /* The vdbe must make its own copy of the column-type and other 
91591     ** column specific strings, in case the schema is reset before this
91592     ** virtual machine is deleted.
91593     */
91594     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
91595     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
91596     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
91597 #else
91598     zType = columnType(&sNC, p, 0, 0, 0);
91599 #endif
91600     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
91601   }
91602 #endif /* SQLITE_OMIT_DECLTYPE */
91603 }
91604
91605 /*
91606 ** Generate code that will tell the VDBE the names of columns
91607 ** in the result set.  This information is used to provide the
91608 ** azCol[] values in the callback.
91609 */
91610 static void generateColumnNames(
91611   Parse *pParse,      /* Parser context */
91612   SrcList *pTabList,  /* List of tables */
91613   ExprList *pEList    /* Expressions defining the result set */
91614 ){
91615   Vdbe *v = pParse->pVdbe;
91616   int i, j;
91617   sqlite3 *db = pParse->db;
91618   int fullNames, shortNames;
91619
91620 #ifndef SQLITE_OMIT_EXPLAIN
91621   /* If this is an EXPLAIN, skip this step */
91622   if( pParse->explain ){
91623     return;
91624   }
91625 #endif
91626
91627   if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
91628   pParse->colNamesSet = 1;
91629   fullNames = (db->flags & SQLITE_FullColNames)!=0;
91630   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
91631   sqlite3VdbeSetNumCols(v, pEList->nExpr);
91632   for(i=0; i<pEList->nExpr; i++){
91633     Expr *p;
91634     p = pEList->a[i].pExpr;
91635     if( NEVER(p==0) ) continue;
91636     if( pEList->a[i].zName ){
91637       char *zName = pEList->a[i].zName;
91638       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
91639     }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
91640       Table *pTab;
91641       char *zCol;
91642       int iCol = p->iColumn;
91643       for(j=0; ALWAYS(j<pTabList->nSrc); j++){
91644         if( pTabList->a[j].iCursor==p->iTable ) break;
91645       }
91646       assert( j<pTabList->nSrc );
91647       pTab = pTabList->a[j].pTab;
91648       if( iCol<0 ) iCol = pTab->iPKey;
91649       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
91650       if( iCol<0 ){
91651         zCol = "rowid";
91652       }else{
91653         zCol = pTab->aCol[iCol].zName;
91654       }
91655       if( !shortNames && !fullNames ){
91656         sqlite3VdbeSetColName(v, i, COLNAME_NAME, 
91657             sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
91658       }else if( fullNames ){
91659         char *zName = 0;
91660         zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
91661         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
91662       }else{
91663         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
91664       }
91665     }else{
91666       sqlite3VdbeSetColName(v, i, COLNAME_NAME, 
91667           sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
91668     }
91669   }
91670   generateColumnTypes(pParse, pTabList, pEList);
91671 }
91672
91673 /*
91674 ** Given a an expression list (which is really the list of expressions
91675 ** that form the result set of a SELECT statement) compute appropriate
91676 ** column names for a table that would hold the expression list.
91677 **
91678 ** All column names will be unique.
91679 **
91680 ** Only the column names are computed.  Column.zType, Column.zColl,
91681 ** and other fields of Column are zeroed.
91682 **
91683 ** Return SQLITE_OK on success.  If a memory allocation error occurs,
91684 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
91685 */
91686 static int selectColumnsFromExprList(
91687   Parse *pParse,          /* Parsing context */
91688   ExprList *pEList,       /* Expr list from which to derive column names */
91689   int *pnCol,             /* Write the number of columns here */
91690   Column **paCol          /* Write the new column list here */
91691 ){
91692   sqlite3 *db = pParse->db;   /* Database connection */
91693   int i, j;                   /* Loop counters */
91694   int cnt;                    /* Index added to make the name unique */
91695   Column *aCol, *pCol;        /* For looping over result columns */
91696   int nCol;                   /* Number of columns in the result set */
91697   Expr *p;                    /* Expression for a single result column */
91698   char *zName;                /* Column name */
91699   int nName;                  /* Size of name in zName[] */
91700
91701   *pnCol = nCol = pEList->nExpr;
91702   aCol = *paCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
91703   if( aCol==0 ) return SQLITE_NOMEM;
91704   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
91705     /* Get an appropriate name for the column
91706     */
91707     p = pEList->a[i].pExpr;
91708     assert( p->pRight==0 || ExprHasProperty(p->pRight, EP_IntValue)
91709                || p->pRight->u.zToken==0 || p->pRight->u.zToken[0]!=0 );
91710     if( (zName = pEList->a[i].zName)!=0 ){
91711       /* If the column contains an "AS <name>" phrase, use <name> as the name */
91712       zName = sqlite3DbStrDup(db, zName);
91713     }else{
91714       Expr *pColExpr = p;  /* The expression that is the result column name */
91715       Table *pTab;         /* Table associated with this expression */
91716       while( pColExpr->op==TK_DOT ) pColExpr = pColExpr->pRight;
91717       if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
91718         /* For columns use the column name name */
91719         int iCol = pColExpr->iColumn;
91720         pTab = pColExpr->pTab;
91721         if( iCol<0 ) iCol = pTab->iPKey;
91722         zName = sqlite3MPrintf(db, "%s",
91723                  iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
91724       }else if( pColExpr->op==TK_ID ){
91725         assert( !ExprHasProperty(pColExpr, EP_IntValue) );
91726         zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
91727       }else{
91728         /* Use the original text of the column expression as its name */
91729         zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
91730       }
91731     }
91732     if( db->mallocFailed ){
91733       sqlite3DbFree(db, zName);
91734       break;
91735     }
91736
91737     /* Make sure the column name is unique.  If the name is not unique,
91738     ** append a integer to the name so that it becomes unique.
91739     */
91740     nName = sqlite3Strlen30(zName);
91741     for(j=cnt=0; j<i; j++){
91742       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
91743         char *zNewName;
91744         zName[nName] = 0;
91745         zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
91746         sqlite3DbFree(db, zName);
91747         zName = zNewName;
91748         j = -1;
91749         if( zName==0 ) break;
91750       }
91751     }
91752     pCol->zName = zName;
91753   }
91754   if( db->mallocFailed ){
91755     for(j=0; j<i; j++){
91756       sqlite3DbFree(db, aCol[j].zName);
91757     }
91758     sqlite3DbFree(db, aCol);
91759     *paCol = 0;
91760     *pnCol = 0;
91761     return SQLITE_NOMEM;
91762   }
91763   return SQLITE_OK;
91764 }
91765
91766 /*
91767 ** Add type and collation information to a column list based on
91768 ** a SELECT statement.
91769 ** 
91770 ** The column list presumably came from selectColumnNamesFromExprList().
91771 ** The column list has only names, not types or collations.  This
91772 ** routine goes through and adds the types and collations.
91773 **
91774 ** This routine requires that all identifiers in the SELECT
91775 ** statement be resolved.
91776 */
91777 static void selectAddColumnTypeAndCollation(
91778   Parse *pParse,        /* Parsing contexts */
91779   int nCol,             /* Number of columns */
91780   Column *aCol,         /* List of columns */
91781   Select *pSelect       /* SELECT used to determine types and collations */
91782 ){
91783   sqlite3 *db = pParse->db;
91784   NameContext sNC;
91785   Column *pCol;
91786   CollSeq *pColl;
91787   int i;
91788   Expr *p;
91789   struct ExprList_item *a;
91790
91791   assert( pSelect!=0 );
91792   assert( (pSelect->selFlags & SF_Resolved)!=0 );
91793   assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
91794   if( db->mallocFailed ) return;
91795   memset(&sNC, 0, sizeof(sNC));
91796   sNC.pSrcList = pSelect->pSrc;
91797   a = pSelect->pEList->a;
91798   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
91799     p = a[i].pExpr;
91800     pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
91801     pCol->affinity = sqlite3ExprAffinity(p);
91802     if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
91803     pColl = sqlite3ExprCollSeq(pParse, p);
91804     if( pColl ){
91805       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
91806     }
91807   }
91808 }
91809
91810 /*
91811 ** Given a SELECT statement, generate a Table structure that describes
91812 ** the result set of that SELECT.
91813 */
91814 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
91815   Table *pTab;
91816   sqlite3 *db = pParse->db;
91817   int savedFlags;
91818
91819   savedFlags = db->flags;
91820   db->flags &= ~SQLITE_FullColNames;
91821   db->flags |= SQLITE_ShortColNames;
91822   sqlite3SelectPrep(pParse, pSelect, 0);
91823   if( pParse->nErr ) return 0;
91824   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
91825   db->flags = savedFlags;
91826   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
91827   if( pTab==0 ){
91828     return 0;
91829   }
91830   /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
91831   ** is disabled */
91832   assert( db->lookaside.bEnabled==0 );
91833   pTab->nRef = 1;
91834   pTab->zName = 0;
91835   pTab->nRowEst = 1000000;
91836   selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
91837   selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
91838   pTab->iPKey = -1;
91839   if( db->mallocFailed ){
91840     sqlite3DeleteTable(db, pTab);
91841     return 0;
91842   }
91843   return pTab;
91844 }
91845
91846 /*
91847 ** Get a VDBE for the given parser context.  Create a new one if necessary.
91848 ** If an error occurs, return NULL and leave a message in pParse.
91849 */
91850 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
91851   Vdbe *v = pParse->pVdbe;
91852   if( v==0 ){
91853     v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
91854 #ifndef SQLITE_OMIT_TRACE
91855     if( v ){
91856       sqlite3VdbeAddOp0(v, OP_Trace);
91857     }
91858 #endif
91859   }
91860   return v;
91861 }
91862
91863
91864 /*
91865 ** Compute the iLimit and iOffset fields of the SELECT based on the
91866 ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
91867 ** that appear in the original SQL statement after the LIMIT and OFFSET
91868 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset 
91869 ** are the integer memory register numbers for counters used to compute 
91870 ** the limit and offset.  If there is no limit and/or offset, then 
91871 ** iLimit and iOffset are negative.
91872 **
91873 ** This routine changes the values of iLimit and iOffset only if
91874 ** a limit or offset is defined by pLimit and pOffset.  iLimit and
91875 ** iOffset should have been preset to appropriate default values
91876 ** (usually but not always -1) prior to calling this routine.
91877 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
91878 ** redefined.  The UNION ALL operator uses this property to force
91879 ** the reuse of the same limit and offset registers across multiple
91880 ** SELECT statements.
91881 */
91882 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
91883   Vdbe *v = 0;
91884   int iLimit = 0;
91885   int iOffset;
91886   int addr1, n;
91887   if( p->iLimit ) return;
91888
91889   /* 
91890   ** "LIMIT -1" always shows all rows.  There is some
91891   ** contraversy about what the correct behavior should be.
91892   ** The current implementation interprets "LIMIT 0" to mean
91893   ** no rows.
91894   */
91895   sqlite3ExprCacheClear(pParse);
91896   assert( p->pOffset==0 || p->pLimit!=0 );
91897   if( p->pLimit ){
91898     p->iLimit = iLimit = ++pParse->nMem;
91899     v = sqlite3GetVdbe(pParse);
91900     if( NEVER(v==0) ) return;  /* VDBE should have already been allocated */
91901     if( sqlite3ExprIsInteger(p->pLimit, &n) ){
91902       sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
91903       VdbeComment((v, "LIMIT counter"));
91904       if( n==0 ){
91905         sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
91906       }else{
91907         if( p->nSelectRow > (double)n ) p->nSelectRow = (double)n;
91908       }
91909     }else{
91910       sqlite3ExprCode(pParse, p->pLimit, iLimit);
91911       sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
91912       VdbeComment((v, "LIMIT counter"));
91913       sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
91914     }
91915     if( p->pOffset ){
91916       p->iOffset = iOffset = ++pParse->nMem;
91917       pParse->nMem++;   /* Allocate an extra register for limit+offset */
91918       sqlite3ExprCode(pParse, p->pOffset, iOffset);
91919       sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
91920       VdbeComment((v, "OFFSET counter"));
91921       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
91922       sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
91923       sqlite3VdbeJumpHere(v, addr1);
91924       sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
91925       VdbeComment((v, "LIMIT+OFFSET"));
91926       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
91927       sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
91928       sqlite3VdbeJumpHere(v, addr1);
91929     }
91930   }
91931 }
91932
91933 #ifndef SQLITE_OMIT_COMPOUND_SELECT
91934 /*
91935 ** Return the appropriate collating sequence for the iCol-th column of
91936 ** the result set for the compound-select statement "p".  Return NULL if
91937 ** the column has no default collating sequence.
91938 **
91939 ** The collating sequence for the compound select is taken from the
91940 ** left-most term of the select that has a collating sequence.
91941 */
91942 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
91943   CollSeq *pRet;
91944   if( p->pPrior ){
91945     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
91946   }else{
91947     pRet = 0;
91948   }
91949   assert( iCol>=0 );
91950   if( pRet==0 && iCol<p->pEList->nExpr ){
91951     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
91952   }
91953   return pRet;
91954 }
91955 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
91956
91957 /* Forward reference */
91958 static int multiSelectOrderBy(
91959   Parse *pParse,        /* Parsing context */
91960   Select *p,            /* The right-most of SELECTs to be coded */
91961   SelectDest *pDest     /* What to do with query results */
91962 );
91963
91964
91965 #ifndef SQLITE_OMIT_COMPOUND_SELECT
91966 /*
91967 ** This routine is called to process a compound query form from
91968 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
91969 ** INTERSECT
91970 **
91971 ** "p" points to the right-most of the two queries.  the query on the
91972 ** left is p->pPrior.  The left query could also be a compound query
91973 ** in which case this routine will be called recursively. 
91974 **
91975 ** The results of the total query are to be written into a destination
91976 ** of type eDest with parameter iParm.
91977 **
91978 ** Example 1:  Consider a three-way compound SQL statement.
91979 **
91980 **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
91981 **
91982 ** This statement is parsed up as follows:
91983 **
91984 **     SELECT c FROM t3
91985 **      |
91986 **      `----->  SELECT b FROM t2
91987 **                |
91988 **                `------>  SELECT a FROM t1
91989 **
91990 ** The arrows in the diagram above represent the Select.pPrior pointer.
91991 ** So if this routine is called with p equal to the t3 query, then
91992 ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
91993 **
91994 ** Notice that because of the way SQLite parses compound SELECTs, the
91995 ** individual selects always group from left to right.
91996 */
91997 static int multiSelect(
91998   Parse *pParse,        /* Parsing context */
91999   Select *p,            /* The right-most of SELECTs to be coded */
92000   SelectDest *pDest     /* What to do with query results */
92001 ){
92002   int rc = SQLITE_OK;   /* Success code from a subroutine */
92003   Select *pPrior;       /* Another SELECT immediately to our left */
92004   Vdbe *v;              /* Generate code to this VDBE */
92005   SelectDest dest;      /* Alternative data destination */
92006   Select *pDelete = 0;  /* Chain of simple selects to delete */
92007   sqlite3 *db;          /* Database connection */
92008 #ifndef SQLITE_OMIT_EXPLAIN
92009   int iSub1;            /* EQP id of left-hand query */
92010   int iSub2;            /* EQP id of right-hand query */
92011 #endif
92012
92013   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
92014   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
92015   */
92016   assert( p && p->pPrior );  /* Calling function guarantees this much */
92017   db = pParse->db;
92018   pPrior = p->pPrior;
92019   assert( pPrior->pRightmost!=pPrior );
92020   assert( pPrior->pRightmost==p->pRightmost );
92021   dest = *pDest;
92022   if( pPrior->pOrderBy ){
92023     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
92024       selectOpName(p->op));
92025     rc = 1;
92026     goto multi_select_end;
92027   }
92028   if( pPrior->pLimit ){
92029     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
92030       selectOpName(p->op));
92031     rc = 1;
92032     goto multi_select_end;
92033   }
92034
92035   v = sqlite3GetVdbe(pParse);
92036   assert( v!=0 );  /* The VDBE already created by calling function */
92037
92038   /* Create the destination temporary table if necessary
92039   */
92040   if( dest.eDest==SRT_EphemTab ){
92041     assert( p->pEList );
92042     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr);
92043     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
92044     dest.eDest = SRT_Table;
92045   }
92046
92047   /* Make sure all SELECTs in the statement have the same number of elements
92048   ** in their result sets.
92049   */
92050   assert( p->pEList && pPrior->pEList );
92051   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
92052     sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
92053       " do not have the same number of result columns", selectOpName(p->op));
92054     rc = 1;
92055     goto multi_select_end;
92056   }
92057
92058   /* Compound SELECTs that have an ORDER BY clause are handled separately.
92059   */
92060   if( p->pOrderBy ){
92061     return multiSelectOrderBy(pParse, p, pDest);
92062   }
92063
92064   /* Generate code for the left and right SELECT statements.
92065   */
92066   switch( p->op ){
92067     case TK_ALL: {
92068       int addr = 0;
92069       int nLimit;
92070       assert( !pPrior->pLimit );
92071       pPrior->pLimit = p->pLimit;
92072       pPrior->pOffset = p->pOffset;
92073       explainSetInteger(iSub1, pParse->iNextSelectId);
92074       rc = sqlite3Select(pParse, pPrior, &dest);
92075       p->pLimit = 0;
92076       p->pOffset = 0;
92077       if( rc ){
92078         goto multi_select_end;
92079       }
92080       p->pPrior = 0;
92081       p->iLimit = pPrior->iLimit;
92082       p->iOffset = pPrior->iOffset;
92083       if( p->iLimit ){
92084         addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
92085         VdbeComment((v, "Jump ahead if LIMIT reached"));
92086       }
92087       explainSetInteger(iSub2, pParse->iNextSelectId);
92088       rc = sqlite3Select(pParse, p, &dest);
92089       testcase( rc!=SQLITE_OK );
92090       pDelete = p->pPrior;
92091       p->pPrior = pPrior;
92092       p->nSelectRow += pPrior->nSelectRow;
92093       if( pPrior->pLimit
92094        && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
92095        && p->nSelectRow > (double)nLimit 
92096       ){
92097         p->nSelectRow = (double)nLimit;
92098       }
92099       if( addr ){
92100         sqlite3VdbeJumpHere(v, addr);
92101       }
92102       break;
92103     }
92104     case TK_EXCEPT:
92105     case TK_UNION: {
92106       int unionTab;    /* Cursor number of the temporary table holding result */
92107       u8 op = 0;       /* One of the SRT_ operations to apply to self */
92108       int priorOp;     /* The SRT_ operation to apply to prior selects */
92109       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
92110       int addr;
92111       SelectDest uniondest;
92112
92113       testcase( p->op==TK_EXCEPT );
92114       testcase( p->op==TK_UNION );
92115       priorOp = SRT_Union;
92116       if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
92117         /* We can reuse a temporary table generated by a SELECT to our
92118         ** right.
92119         */
92120         assert( p->pRightmost!=p );  /* Can only happen for leftward elements
92121                                      ** of a 3-way or more compound */
92122         assert( p->pLimit==0 );      /* Not allowed on leftward elements */
92123         assert( p->pOffset==0 );     /* Not allowed on leftward elements */
92124         unionTab = dest.iParm;
92125       }else{
92126         /* We will need to create our own temporary table to hold the
92127         ** intermediate results.
92128         */
92129         unionTab = pParse->nTab++;
92130         assert( p->pOrderBy==0 );
92131         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
92132         assert( p->addrOpenEphm[0] == -1 );
92133         p->addrOpenEphm[0] = addr;
92134         p->pRightmost->selFlags |= SF_UsesEphemeral;
92135         assert( p->pEList );
92136       }
92137
92138       /* Code the SELECT statements to our left
92139       */
92140       assert( !pPrior->pOrderBy );
92141       sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
92142       explainSetInteger(iSub1, pParse->iNextSelectId);
92143       rc = sqlite3Select(pParse, pPrior, &uniondest);
92144       if( rc ){
92145         goto multi_select_end;
92146       }
92147
92148       /* Code the current SELECT statement
92149       */
92150       if( p->op==TK_EXCEPT ){
92151         op = SRT_Except;
92152       }else{
92153         assert( p->op==TK_UNION );
92154         op = SRT_Union;
92155       }
92156       p->pPrior = 0;
92157       pLimit = p->pLimit;
92158       p->pLimit = 0;
92159       pOffset = p->pOffset;
92160       p->pOffset = 0;
92161       uniondest.eDest = op;
92162       explainSetInteger(iSub2, pParse->iNextSelectId);
92163       rc = sqlite3Select(pParse, p, &uniondest);
92164       testcase( rc!=SQLITE_OK );
92165       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
92166       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
92167       sqlite3ExprListDelete(db, p->pOrderBy);
92168       pDelete = p->pPrior;
92169       p->pPrior = pPrior;
92170       p->pOrderBy = 0;
92171       if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
92172       sqlite3ExprDelete(db, p->pLimit);
92173       p->pLimit = pLimit;
92174       p->pOffset = pOffset;
92175       p->iLimit = 0;
92176       p->iOffset = 0;
92177
92178       /* Convert the data in the temporary table into whatever form
92179       ** it is that we currently need.
92180       */
92181       assert( unionTab==dest.iParm || dest.eDest!=priorOp );
92182       if( dest.eDest!=priorOp ){
92183         int iCont, iBreak, iStart;
92184         assert( p->pEList );
92185         if( dest.eDest==SRT_Output ){
92186           Select *pFirst = p;
92187           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
92188           generateColumnNames(pParse, 0, pFirst->pEList);
92189         }
92190         iBreak = sqlite3VdbeMakeLabel(v);
92191         iCont = sqlite3VdbeMakeLabel(v);
92192         computeLimitRegisters(pParse, p, iBreak);
92193         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
92194         iStart = sqlite3VdbeCurrentAddr(v);
92195         selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
92196                         0, -1, &dest, iCont, iBreak);
92197         sqlite3VdbeResolveLabel(v, iCont);
92198         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
92199         sqlite3VdbeResolveLabel(v, iBreak);
92200         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
92201       }
92202       break;
92203     }
92204     default: assert( p->op==TK_INTERSECT ); {
92205       int tab1, tab2;
92206       int iCont, iBreak, iStart;
92207       Expr *pLimit, *pOffset;
92208       int addr;
92209       SelectDest intersectdest;
92210       int r1;
92211
92212       /* INTERSECT is different from the others since it requires
92213       ** two temporary tables.  Hence it has its own case.  Begin
92214       ** by allocating the tables we will need.
92215       */
92216       tab1 = pParse->nTab++;
92217       tab2 = pParse->nTab++;
92218       assert( p->pOrderBy==0 );
92219
92220       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
92221       assert( p->addrOpenEphm[0] == -1 );
92222       p->addrOpenEphm[0] = addr;
92223       p->pRightmost->selFlags |= SF_UsesEphemeral;
92224       assert( p->pEList );
92225
92226       /* Code the SELECTs to our left into temporary table "tab1".
92227       */
92228       sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
92229       explainSetInteger(iSub1, pParse->iNextSelectId);
92230       rc = sqlite3Select(pParse, pPrior, &intersectdest);
92231       if( rc ){
92232         goto multi_select_end;
92233       }
92234
92235       /* Code the current SELECT into temporary table "tab2"
92236       */
92237       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
92238       assert( p->addrOpenEphm[1] == -1 );
92239       p->addrOpenEphm[1] = addr;
92240       p->pPrior = 0;
92241       pLimit = p->pLimit;
92242       p->pLimit = 0;
92243       pOffset = p->pOffset;
92244       p->pOffset = 0;
92245       intersectdest.iParm = tab2;
92246       explainSetInteger(iSub2, pParse->iNextSelectId);
92247       rc = sqlite3Select(pParse, p, &intersectdest);
92248       testcase( rc!=SQLITE_OK );
92249       pDelete = p->pPrior;
92250       p->pPrior = pPrior;
92251       if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
92252       sqlite3ExprDelete(db, p->pLimit);
92253       p->pLimit = pLimit;
92254       p->pOffset = pOffset;
92255
92256       /* Generate code to take the intersection of the two temporary
92257       ** tables.
92258       */
92259       assert( p->pEList );
92260       if( dest.eDest==SRT_Output ){
92261         Select *pFirst = p;
92262         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
92263         generateColumnNames(pParse, 0, pFirst->pEList);
92264       }
92265       iBreak = sqlite3VdbeMakeLabel(v);
92266       iCont = sqlite3VdbeMakeLabel(v);
92267       computeLimitRegisters(pParse, p, iBreak);
92268       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
92269       r1 = sqlite3GetTempReg(pParse);
92270       iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
92271       sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
92272       sqlite3ReleaseTempReg(pParse, r1);
92273       selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
92274                       0, -1, &dest, iCont, iBreak);
92275       sqlite3VdbeResolveLabel(v, iCont);
92276       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
92277       sqlite3VdbeResolveLabel(v, iBreak);
92278       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
92279       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
92280       break;
92281     }
92282   }
92283
92284   explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
92285
92286   /* Compute collating sequences used by 
92287   ** temporary tables needed to implement the compound select.
92288   ** Attach the KeyInfo structure to all temporary tables.
92289   **
92290   ** This section is run by the right-most SELECT statement only.
92291   ** SELECT statements to the left always skip this part.  The right-most
92292   ** SELECT might also skip this part if it has no ORDER BY clause and
92293   ** no temp tables are required.
92294   */
92295   if( p->selFlags & SF_UsesEphemeral ){
92296     int i;                        /* Loop counter */
92297     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
92298     Select *pLoop;                /* For looping through SELECT statements */
92299     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
92300     int nCol;                     /* Number of columns in result set */
92301
92302     assert( p->pRightmost==p );
92303     nCol = p->pEList->nExpr;
92304     pKeyInfo = sqlite3DbMallocZero(db,
92305                        sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
92306     if( !pKeyInfo ){
92307       rc = SQLITE_NOMEM;
92308       goto multi_select_end;
92309     }
92310
92311     pKeyInfo->enc = ENC(db);
92312     pKeyInfo->nField = (u16)nCol;
92313
92314     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
92315       *apColl = multiSelectCollSeq(pParse, p, i);
92316       if( 0==*apColl ){
92317         *apColl = db->pDfltColl;
92318       }
92319     }
92320
92321     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
92322       for(i=0; i<2; i++){
92323         int addr = pLoop->addrOpenEphm[i];
92324         if( addr<0 ){
92325           /* If [0] is unused then [1] is also unused.  So we can
92326           ** always safely abort as soon as the first unused slot is found */
92327           assert( pLoop->addrOpenEphm[1]<0 );
92328           break;
92329         }
92330         sqlite3VdbeChangeP2(v, addr, nCol);
92331         sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
92332         pLoop->addrOpenEphm[i] = -1;
92333       }
92334     }
92335     sqlite3DbFree(db, pKeyInfo);
92336   }
92337
92338 multi_select_end:
92339   pDest->iMem = dest.iMem;
92340   pDest->nMem = dest.nMem;
92341   sqlite3SelectDelete(db, pDelete);
92342   return rc;
92343 }
92344 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
92345
92346 /*
92347 ** Code an output subroutine for a coroutine implementation of a
92348 ** SELECT statment.
92349 **
92350 ** The data to be output is contained in pIn->iMem.  There are
92351 ** pIn->nMem columns to be output.  pDest is where the output should
92352 ** be sent.
92353 **
92354 ** regReturn is the number of the register holding the subroutine
92355 ** return address.
92356 **
92357 ** If regPrev>0 then it is the first register in a vector that
92358 ** records the previous output.  mem[regPrev] is a flag that is false
92359 ** if there has been no previous output.  If regPrev>0 then code is
92360 ** generated to suppress duplicates.  pKeyInfo is used for comparing
92361 ** keys.
92362 **
92363 ** If the LIMIT found in p->iLimit is reached, jump immediately to
92364 ** iBreak.
92365 */
92366 static int generateOutputSubroutine(
92367   Parse *pParse,          /* Parsing context */
92368   Select *p,              /* The SELECT statement */
92369   SelectDest *pIn,        /* Coroutine supplying data */
92370   SelectDest *pDest,      /* Where to send the data */
92371   int regReturn,          /* The return address register */
92372   int regPrev,            /* Previous result register.  No uniqueness if 0 */
92373   KeyInfo *pKeyInfo,      /* For comparing with previous entry */
92374   int p4type,             /* The p4 type for pKeyInfo */
92375   int iBreak              /* Jump here if we hit the LIMIT */
92376 ){
92377   Vdbe *v = pParse->pVdbe;
92378   int iContinue;
92379   int addr;
92380
92381   addr = sqlite3VdbeCurrentAddr(v);
92382   iContinue = sqlite3VdbeMakeLabel(v);
92383
92384   /* Suppress duplicates for UNION, EXCEPT, and INTERSECT 
92385   */
92386   if( regPrev ){
92387     int j1, j2;
92388     j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
92389     j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iMem, regPrev+1, pIn->nMem,
92390                               (char*)pKeyInfo, p4type);
92391     sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
92392     sqlite3VdbeJumpHere(v, j1);
92393     sqlite3ExprCodeCopy(pParse, pIn->iMem, regPrev+1, pIn->nMem);
92394     sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
92395   }
92396   if( pParse->db->mallocFailed ) return 0;
92397
92398   /* Suppress the the first OFFSET entries if there is an OFFSET clause
92399   */
92400   codeOffset(v, p, iContinue);
92401
92402   switch( pDest->eDest ){
92403     /* Store the result as data using a unique key.
92404     */
92405     case SRT_Table:
92406     case SRT_EphemTab: {
92407       int r1 = sqlite3GetTempReg(pParse);
92408       int r2 = sqlite3GetTempReg(pParse);
92409       testcase( pDest->eDest==SRT_Table );
92410       testcase( pDest->eDest==SRT_EphemTab );
92411       sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iMem, pIn->nMem, r1);
92412       sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iParm, r2);
92413       sqlite3VdbeAddOp3(v, OP_Insert, pDest->iParm, r1, r2);
92414       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
92415       sqlite3ReleaseTempReg(pParse, r2);
92416       sqlite3ReleaseTempReg(pParse, r1);
92417       break;
92418     }
92419
92420 #ifndef SQLITE_OMIT_SUBQUERY
92421     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
92422     ** then there should be a single item on the stack.  Write this
92423     ** item into the set table with bogus data.
92424     */
92425     case SRT_Set: {
92426       int r1;
92427       assert( pIn->nMem==1 );
92428       p->affinity = 
92429          sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affinity);
92430       r1 = sqlite3GetTempReg(pParse);
92431       sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iMem, 1, r1, &p->affinity, 1);
92432       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, 1);
92433       sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iParm, r1);
92434       sqlite3ReleaseTempReg(pParse, r1);
92435       break;
92436     }
92437
92438 #if 0  /* Never occurs on an ORDER BY query */
92439     /* If any row exist in the result set, record that fact and abort.
92440     */
92441     case SRT_Exists: {
92442       sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iParm);
92443       /* The LIMIT clause will terminate the loop for us */
92444       break;
92445     }
92446 #endif
92447
92448     /* If this is a scalar select that is part of an expression, then
92449     ** store the results in the appropriate memory cell and break out
92450     ** of the scan loop.
92451     */
92452     case SRT_Mem: {
92453       assert( pIn->nMem==1 );
92454       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iParm, 1);
92455       /* The LIMIT clause will jump out of the loop for us */
92456       break;
92457     }
92458 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
92459
92460     /* The results are stored in a sequence of registers
92461     ** starting at pDest->iMem.  Then the co-routine yields.
92462     */
92463     case SRT_Coroutine: {
92464       if( pDest->iMem==0 ){
92465         pDest->iMem = sqlite3GetTempRange(pParse, pIn->nMem);
92466         pDest->nMem = pIn->nMem;
92467       }
92468       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iMem, pDest->nMem);
92469       sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
92470       break;
92471     }
92472
92473     /* If none of the above, then the result destination must be
92474     ** SRT_Output.  This routine is never called with any other
92475     ** destination other than the ones handled above or SRT_Output.
92476     **
92477     ** For SRT_Output, results are stored in a sequence of registers.  
92478     ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
92479     ** return the next row of result.
92480     */
92481     default: {
92482       assert( pDest->eDest==SRT_Output );
92483       sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iMem, pIn->nMem);
92484       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, pIn->nMem);
92485       break;
92486     }
92487   }
92488
92489   /* Jump to the end of the loop if the LIMIT is reached.
92490   */
92491   if( p->iLimit ){
92492     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
92493   }
92494
92495   /* Generate the subroutine return
92496   */
92497   sqlite3VdbeResolveLabel(v, iContinue);
92498   sqlite3VdbeAddOp1(v, OP_Return, regReturn);
92499
92500   return addr;
92501 }
92502
92503 /*
92504 ** Alternative compound select code generator for cases when there
92505 ** is an ORDER BY clause.
92506 **
92507 ** We assume a query of the following form:
92508 **
92509 **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
92510 **
92511 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
92512 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
92513 ** co-routines.  Then run the co-routines in parallel and merge the results
92514 ** into the output.  In addition to the two coroutines (called selectA and
92515 ** selectB) there are 7 subroutines:
92516 **
92517 **    outA:    Move the output of the selectA coroutine into the output
92518 **             of the compound query.
92519 **
92520 **    outB:    Move the output of the selectB coroutine into the output
92521 **             of the compound query.  (Only generated for UNION and
92522 **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
92523 **             appears only in B.)
92524 **
92525 **    AltB:    Called when there is data from both coroutines and A<B.
92526 **
92527 **    AeqB:    Called when there is data from both coroutines and A==B.
92528 **
92529 **    AgtB:    Called when there is data from both coroutines and A>B.
92530 **
92531 **    EofA:    Called when data is exhausted from selectA.
92532 **
92533 **    EofB:    Called when data is exhausted from selectB.
92534 **
92535 ** The implementation of the latter five subroutines depend on which 
92536 ** <operator> is used:
92537 **
92538 **
92539 **             UNION ALL         UNION            EXCEPT          INTERSECT
92540 **          -------------  -----------------  --------------  -----------------
92541 **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
92542 **
92543 **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
92544 **
92545 **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
92546 **
92547 **   EofA:   outB, nextB      outB, nextB          halt             halt
92548 **
92549 **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
92550 **
92551 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
92552 ** causes an immediate jump to EofA and an EOF on B following nextB causes
92553 ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
92554 ** following nextX causes a jump to the end of the select processing.
92555 **
92556 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
92557 ** within the output subroutine.  The regPrev register set holds the previously
92558 ** output value.  A comparison is made against this value and the output
92559 ** is skipped if the next results would be the same as the previous.
92560 **
92561 ** The implementation plan is to implement the two coroutines and seven
92562 ** subroutines first, then put the control logic at the bottom.  Like this:
92563 **
92564 **          goto Init
92565 **     coA: coroutine for left query (A)
92566 **     coB: coroutine for right query (B)
92567 **    outA: output one row of A
92568 **    outB: output one row of B (UNION and UNION ALL only)
92569 **    EofA: ...
92570 **    EofB: ...
92571 **    AltB: ...
92572 **    AeqB: ...
92573 **    AgtB: ...
92574 **    Init: initialize coroutine registers
92575 **          yield coA
92576 **          if eof(A) goto EofA
92577 **          yield coB
92578 **          if eof(B) goto EofB
92579 **    Cmpr: Compare A, B
92580 **          Jump AltB, AeqB, AgtB
92581 **     End: ...
92582 **
92583 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
92584 ** actually called using Gosub and they do not Return.  EofA and EofB loop
92585 ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
92586 ** and AgtB jump to either L2 or to one of EofA or EofB.
92587 */
92588 #ifndef SQLITE_OMIT_COMPOUND_SELECT
92589 static int multiSelectOrderBy(
92590   Parse *pParse,        /* Parsing context */
92591   Select *p,            /* The right-most of SELECTs to be coded */
92592   SelectDest *pDest     /* What to do with query results */
92593 ){
92594   int i, j;             /* Loop counters */
92595   Select *pPrior;       /* Another SELECT immediately to our left */
92596   Vdbe *v;              /* Generate code to this VDBE */
92597   SelectDest destA;     /* Destination for coroutine A */
92598   SelectDest destB;     /* Destination for coroutine B */
92599   int regAddrA;         /* Address register for select-A coroutine */
92600   int regEofA;          /* Flag to indicate when select-A is complete */
92601   int regAddrB;         /* Address register for select-B coroutine */
92602   int regEofB;          /* Flag to indicate when select-B is complete */
92603   int addrSelectA;      /* Address of the select-A coroutine */
92604   int addrSelectB;      /* Address of the select-B coroutine */
92605   int regOutA;          /* Address register for the output-A subroutine */
92606   int regOutB;          /* Address register for the output-B subroutine */
92607   int addrOutA;         /* Address of the output-A subroutine */
92608   int addrOutB = 0;     /* Address of the output-B subroutine */
92609   int addrEofA;         /* Address of the select-A-exhausted subroutine */
92610   int addrEofB;         /* Address of the select-B-exhausted subroutine */
92611   int addrAltB;         /* Address of the A<B subroutine */
92612   int addrAeqB;         /* Address of the A==B subroutine */
92613   int addrAgtB;         /* Address of the A>B subroutine */
92614   int regLimitA;        /* Limit register for select-A */
92615   int regLimitB;        /* Limit register for select-A */
92616   int regPrev;          /* A range of registers to hold previous output */
92617   int savedLimit;       /* Saved value of p->iLimit */
92618   int savedOffset;      /* Saved value of p->iOffset */
92619   int labelCmpr;        /* Label for the start of the merge algorithm */
92620   int labelEnd;         /* Label for the end of the overall SELECT stmt */
92621   int j1;               /* Jump instructions that get retargetted */
92622   int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
92623   KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
92624   KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
92625   sqlite3 *db;          /* Database connection */
92626   ExprList *pOrderBy;   /* The ORDER BY clause */
92627   int nOrderBy;         /* Number of terms in the ORDER BY clause */
92628   int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
92629 #ifndef SQLITE_OMIT_EXPLAIN
92630   int iSub1;            /* EQP id of left-hand query */
92631   int iSub2;            /* EQP id of right-hand query */
92632 #endif
92633
92634   assert( p->pOrderBy!=0 );
92635   assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
92636   db = pParse->db;
92637   v = pParse->pVdbe;
92638   assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
92639   labelEnd = sqlite3VdbeMakeLabel(v);
92640   labelCmpr = sqlite3VdbeMakeLabel(v);
92641
92642
92643   /* Patch up the ORDER BY clause
92644   */
92645   op = p->op;  
92646   pPrior = p->pPrior;
92647   assert( pPrior->pOrderBy==0 );
92648   pOrderBy = p->pOrderBy;
92649   assert( pOrderBy );
92650   nOrderBy = pOrderBy->nExpr;
92651
92652   /* For operators other than UNION ALL we have to make sure that
92653   ** the ORDER BY clause covers every term of the result set.  Add
92654   ** terms to the ORDER BY clause as necessary.
92655   */
92656   if( op!=TK_ALL ){
92657     for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
92658       struct ExprList_item *pItem;
92659       for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
92660         assert( pItem->iCol>0 );
92661         if( pItem->iCol==i ) break;
92662       }
92663       if( j==nOrderBy ){
92664         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
92665         if( pNew==0 ) return SQLITE_NOMEM;
92666         pNew->flags |= EP_IntValue;
92667         pNew->u.iValue = i;
92668         pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
92669         pOrderBy->a[nOrderBy++].iCol = (u16)i;
92670       }
92671     }
92672   }
92673
92674   /* Compute the comparison permutation and keyinfo that is used with
92675   ** the permutation used to determine if the next
92676   ** row of results comes from selectA or selectB.  Also add explicit
92677   ** collations to the ORDER BY clause terms so that when the subqueries
92678   ** to the right and the left are evaluated, they use the correct
92679   ** collation.
92680   */
92681   aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
92682   if( aPermute ){
92683     struct ExprList_item *pItem;
92684     for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
92685       assert( pItem->iCol>0  && pItem->iCol<=p->pEList->nExpr );
92686       aPermute[i] = pItem->iCol - 1;
92687     }
92688     pKeyMerge =
92689       sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
92690     if( pKeyMerge ){
92691       pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
92692       pKeyMerge->nField = (u16)nOrderBy;
92693       pKeyMerge->enc = ENC(db);
92694       for(i=0; i<nOrderBy; i++){
92695         CollSeq *pColl;
92696         Expr *pTerm = pOrderBy->a[i].pExpr;
92697         if( pTerm->flags & EP_ExpCollate ){
92698           pColl = pTerm->pColl;
92699         }else{
92700           pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
92701           pTerm->flags |= EP_ExpCollate;
92702           pTerm->pColl = pColl;
92703         }
92704         pKeyMerge->aColl[i] = pColl;
92705         pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
92706       }
92707     }
92708   }else{
92709     pKeyMerge = 0;
92710   }
92711
92712   /* Reattach the ORDER BY clause to the query.
92713   */
92714   p->pOrderBy = pOrderBy;
92715   pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
92716
92717   /* Allocate a range of temporary registers and the KeyInfo needed
92718   ** for the logic that removes duplicate result rows when the
92719   ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
92720   */
92721   if( op==TK_ALL ){
92722     regPrev = 0;
92723   }else{
92724     int nExpr = p->pEList->nExpr;
92725     assert( nOrderBy>=nExpr || db->mallocFailed );
92726     regPrev = sqlite3GetTempRange(pParse, nExpr+1);
92727     sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
92728     pKeyDup = sqlite3DbMallocZero(db,
92729                   sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
92730     if( pKeyDup ){
92731       pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
92732       pKeyDup->nField = (u16)nExpr;
92733       pKeyDup->enc = ENC(db);
92734       for(i=0; i<nExpr; i++){
92735         pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
92736         pKeyDup->aSortOrder[i] = 0;
92737       }
92738     }
92739   }
92740  
92741   /* Separate the left and the right query from one another
92742   */
92743   p->pPrior = 0;
92744   sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
92745   if( pPrior->pPrior==0 ){
92746     sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
92747   }
92748
92749   /* Compute the limit registers */
92750   computeLimitRegisters(pParse, p, labelEnd);
92751   if( p->iLimit && op==TK_ALL ){
92752     regLimitA = ++pParse->nMem;
92753     regLimitB = ++pParse->nMem;
92754     sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
92755                                   regLimitA);
92756     sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
92757   }else{
92758     regLimitA = regLimitB = 0;
92759   }
92760   sqlite3ExprDelete(db, p->pLimit);
92761   p->pLimit = 0;
92762   sqlite3ExprDelete(db, p->pOffset);
92763   p->pOffset = 0;
92764
92765   regAddrA = ++pParse->nMem;
92766   regEofA = ++pParse->nMem;
92767   regAddrB = ++pParse->nMem;
92768   regEofB = ++pParse->nMem;
92769   regOutA = ++pParse->nMem;
92770   regOutB = ++pParse->nMem;
92771   sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
92772   sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
92773
92774   /* Jump past the various subroutines and coroutines to the main
92775   ** merge loop
92776   */
92777   j1 = sqlite3VdbeAddOp0(v, OP_Goto);
92778   addrSelectA = sqlite3VdbeCurrentAddr(v);
92779
92780
92781   /* Generate a coroutine to evaluate the SELECT statement to the
92782   ** left of the compound operator - the "A" select.
92783   */
92784   VdbeNoopComment((v, "Begin coroutine for left SELECT"));
92785   pPrior->iLimit = regLimitA;
92786   explainSetInteger(iSub1, pParse->iNextSelectId);
92787   sqlite3Select(pParse, pPrior, &destA);
92788   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
92789   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
92790   VdbeNoopComment((v, "End coroutine for left SELECT"));
92791
92792   /* Generate a coroutine to evaluate the SELECT statement on 
92793   ** the right - the "B" select
92794   */
92795   addrSelectB = sqlite3VdbeCurrentAddr(v);
92796   VdbeNoopComment((v, "Begin coroutine for right SELECT"));
92797   savedLimit = p->iLimit;
92798   savedOffset = p->iOffset;
92799   p->iLimit = regLimitB;
92800   p->iOffset = 0;  
92801   explainSetInteger(iSub2, pParse->iNextSelectId);
92802   sqlite3Select(pParse, p, &destB);
92803   p->iLimit = savedLimit;
92804   p->iOffset = savedOffset;
92805   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
92806   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
92807   VdbeNoopComment((v, "End coroutine for right SELECT"));
92808
92809   /* Generate a subroutine that outputs the current row of the A
92810   ** select as the next output row of the compound select.
92811   */
92812   VdbeNoopComment((v, "Output routine for A"));
92813   addrOutA = generateOutputSubroutine(pParse,
92814                  p, &destA, pDest, regOutA,
92815                  regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
92816   
92817   /* Generate a subroutine that outputs the current row of the B
92818   ** select as the next output row of the compound select.
92819   */
92820   if( op==TK_ALL || op==TK_UNION ){
92821     VdbeNoopComment((v, "Output routine for B"));
92822     addrOutB = generateOutputSubroutine(pParse,
92823                  p, &destB, pDest, regOutB,
92824                  regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
92825   }
92826
92827   /* Generate a subroutine to run when the results from select A
92828   ** are exhausted and only data in select B remains.
92829   */
92830   VdbeNoopComment((v, "eof-A subroutine"));
92831   if( op==TK_EXCEPT || op==TK_INTERSECT ){
92832     addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
92833   }else{  
92834     addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
92835     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
92836     sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
92837     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
92838     p->nSelectRow += pPrior->nSelectRow;
92839   }
92840
92841   /* Generate a subroutine to run when the results from select B
92842   ** are exhausted and only data in select A remains.
92843   */
92844   if( op==TK_INTERSECT ){
92845     addrEofB = addrEofA;
92846     if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
92847   }else{  
92848     VdbeNoopComment((v, "eof-B subroutine"));
92849     addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
92850     sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
92851     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
92852     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
92853   }
92854
92855   /* Generate code to handle the case of A<B
92856   */
92857   VdbeNoopComment((v, "A-lt-B subroutine"));
92858   addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
92859   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
92860   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
92861   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
92862
92863   /* Generate code to handle the case of A==B
92864   */
92865   if( op==TK_ALL ){
92866     addrAeqB = addrAltB;
92867   }else if( op==TK_INTERSECT ){
92868     addrAeqB = addrAltB;
92869     addrAltB++;
92870   }else{
92871     VdbeNoopComment((v, "A-eq-B subroutine"));
92872     addrAeqB =
92873     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
92874     sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
92875     sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
92876   }
92877
92878   /* Generate code to handle the case of A>B
92879   */
92880   VdbeNoopComment((v, "A-gt-B subroutine"));
92881   addrAgtB = sqlite3VdbeCurrentAddr(v);
92882   if( op==TK_ALL || op==TK_UNION ){
92883     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
92884   }
92885   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
92886   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
92887   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
92888
92889   /* This code runs once to initialize everything.
92890   */
92891   sqlite3VdbeJumpHere(v, j1);
92892   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
92893   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
92894   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
92895   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
92896   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
92897   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
92898
92899   /* Implement the main merge loop
92900   */
92901   sqlite3VdbeResolveLabel(v, labelCmpr);
92902   sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
92903   sqlite3VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy,
92904                          (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
92905   sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
92906
92907   /* Release temporary registers
92908   */
92909   if( regPrev ){
92910     sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1);
92911   }
92912
92913   /* Jump to the this point in order to terminate the query.
92914   */
92915   sqlite3VdbeResolveLabel(v, labelEnd);
92916
92917   /* Set the number of output columns
92918   */
92919   if( pDest->eDest==SRT_Output ){
92920     Select *pFirst = pPrior;
92921     while( pFirst->pPrior ) pFirst = pFirst->pPrior;
92922     generateColumnNames(pParse, 0, pFirst->pEList);
92923   }
92924
92925   /* Reassembly the compound query so that it will be freed correctly
92926   ** by the calling function */
92927   if( p->pPrior ){
92928     sqlite3SelectDelete(db, p->pPrior);
92929   }
92930   p->pPrior = pPrior;
92931
92932   /*** TBD:  Insert subroutine calls to close cursors on incomplete
92933   **** subqueries ****/
92934   explainComposite(pParse, p->op, iSub1, iSub2, 0);
92935   return SQLITE_OK;
92936 }
92937 #endif
92938
92939 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
92940 /* Forward Declarations */
92941 static void substExprList(sqlite3*, ExprList*, int, ExprList*);
92942 static void substSelect(sqlite3*, Select *, int, ExprList *);
92943
92944 /*
92945 ** Scan through the expression pExpr.  Replace every reference to
92946 ** a column in table number iTable with a copy of the iColumn-th
92947 ** entry in pEList.  (But leave references to the ROWID column 
92948 ** unchanged.)
92949 **
92950 ** This routine is part of the flattening procedure.  A subquery
92951 ** whose result set is defined by pEList appears as entry in the
92952 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
92953 ** FORM clause entry is iTable.  This routine make the necessary 
92954 ** changes to pExpr so that it refers directly to the source table
92955 ** of the subquery rather the result set of the subquery.
92956 */
92957 static Expr *substExpr(
92958   sqlite3 *db,        /* Report malloc errors to this connection */
92959   Expr *pExpr,        /* Expr in which substitution occurs */
92960   int iTable,         /* Table to be substituted */
92961   ExprList *pEList    /* Substitute expressions */
92962 ){
92963   if( pExpr==0 ) return 0;
92964   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
92965     if( pExpr->iColumn<0 ){
92966       pExpr->op = TK_NULL;
92967     }else{
92968       Expr *pNew;
92969       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
92970       assert( pExpr->pLeft==0 && pExpr->pRight==0 );
92971       pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
92972       if( pNew && pExpr->pColl ){
92973         pNew->pColl = pExpr->pColl;
92974       }
92975       sqlite3ExprDelete(db, pExpr);
92976       pExpr = pNew;
92977     }
92978   }else{
92979     pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
92980     pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
92981     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
92982       substSelect(db, pExpr->x.pSelect, iTable, pEList);
92983     }else{
92984       substExprList(db, pExpr->x.pList, iTable, pEList);
92985     }
92986   }
92987   return pExpr;
92988 }
92989 static void substExprList(
92990   sqlite3 *db,         /* Report malloc errors here */
92991   ExprList *pList,     /* List to scan and in which to make substitutes */
92992   int iTable,          /* Table to be substituted */
92993   ExprList *pEList     /* Substitute values */
92994 ){
92995   int i;
92996   if( pList==0 ) return;
92997   for(i=0; i<pList->nExpr; i++){
92998     pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
92999   }
93000 }
93001 static void substSelect(
93002   sqlite3 *db,         /* Report malloc errors here */
93003   Select *p,           /* SELECT statement in which to make substitutions */
93004   int iTable,          /* Table to be replaced */
93005   ExprList *pEList     /* Substitute values */
93006 ){
93007   SrcList *pSrc;
93008   struct SrcList_item *pItem;
93009   int i;
93010   if( !p ) return;
93011   substExprList(db, p->pEList, iTable, pEList);
93012   substExprList(db, p->pGroupBy, iTable, pEList);
93013   substExprList(db, p->pOrderBy, iTable, pEList);
93014   p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
93015   p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
93016   substSelect(db, p->pPrior, iTable, pEList);
93017   pSrc = p->pSrc;
93018   assert( pSrc );  /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
93019   if( ALWAYS(pSrc) ){
93020     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
93021       substSelect(db, pItem->pSelect, iTable, pEList);
93022     }
93023   }
93024 }
93025 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
93026
93027 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
93028 /*
93029 ** This routine attempts to flatten subqueries in order to speed
93030 ** execution.  It returns 1 if it makes changes and 0 if no flattening
93031 ** occurs.
93032 **
93033 ** To understand the concept of flattening, consider the following
93034 ** query:
93035 **
93036 **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
93037 **
93038 ** The default way of implementing this query is to execute the
93039 ** subquery first and store the results in a temporary table, then
93040 ** run the outer query on that temporary table.  This requires two
93041 ** passes over the data.  Furthermore, because the temporary table
93042 ** has no indices, the WHERE clause on the outer query cannot be
93043 ** optimized.
93044 **
93045 ** This routine attempts to rewrite queries such as the above into
93046 ** a single flat select, like this:
93047 **
93048 **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
93049 **
93050 ** The code generated for this simpification gives the same result
93051 ** but only has to scan the data once.  And because indices might 
93052 ** exist on the table t1, a complete scan of the data might be
93053 ** avoided.
93054 **
93055 ** Flattening is only attempted if all of the following are true:
93056 **
93057 **   (1)  The subquery and the outer query do not both use aggregates.
93058 **
93059 **   (2)  The subquery is not an aggregate or the outer query is not a join.
93060 **
93061 **   (3)  The subquery is not the right operand of a left outer join
93062 **        (Originally ticket #306.  Strengthened by ticket #3300)
93063 **
93064 **   (4)  The subquery is not DISTINCT.
93065 **
93066 **  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
93067 **        sub-queries that were excluded from this optimization. Restriction 
93068 **        (4) has since been expanded to exclude all DISTINCT subqueries.
93069 **
93070 **   (6)  The subquery does not use aggregates or the outer query is not
93071 **        DISTINCT.
93072 **
93073 **   (7)  The subquery has a FROM clause.
93074 **
93075 **   (8)  The subquery does not use LIMIT or the outer query is not a join.
93076 **
93077 **   (9)  The subquery does not use LIMIT or the outer query does not use
93078 **        aggregates.
93079 **
93080 **  (10)  The subquery does not use aggregates or the outer query does not
93081 **        use LIMIT.
93082 **
93083 **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
93084 **
93085 **  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
93086 **        a separate restriction deriving from ticket #350.
93087 **
93088 **  (13)  The subquery and outer query do not both use LIMIT.
93089 **
93090 **  (14)  The subquery does not use OFFSET.
93091 **
93092 **  (15)  The outer query is not part of a compound select or the
93093 **        subquery does not have a LIMIT clause.
93094 **        (See ticket #2339 and ticket [02a8e81d44]).
93095 **
93096 **  (16)  The outer query is not an aggregate or the subquery does
93097 **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
93098 **        until we introduced the group_concat() function.  
93099 **
93100 **  (17)  The sub-query is not a compound select, or it is a UNION ALL 
93101 **        compound clause made up entirely of non-aggregate queries, and 
93102 **        the parent query:
93103 **
93104 **          * is not itself part of a compound select,
93105 **          * is not an aggregate or DISTINCT query, and
93106 **          * has no other tables or sub-selects in the FROM clause.
93107 **
93108 **        The parent and sub-query may contain WHERE clauses. Subject to
93109 **        rules (11), (13) and (14), they may also contain ORDER BY,
93110 **        LIMIT and OFFSET clauses.
93111 **
93112 **  (18)  If the sub-query is a compound select, then all terms of the
93113 **        ORDER by clause of the parent must be simple references to 
93114 **        columns of the sub-query.
93115 **
93116 **  (19)  The subquery does not use LIMIT or the outer query does not
93117 **        have a WHERE clause.
93118 **
93119 **  (20)  If the sub-query is a compound select, then it must not use
93120 **        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
93121 **        somewhat by saying that the terms of the ORDER BY clause must
93122 **        appear as unmodified result columns in the outer query.  But
93123 **        have other optimizations in mind to deal with that case.
93124 **
93125 **  (21)  The subquery does not use LIMIT or the outer query is not
93126 **        DISTINCT.  (See ticket [752e1646fc]).
93127 **
93128 ** In this routine, the "p" parameter is a pointer to the outer query.
93129 ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
93130 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
93131 **
93132 ** If flattening is not attempted, this routine is a no-op and returns 0.
93133 ** If flattening is attempted this routine returns 1.
93134 **
93135 ** All of the expression analysis must occur on both the outer query and
93136 ** the subquery before this routine runs.
93137 */
93138 static int flattenSubquery(
93139   Parse *pParse,       /* Parsing context */
93140   Select *p,           /* The parent or outer SELECT statement */
93141   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
93142   int isAgg,           /* True if outer SELECT uses aggregate functions */
93143   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
93144 ){
93145   const char *zSavedAuthContext = pParse->zAuthContext;
93146   Select *pParent;
93147   Select *pSub;       /* The inner query or "subquery" */
93148   Select *pSub1;      /* Pointer to the rightmost select in sub-query */
93149   SrcList *pSrc;      /* The FROM clause of the outer query */
93150   SrcList *pSubSrc;   /* The FROM clause of the subquery */
93151   ExprList *pList;    /* The result set of the outer query */
93152   int iParent;        /* VDBE cursor number of the pSub result set temp table */
93153   int i;              /* Loop counter */
93154   Expr *pWhere;                    /* The WHERE clause */
93155   struct SrcList_item *pSubitem;   /* The subquery */
93156   sqlite3 *db = pParse->db;
93157
93158   /* Check to see if flattening is permitted.  Return 0 if not.
93159   */
93160   assert( p!=0 );
93161   assert( p->pPrior==0 );  /* Unable to flatten compound queries */
93162   if( db->flags & SQLITE_QueryFlattener ) return 0;
93163   pSrc = p->pSrc;
93164   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
93165   pSubitem = &pSrc->a[iFrom];
93166   iParent = pSubitem->iCursor;
93167   pSub = pSubitem->pSelect;
93168   assert( pSub!=0 );
93169   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
93170   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
93171   pSubSrc = pSub->pSrc;
93172   assert( pSubSrc );
93173   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
93174   ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
93175   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
93176   ** became arbitrary expressions, we were forced to add restrictions (13)
93177   ** and (14). */
93178   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
93179   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
93180   if( p->pRightmost && pSub->pLimit ){
93181     return 0;                                            /* Restriction (15) */
93182   }
93183   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
93184   if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (5)  */
93185   if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
93186      return 0;         /* Restrictions (8)(9) */
93187   }
93188   if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
93189      return 0;         /* Restriction (6)  */
93190   }
93191   if( p->pOrderBy && pSub->pOrderBy ){
93192      return 0;                                           /* Restriction (11) */
93193   }
93194   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
93195   if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
93196   if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
93197      return 0;         /* Restriction (21) */
93198   }
93199
93200   /* OBSOLETE COMMENT 1:
93201   ** Restriction 3:  If the subquery is a join, make sure the subquery is 
93202   ** not used as the right operand of an outer join.  Examples of why this
93203   ** is not allowed:
93204   **
93205   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
93206   **
93207   ** If we flatten the above, we would get
93208   **
93209   **         (t1 LEFT OUTER JOIN t2) JOIN t3
93210   **
93211   ** which is not at all the same thing.
93212   **
93213   ** OBSOLETE COMMENT 2:
93214   ** Restriction 12:  If the subquery is the right operand of a left outer
93215   ** join, make sure the subquery has no WHERE clause.
93216   ** An examples of why this is not allowed:
93217   **
93218   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
93219   **
93220   ** If we flatten the above, we would get
93221   **
93222   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
93223   **
93224   ** But the t2.x>0 test will always fail on a NULL row of t2, which
93225   ** effectively converts the OUTER JOIN into an INNER JOIN.
93226   **
93227   ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
93228   ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
93229   ** is fraught with danger.  Best to avoid the whole thing.  If the
93230   ** subquery is the right term of a LEFT JOIN, then do not flatten.
93231   */
93232   if( (pSubitem->jointype & JT_OUTER)!=0 ){
93233     return 0;
93234   }
93235
93236   /* Restriction 17: If the sub-query is a compound SELECT, then it must
93237   ** use only the UNION ALL operator. And none of the simple select queries
93238   ** that make up the compound SELECT are allowed to be aggregate or distinct
93239   ** queries.
93240   */
93241   if( pSub->pPrior ){
93242     if( pSub->pOrderBy ){
93243       return 0;  /* Restriction 20 */
93244     }
93245     if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
93246       return 0;
93247     }
93248     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
93249       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
93250       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
93251       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
93252        || (pSub1->pPrior && pSub1->op!=TK_ALL) 
93253        || NEVER(pSub1->pSrc==0) || pSub1->pSrc->nSrc!=1
93254       ){
93255         return 0;
93256       }
93257     }
93258
93259     /* Restriction 18. */
93260     if( p->pOrderBy ){
93261       int ii;
93262       for(ii=0; ii<p->pOrderBy->nExpr; ii++){
93263         if( p->pOrderBy->a[ii].iCol==0 ) return 0;
93264       }
93265     }
93266   }
93267
93268   /***** If we reach this point, flattening is permitted. *****/
93269
93270   /* Authorize the subquery */
93271   pParse->zAuthContext = pSubitem->zName;
93272   sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
93273   pParse->zAuthContext = zSavedAuthContext;
93274
93275   /* If the sub-query is a compound SELECT statement, then (by restrictions
93276   ** 17 and 18 above) it must be a UNION ALL and the parent query must 
93277   ** be of the form:
93278   **
93279   **     SELECT <expr-list> FROM (<sub-query>) <where-clause> 
93280   **
93281   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
93282   ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or 
93283   ** OFFSET clauses and joins them to the left-hand-side of the original
93284   ** using UNION ALL operators. In this case N is the number of simple
93285   ** select statements in the compound sub-query.
93286   **
93287   ** Example:
93288   **
93289   **     SELECT a+1 FROM (
93290   **        SELECT x FROM tab
93291   **        UNION ALL
93292   **        SELECT y FROM tab
93293   **        UNION ALL
93294   **        SELECT abs(z*2) FROM tab2
93295   **     ) WHERE a!=5 ORDER BY 1
93296   **
93297   ** Transformed into:
93298   **
93299   **     SELECT x+1 FROM tab WHERE x+1!=5
93300   **     UNION ALL
93301   **     SELECT y+1 FROM tab WHERE y+1!=5
93302   **     UNION ALL
93303   **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
93304   **     ORDER BY 1
93305   **
93306   ** We call this the "compound-subquery flattening".
93307   */
93308   for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
93309     Select *pNew;
93310     ExprList *pOrderBy = p->pOrderBy;
93311     Expr *pLimit = p->pLimit;
93312     Select *pPrior = p->pPrior;
93313     p->pOrderBy = 0;
93314     p->pSrc = 0;
93315     p->pPrior = 0;
93316     p->pLimit = 0;
93317     pNew = sqlite3SelectDup(db, p, 0);
93318     p->pLimit = pLimit;
93319     p->pOrderBy = pOrderBy;
93320     p->pSrc = pSrc;
93321     p->op = TK_ALL;
93322     p->pRightmost = 0;
93323     if( pNew==0 ){
93324       pNew = pPrior;
93325     }else{
93326       pNew->pPrior = pPrior;
93327       pNew->pRightmost = 0;
93328     }
93329     p->pPrior = pNew;
93330     if( db->mallocFailed ) return 1;
93331   }
93332
93333   /* Begin flattening the iFrom-th entry of the FROM clause 
93334   ** in the outer query.
93335   */
93336   pSub = pSub1 = pSubitem->pSelect;
93337
93338   /* Delete the transient table structure associated with the
93339   ** subquery
93340   */
93341   sqlite3DbFree(db, pSubitem->zDatabase);
93342   sqlite3DbFree(db, pSubitem->zName);
93343   sqlite3DbFree(db, pSubitem->zAlias);
93344   pSubitem->zDatabase = 0;
93345   pSubitem->zName = 0;
93346   pSubitem->zAlias = 0;
93347   pSubitem->pSelect = 0;
93348
93349   /* Defer deleting the Table object associated with the
93350   ** subquery until code generation is
93351   ** complete, since there may still exist Expr.pTab entries that
93352   ** refer to the subquery even after flattening.  Ticket #3346.
93353   **
93354   ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
93355   */
93356   if( ALWAYS(pSubitem->pTab!=0) ){
93357     Table *pTabToDel = pSubitem->pTab;
93358     if( pTabToDel->nRef==1 ){
93359       Parse *pToplevel = sqlite3ParseToplevel(pParse);
93360       pTabToDel->pNextZombie = pToplevel->pZombieTab;
93361       pToplevel->pZombieTab = pTabToDel;
93362     }else{
93363       pTabToDel->nRef--;
93364     }
93365     pSubitem->pTab = 0;
93366   }
93367
93368   /* The following loop runs once for each term in a compound-subquery
93369   ** flattening (as described above).  If we are doing a different kind
93370   ** of flattening - a flattening other than a compound-subquery flattening -
93371   ** then this loop only runs once.
93372   **
93373   ** This loop moves all of the FROM elements of the subquery into the
93374   ** the FROM clause of the outer query.  Before doing this, remember
93375   ** the cursor number for the original outer query FROM element in
93376   ** iParent.  The iParent cursor will never be used.  Subsequent code
93377   ** will scan expressions looking for iParent references and replace
93378   ** those references with expressions that resolve to the subquery FROM
93379   ** elements we are now copying in.
93380   */
93381   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
93382     int nSubSrc;
93383     u8 jointype = 0;
93384     pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
93385     nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
93386     pSrc = pParent->pSrc;     /* FROM clause of the outer query */
93387
93388     if( pSrc ){
93389       assert( pParent==p );  /* First time through the loop */
93390       jointype = pSubitem->jointype;
93391     }else{
93392       assert( pParent!=p );  /* 2nd and subsequent times through the loop */
93393       pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
93394       if( pSrc==0 ){
93395         assert( db->mallocFailed );
93396         break;
93397       }
93398     }
93399
93400     /* The subquery uses a single slot of the FROM clause of the outer
93401     ** query.  If the subquery has more than one element in its FROM clause,
93402     ** then expand the outer query to make space for it to hold all elements
93403     ** of the subquery.
93404     **
93405     ** Example:
93406     **
93407     **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
93408     **
93409     ** The outer query has 3 slots in its FROM clause.  One slot of the
93410     ** outer query (the middle slot) is used by the subquery.  The next
93411     ** block of code will expand the out query to 4 slots.  The middle
93412     ** slot is expanded to two slots in order to make space for the
93413     ** two elements in the FROM clause of the subquery.
93414     */
93415     if( nSubSrc>1 ){
93416       pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
93417       if( db->mallocFailed ){
93418         break;
93419       }
93420     }
93421
93422     /* Transfer the FROM clause terms from the subquery into the
93423     ** outer query.
93424     */
93425     for(i=0; i<nSubSrc; i++){
93426       sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
93427       pSrc->a[i+iFrom] = pSubSrc->a[i];
93428       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
93429     }
93430     pSrc->a[iFrom].jointype = jointype;
93431   
93432     /* Now begin substituting subquery result set expressions for 
93433     ** references to the iParent in the outer query.
93434     ** 
93435     ** Example:
93436     **
93437     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
93438     **   \                     \_____________ subquery __________/          /
93439     **    \_____________________ outer query ______________________________/
93440     **
93441     ** We look at every expression in the outer query and every place we see
93442     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
93443     */
93444     pList = pParent->pEList;
93445     for(i=0; i<pList->nExpr; i++){
93446       if( pList->a[i].zName==0 ){
93447         const char *zSpan = pList->a[i].zSpan;
93448         if( ALWAYS(zSpan) ){
93449           pList->a[i].zName = sqlite3DbStrDup(db, zSpan);
93450         }
93451       }
93452     }
93453     substExprList(db, pParent->pEList, iParent, pSub->pEList);
93454     if( isAgg ){
93455       substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
93456       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
93457     }
93458     if( pSub->pOrderBy ){
93459       assert( pParent->pOrderBy==0 );
93460       pParent->pOrderBy = pSub->pOrderBy;
93461       pSub->pOrderBy = 0;
93462     }else if( pParent->pOrderBy ){
93463       substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
93464     }
93465     if( pSub->pWhere ){
93466       pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
93467     }else{
93468       pWhere = 0;
93469     }
93470     if( subqueryIsAgg ){
93471       assert( pParent->pHaving==0 );
93472       pParent->pHaving = pParent->pWhere;
93473       pParent->pWhere = pWhere;
93474       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
93475       pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving, 
93476                                   sqlite3ExprDup(db, pSub->pHaving, 0));
93477       assert( pParent->pGroupBy==0 );
93478       pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
93479     }else{
93480       pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
93481       pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
93482     }
93483   
93484     /* The flattened query is distinct if either the inner or the
93485     ** outer query is distinct. 
93486     */
93487     pParent->selFlags |= pSub->selFlags & SF_Distinct;
93488   
93489     /*
93490     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
93491     **
93492     ** One is tempted to try to add a and b to combine the limits.  But this
93493     ** does not work if either limit is negative.
93494     */
93495     if( pSub->pLimit ){
93496       pParent->pLimit = pSub->pLimit;
93497       pSub->pLimit = 0;
93498     }
93499   }
93500
93501   /* Finially, delete what is left of the subquery and return
93502   ** success.
93503   */
93504   sqlite3SelectDelete(db, pSub1);
93505
93506   return 1;
93507 }
93508 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
93509
93510 /*
93511 ** Analyze the SELECT statement passed as an argument to see if it
93512 ** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if 
93513 ** it is, or 0 otherwise. At present, a query is considered to be
93514 ** a min()/max() query if:
93515 **
93516 **   1. There is a single object in the FROM clause.
93517 **
93518 **   2. There is a single expression in the result set, and it is
93519 **      either min(x) or max(x), where x is a column reference.
93520 */
93521 static u8 minMaxQuery(Select *p){
93522   Expr *pExpr;
93523   ExprList *pEList = p->pEList;
93524
93525   if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
93526   pExpr = pEList->a[0].pExpr;
93527   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
93528   if( NEVER(ExprHasProperty(pExpr, EP_xIsSelect)) ) return 0;
93529   pEList = pExpr->x.pList;
93530   if( pEList==0 || pEList->nExpr!=1 ) return 0;
93531   if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
93532   assert( !ExprHasProperty(pExpr, EP_IntValue) );
93533   if( sqlite3StrICmp(pExpr->u.zToken,"min")==0 ){
93534     return WHERE_ORDERBY_MIN;
93535   }else if( sqlite3StrICmp(pExpr->u.zToken,"max")==0 ){
93536     return WHERE_ORDERBY_MAX;
93537   }
93538   return WHERE_ORDERBY_NORMAL;
93539 }
93540
93541 /*
93542 ** The select statement passed as the first argument is an aggregate query.
93543 ** The second argment is the associated aggregate-info object. This 
93544 ** function tests if the SELECT is of the form:
93545 **
93546 **   SELECT count(*) FROM <tbl>
93547 **
93548 ** where table is a database table, not a sub-select or view. If the query
93549 ** does match this pattern, then a pointer to the Table object representing
93550 ** <tbl> is returned. Otherwise, 0 is returned.
93551 */
93552 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
93553   Table *pTab;
93554   Expr *pExpr;
93555
93556   assert( !p->pGroupBy );
93557
93558   if( p->pWhere || p->pEList->nExpr!=1 
93559    || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
93560   ){
93561     return 0;
93562   }
93563   pTab = p->pSrc->a[0].pTab;
93564   pExpr = p->pEList->a[0].pExpr;
93565   assert( pTab && !pTab->pSelect && pExpr );
93566
93567   if( IsVirtual(pTab) ) return 0;
93568   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
93569   if( (pAggInfo->aFunc[0].pFunc->flags&SQLITE_FUNC_COUNT)==0 ) return 0;
93570   if( pExpr->flags&EP_Distinct ) return 0;
93571
93572   return pTab;
93573 }
93574
93575 /*
93576 ** If the source-list item passed as an argument was augmented with an
93577 ** INDEXED BY clause, then try to locate the specified index. If there
93578 ** was such a clause and the named index cannot be found, return 
93579 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate 
93580 ** pFrom->pIndex and return SQLITE_OK.
93581 */
93582 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
93583   if( pFrom->pTab && pFrom->zIndex ){
93584     Table *pTab = pFrom->pTab;
93585     char *zIndex = pFrom->zIndex;
93586     Index *pIdx;
93587     for(pIdx=pTab->pIndex; 
93588         pIdx && sqlite3StrICmp(pIdx->zName, zIndex); 
93589         pIdx=pIdx->pNext
93590     );
93591     if( !pIdx ){
93592       sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
93593       pParse->checkSchema = 1;
93594       return SQLITE_ERROR;
93595     }
93596     pFrom->pIndex = pIdx;
93597   }
93598   return SQLITE_OK;
93599 }
93600
93601 /*
93602 ** This routine is a Walker callback for "expanding" a SELECT statement.
93603 ** "Expanding" means to do the following:
93604 **
93605 **    (1)  Make sure VDBE cursor numbers have been assigned to every
93606 **         element of the FROM clause.
93607 **
93608 **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that 
93609 **         defines FROM clause.  When views appear in the FROM clause,
93610 **         fill pTabList->a[].pSelect with a copy of the SELECT statement
93611 **         that implements the view.  A copy is made of the view's SELECT
93612 **         statement so that we can freely modify or delete that statement
93613 **         without worrying about messing up the presistent representation
93614 **         of the view.
93615 **
93616 **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
93617 **         on joins and the ON and USING clause of joins.
93618 **
93619 **    (4)  Scan the list of columns in the result set (pEList) looking
93620 **         for instances of the "*" operator or the TABLE.* operator.
93621 **         If found, expand each "*" to be every column in every table
93622 **         and TABLE.* to be every column in TABLE.
93623 **
93624 */
93625 static int selectExpander(Walker *pWalker, Select *p){
93626   Parse *pParse = pWalker->pParse;
93627   int i, j, k;
93628   SrcList *pTabList;
93629   ExprList *pEList;
93630   struct SrcList_item *pFrom;
93631   sqlite3 *db = pParse->db;
93632
93633   if( db->mallocFailed  ){
93634     return WRC_Abort;
93635   }
93636   if( NEVER(p->pSrc==0) || (p->selFlags & SF_Expanded)!=0 ){
93637     return WRC_Prune;
93638   }
93639   p->selFlags |= SF_Expanded;
93640   pTabList = p->pSrc;
93641   pEList = p->pEList;
93642
93643   /* Make sure cursor numbers have been assigned to all entries in
93644   ** the FROM clause of the SELECT statement.
93645   */
93646   sqlite3SrcListAssignCursors(pParse, pTabList);
93647
93648   /* Look up every table named in the FROM clause of the select.  If
93649   ** an entry of the FROM clause is a subquery instead of a table or view,
93650   ** then create a transient table structure to describe the subquery.
93651   */
93652   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
93653     Table *pTab;
93654     if( pFrom->pTab!=0 ){
93655       /* This statement has already been prepared.  There is no need
93656       ** to go further. */
93657       assert( i==0 );
93658       return WRC_Prune;
93659     }
93660     if( pFrom->zName==0 ){
93661 #ifndef SQLITE_OMIT_SUBQUERY
93662       Select *pSel = pFrom->pSelect;
93663       /* A sub-query in the FROM clause of a SELECT */
93664       assert( pSel!=0 );
93665       assert( pFrom->pTab==0 );
93666       sqlite3WalkSelect(pWalker, pSel);
93667       pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
93668       if( pTab==0 ) return WRC_Abort;
93669       pTab->nRef = 1;
93670       pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
93671       while( pSel->pPrior ){ pSel = pSel->pPrior; }
93672       selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
93673       pTab->iPKey = -1;
93674       pTab->nRowEst = 1000000;
93675       pTab->tabFlags |= TF_Ephemeral;
93676 #endif
93677     }else{
93678       /* An ordinary table or view name in the FROM clause */
93679       assert( pFrom->pTab==0 );
93680       pFrom->pTab = pTab = 
93681         sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);
93682       if( pTab==0 ) return WRC_Abort;
93683       pTab->nRef++;
93684 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
93685       if( pTab->pSelect || IsVirtual(pTab) ){
93686         /* We reach here if the named table is a really a view */
93687         if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
93688         assert( pFrom->pSelect==0 );
93689         pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
93690         sqlite3WalkSelect(pWalker, pFrom->pSelect);
93691       }
93692 #endif
93693     }
93694
93695     /* Locate the index named by the INDEXED BY clause, if any. */
93696     if( sqlite3IndexedByLookup(pParse, pFrom) ){
93697       return WRC_Abort;
93698     }
93699   }
93700
93701   /* Process NATURAL keywords, and ON and USING clauses of joins.
93702   */
93703   if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
93704     return WRC_Abort;
93705   }
93706
93707   /* For every "*" that occurs in the column list, insert the names of
93708   ** all columns in all tables.  And for every TABLE.* insert the names
93709   ** of all columns in TABLE.  The parser inserted a special expression
93710   ** with the TK_ALL operator for each "*" that it found in the column list.
93711   ** The following code just has to locate the TK_ALL expressions and expand
93712   ** each one to the list of all columns in all tables.
93713   **
93714   ** The first loop just checks to see if there are any "*" operators
93715   ** that need expanding.
93716   */
93717   for(k=0; k<pEList->nExpr; k++){
93718     Expr *pE = pEList->a[k].pExpr;
93719     if( pE->op==TK_ALL ) break;
93720     assert( pE->op!=TK_DOT || pE->pRight!=0 );
93721     assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
93722     if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
93723   }
93724   if( k<pEList->nExpr ){
93725     /*
93726     ** If we get here it means the result set contains one or more "*"
93727     ** operators that need to be expanded.  Loop through each expression
93728     ** in the result set and expand them one by one.
93729     */
93730     struct ExprList_item *a = pEList->a;
93731     ExprList *pNew = 0;
93732     int flags = pParse->db->flags;
93733     int longNames = (flags & SQLITE_FullColNames)!=0
93734                       && (flags & SQLITE_ShortColNames)==0;
93735
93736     for(k=0; k<pEList->nExpr; k++){
93737       Expr *pE = a[k].pExpr;
93738       assert( pE->op!=TK_DOT || pE->pRight!=0 );
93739       if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pE->pRight->op!=TK_ALL) ){
93740         /* This particular expression does not need to be expanded.
93741         */
93742         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
93743         if( pNew ){
93744           pNew->a[pNew->nExpr-1].zName = a[k].zName;
93745           pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
93746           a[k].zName = 0;
93747           a[k].zSpan = 0;
93748         }
93749         a[k].pExpr = 0;
93750       }else{
93751         /* This expression is a "*" or a "TABLE.*" and needs to be
93752         ** expanded. */
93753         int tableSeen = 0;      /* Set to 1 when TABLE matches */
93754         char *zTName;            /* text of name of TABLE */
93755         if( pE->op==TK_DOT ){
93756           assert( pE->pLeft!=0 );
93757           assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
93758           zTName = pE->pLeft->u.zToken;
93759         }else{
93760           zTName = 0;
93761         }
93762         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
93763           Table *pTab = pFrom->pTab;
93764           char *zTabName = pFrom->zAlias;
93765           if( zTabName==0 ){
93766             zTabName = pTab->zName;
93767           }
93768           if( db->mallocFailed ) break;
93769           if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
93770             continue;
93771           }
93772           tableSeen = 1;
93773           for(j=0; j<pTab->nCol; j++){
93774             Expr *pExpr, *pRight;
93775             char *zName = pTab->aCol[j].zName;
93776             char *zColname;  /* The computed column name */
93777             char *zToFree;   /* Malloced string that needs to be freed */
93778             Token sColname;  /* Computed column name as a token */
93779
93780             /* If a column is marked as 'hidden' (currently only possible
93781             ** for virtual tables), do not include it in the expanded
93782             ** result-set list.
93783             */
93784             if( IsHiddenColumn(&pTab->aCol[j]) ){
93785               assert(IsVirtual(pTab));
93786               continue;
93787             }
93788
93789             if( i>0 && zTName==0 ){
93790               if( (pFrom->jointype & JT_NATURAL)!=0
93791                 && tableAndColumnIndex(pTabList, i, zName, 0, 0)
93792               ){
93793                 /* In a NATURAL join, omit the join columns from the 
93794                 ** table to the right of the join */
93795                 continue;
93796               }
93797               if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
93798                 /* In a join with a USING clause, omit columns in the
93799                 ** using clause from the table on the right. */
93800                 continue;
93801               }
93802             }
93803             pRight = sqlite3Expr(db, TK_ID, zName);
93804             zColname = zName;
93805             zToFree = 0;
93806             if( longNames || pTabList->nSrc>1 ){
93807               Expr *pLeft;
93808               pLeft = sqlite3Expr(db, TK_ID, zTabName);
93809               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
93810               if( longNames ){
93811                 zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
93812                 zToFree = zColname;
93813               }
93814             }else{
93815               pExpr = pRight;
93816             }
93817             pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
93818             sColname.z = zColname;
93819             sColname.n = sqlite3Strlen30(zColname);
93820             sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
93821             sqlite3DbFree(db, zToFree);
93822           }
93823         }
93824         if( !tableSeen ){
93825           if( zTName ){
93826             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
93827           }else{
93828             sqlite3ErrorMsg(pParse, "no tables specified");
93829           }
93830         }
93831       }
93832     }
93833     sqlite3ExprListDelete(db, pEList);
93834     p->pEList = pNew;
93835   }
93836 #if SQLITE_MAX_COLUMN
93837   if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
93838     sqlite3ErrorMsg(pParse, "too many columns in result set");
93839   }
93840 #endif
93841   return WRC_Continue;
93842 }
93843
93844 /*
93845 ** No-op routine for the parse-tree walker.
93846 **
93847 ** When this routine is the Walker.xExprCallback then expression trees
93848 ** are walked without any actions being taken at each node.  Presumably,
93849 ** when this routine is used for Walker.xExprCallback then 
93850 ** Walker.xSelectCallback is set to do something useful for every 
93851 ** subquery in the parser tree.
93852 */
93853 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
93854   UNUSED_PARAMETER2(NotUsed, NotUsed2);
93855   return WRC_Continue;
93856 }
93857
93858 /*
93859 ** This routine "expands" a SELECT statement and all of its subqueries.
93860 ** For additional information on what it means to "expand" a SELECT
93861 ** statement, see the comment on the selectExpand worker callback above.
93862 **
93863 ** Expanding a SELECT statement is the first step in processing a
93864 ** SELECT statement.  The SELECT statement must be expanded before
93865 ** name resolution is performed.
93866 **
93867 ** If anything goes wrong, an error message is written into pParse.
93868 ** The calling function can detect the problem by looking at pParse->nErr
93869 ** and/or pParse->db->mallocFailed.
93870 */
93871 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
93872   Walker w;
93873   w.xSelectCallback = selectExpander;
93874   w.xExprCallback = exprWalkNoop;
93875   w.pParse = pParse;
93876   sqlite3WalkSelect(&w, pSelect);
93877 }
93878
93879
93880 #ifndef SQLITE_OMIT_SUBQUERY
93881 /*
93882 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
93883 ** interface.
93884 **
93885 ** For each FROM-clause subquery, add Column.zType and Column.zColl
93886 ** information to the Table structure that represents the result set
93887 ** of that subquery.
93888 **
93889 ** The Table structure that represents the result set was constructed
93890 ** by selectExpander() but the type and collation information was omitted
93891 ** at that point because identifiers had not yet been resolved.  This
93892 ** routine is called after identifier resolution.
93893 */
93894 static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
93895   Parse *pParse;
93896   int i;
93897   SrcList *pTabList;
93898   struct SrcList_item *pFrom;
93899
93900   assert( p->selFlags & SF_Resolved );
93901   if( (p->selFlags & SF_HasTypeInfo)==0 ){
93902     p->selFlags |= SF_HasTypeInfo;
93903     pParse = pWalker->pParse;
93904     pTabList = p->pSrc;
93905     for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
93906       Table *pTab = pFrom->pTab;
93907       if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
93908         /* A sub-query in the FROM clause of a SELECT */
93909         Select *pSel = pFrom->pSelect;
93910         assert( pSel );
93911         while( pSel->pPrior ) pSel = pSel->pPrior;
93912         selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
93913       }
93914     }
93915   }
93916   return WRC_Continue;
93917 }
93918 #endif
93919
93920
93921 /*
93922 ** This routine adds datatype and collating sequence information to
93923 ** the Table structures of all FROM-clause subqueries in a
93924 ** SELECT statement.
93925 **
93926 ** Use this routine after name resolution.
93927 */
93928 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
93929 #ifndef SQLITE_OMIT_SUBQUERY
93930   Walker w;
93931   w.xSelectCallback = selectAddSubqueryTypeInfo;
93932   w.xExprCallback = exprWalkNoop;
93933   w.pParse = pParse;
93934   sqlite3WalkSelect(&w, pSelect);
93935 #endif
93936 }
93937
93938
93939 /*
93940 ** This routine sets of a SELECT statement for processing.  The
93941 ** following is accomplished:
93942 **
93943 **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
93944 **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
93945 **     *  ON and USING clauses are shifted into WHERE statements
93946 **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
93947 **     *  Identifiers in expression are matched to tables.
93948 **
93949 ** This routine acts recursively on all subqueries within the SELECT.
93950 */
93951 SQLITE_PRIVATE void sqlite3SelectPrep(
93952   Parse *pParse,         /* The parser context */
93953   Select *p,             /* The SELECT statement being coded. */
93954   NameContext *pOuterNC  /* Name context for container */
93955 ){
93956   sqlite3 *db;
93957   if( NEVER(p==0) ) return;
93958   db = pParse->db;
93959   if( p->selFlags & SF_HasTypeInfo ) return;
93960   sqlite3SelectExpand(pParse, p);
93961   if( pParse->nErr || db->mallocFailed ) return;
93962   sqlite3ResolveSelectNames(pParse, p, pOuterNC);
93963   if( pParse->nErr || db->mallocFailed ) return;
93964   sqlite3SelectAddTypeInfo(pParse, p);
93965 }
93966
93967 /*
93968 ** Reset the aggregate accumulator.
93969 **
93970 ** The aggregate accumulator is a set of memory cells that hold
93971 ** intermediate results while calculating an aggregate.  This
93972 ** routine simply stores NULLs in all of those memory cells.
93973 */
93974 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
93975   Vdbe *v = pParse->pVdbe;
93976   int i;
93977   struct AggInfo_func *pFunc;
93978   if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
93979     return;
93980   }
93981   for(i=0; i<pAggInfo->nColumn; i++){
93982     sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
93983   }
93984   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
93985     sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
93986     if( pFunc->iDistinct>=0 ){
93987       Expr *pE = pFunc->pExpr;
93988       assert( !ExprHasProperty(pE, EP_xIsSelect) );
93989       if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
93990         sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
93991            "argument");
93992         pFunc->iDistinct = -1;
93993       }else{
93994         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
93995         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
93996                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
93997       }
93998     }
93999   }
94000 }
94001
94002 /*
94003 ** Invoke the OP_AggFinalize opcode for every aggregate function
94004 ** in the AggInfo structure.
94005 */
94006 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
94007   Vdbe *v = pParse->pVdbe;
94008   int i;
94009   struct AggInfo_func *pF;
94010   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
94011     ExprList *pList = pF->pExpr->x.pList;
94012     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
94013     sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
94014                       (void*)pF->pFunc, P4_FUNCDEF);
94015   }
94016 }
94017
94018 /*
94019 ** Update the accumulator memory cells for an aggregate based on
94020 ** the current cursor position.
94021 */
94022 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
94023   Vdbe *v = pParse->pVdbe;
94024   int i;
94025   struct AggInfo_func *pF;
94026   struct AggInfo_col *pC;
94027
94028   pAggInfo->directMode = 1;
94029   sqlite3ExprCacheClear(pParse);
94030   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
94031     int nArg;
94032     int addrNext = 0;
94033     int regAgg;
94034     ExprList *pList = pF->pExpr->x.pList;
94035     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
94036     if( pList ){
94037       nArg = pList->nExpr;
94038       regAgg = sqlite3GetTempRange(pParse, nArg);
94039       sqlite3ExprCodeExprList(pParse, pList, regAgg, 1);
94040     }else{
94041       nArg = 0;
94042       regAgg = 0;
94043     }
94044     if( pF->iDistinct>=0 ){
94045       addrNext = sqlite3VdbeMakeLabel(v);
94046       assert( nArg==1 );
94047       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
94048     }
94049     if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
94050       CollSeq *pColl = 0;
94051       struct ExprList_item *pItem;
94052       int j;
94053       assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
94054       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
94055         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
94056       }
94057       if( !pColl ){
94058         pColl = pParse->db->pDfltColl;
94059       }
94060       sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
94061     }
94062     sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
94063                       (void*)pF->pFunc, P4_FUNCDEF);
94064     sqlite3VdbeChangeP5(v, (u8)nArg);
94065     sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
94066     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
94067     if( addrNext ){
94068       sqlite3VdbeResolveLabel(v, addrNext);
94069       sqlite3ExprCacheClear(pParse);
94070     }
94071   }
94072
94073   /* Before populating the accumulator registers, clear the column cache.
94074   ** Otherwise, if any of the required column values are already present 
94075   ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
94076   ** to pC->iMem. But by the time the value is used, the original register
94077   ** may have been used, invalidating the underlying buffer holding the
94078   ** text or blob value. See ticket [883034dcb5].
94079   **
94080   ** Another solution would be to change the OP_SCopy used to copy cached
94081   ** values to an OP_Copy.
94082   */
94083   sqlite3ExprCacheClear(pParse);
94084   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
94085     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
94086   }
94087   pAggInfo->directMode = 0;
94088   sqlite3ExprCacheClear(pParse);
94089 }
94090
94091 /*
94092 ** Add a single OP_Explain instruction to the VDBE to explain a simple
94093 ** count(*) query ("SELECT count(*) FROM pTab").
94094 */
94095 #ifndef SQLITE_OMIT_EXPLAIN
94096 static void explainSimpleCount(
94097   Parse *pParse,                  /* Parse context */
94098   Table *pTab,                    /* Table being queried */
94099   Index *pIdx                     /* Index used to optimize scan, or NULL */
94100 ){
94101   if( pParse->explain==2 ){
94102     char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s %s%s(~%d rows)",
94103         pTab->zName, 
94104         pIdx ? "USING COVERING INDEX " : "",
94105         pIdx ? pIdx->zName : "",
94106         pTab->nRowEst
94107     );
94108     sqlite3VdbeAddOp4(
94109         pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
94110     );
94111   }
94112 }
94113 #else
94114 # define explainSimpleCount(a,b,c)
94115 #endif
94116
94117 /*
94118 ** Generate code for the SELECT statement given in the p argument.  
94119 **
94120 ** The results are distributed in various ways depending on the
94121 ** contents of the SelectDest structure pointed to by argument pDest
94122 ** as follows:
94123 **
94124 **     pDest->eDest    Result
94125 **     ------------    -------------------------------------------
94126 **     SRT_Output      Generate a row of output (using the OP_ResultRow
94127 **                     opcode) for each row in the result set.
94128 **
94129 **     SRT_Mem         Only valid if the result is a single column.
94130 **                     Store the first column of the first result row
94131 **                     in register pDest->iParm then abandon the rest
94132 **                     of the query.  This destination implies "LIMIT 1".
94133 **
94134 **     SRT_Set         The result must be a single column.  Store each
94135 **                     row of result as the key in table pDest->iParm. 
94136 **                     Apply the affinity pDest->affinity before storing
94137 **                     results.  Used to implement "IN (SELECT ...)".
94138 **
94139 **     SRT_Union       Store results as a key in a temporary table pDest->iParm.
94140 **
94141 **     SRT_Except      Remove results from the temporary table pDest->iParm.
94142 **
94143 **     SRT_Table       Store results in temporary table pDest->iParm.
94144 **                     This is like SRT_EphemTab except that the table
94145 **                     is assumed to already be open.
94146 **
94147 **     SRT_EphemTab    Create an temporary table pDest->iParm and store
94148 **                     the result there. The cursor is left open after
94149 **                     returning.  This is like SRT_Table except that
94150 **                     this destination uses OP_OpenEphemeral to create
94151 **                     the table first.
94152 **
94153 **     SRT_Coroutine   Generate a co-routine that returns a new row of
94154 **                     results each time it is invoked.  The entry point
94155 **                     of the co-routine is stored in register pDest->iParm.
94156 **
94157 **     SRT_Exists      Store a 1 in memory cell pDest->iParm if the result
94158 **                     set is not empty.
94159 **
94160 **     SRT_Discard     Throw the results away.  This is used by SELECT
94161 **                     statements within triggers whose only purpose is
94162 **                     the side-effects of functions.
94163 **
94164 ** This routine returns the number of errors.  If any errors are
94165 ** encountered, then an appropriate error message is left in
94166 ** pParse->zErrMsg.
94167 **
94168 ** This routine does NOT free the Select structure passed in.  The
94169 ** calling function needs to do that.
94170 */
94171 SQLITE_PRIVATE int sqlite3Select(
94172   Parse *pParse,         /* The parser context */
94173   Select *p,             /* The SELECT statement being coded. */
94174   SelectDest *pDest      /* What to do with the query results */
94175 ){
94176   int i, j;              /* Loop counters */
94177   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
94178   Vdbe *v;               /* The virtual machine under construction */
94179   int isAgg;             /* True for select lists like "count(*)" */
94180   ExprList *pEList;      /* List of columns to extract. */
94181   SrcList *pTabList;     /* List of tables to select from */
94182   Expr *pWhere;          /* The WHERE clause.  May be NULL */
94183   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
94184   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
94185   Expr *pHaving;         /* The HAVING clause.  May be NULL */
94186   int isDistinct;        /* True if the DISTINCT keyword is present */
94187   int distinct;          /* Table to use for the distinct set */
94188   int rc = 1;            /* Value to return from this function */
94189   int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
94190   AggInfo sAggInfo;      /* Information used by aggregate queries */
94191   int iEnd;              /* Address of the end of the query */
94192   sqlite3 *db;           /* The database connection */
94193
94194 #ifndef SQLITE_OMIT_EXPLAIN
94195   int iRestoreSelectId = pParse->iSelectId;
94196   pParse->iSelectId = pParse->iNextSelectId++;
94197 #endif
94198
94199   db = pParse->db;
94200   if( p==0 || db->mallocFailed || pParse->nErr ){
94201     return 1;
94202   }
94203   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
94204   memset(&sAggInfo, 0, sizeof(sAggInfo));
94205
94206   if( IgnorableOrderby(pDest) ){
94207     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || 
94208            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
94209     /* If ORDER BY makes no difference in the output then neither does
94210     ** DISTINCT so it can be removed too. */
94211     sqlite3ExprListDelete(db, p->pOrderBy);
94212     p->pOrderBy = 0;
94213     p->selFlags &= ~SF_Distinct;
94214   }
94215   sqlite3SelectPrep(pParse, p, 0);
94216   pOrderBy = p->pOrderBy;
94217   pTabList = p->pSrc;
94218   pEList = p->pEList;
94219   if( pParse->nErr || db->mallocFailed ){
94220     goto select_end;
94221   }
94222   isAgg = (p->selFlags & SF_Aggregate)!=0;
94223   assert( pEList!=0 );
94224
94225   /* Begin generating code.
94226   */
94227   v = sqlite3GetVdbe(pParse);
94228   if( v==0 ) goto select_end;
94229
94230   /* If writing to memory or generating a set
94231   ** only a single column may be output.
94232   */
94233 #ifndef SQLITE_OMIT_SUBQUERY
94234   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
94235     goto select_end;
94236   }
94237 #endif
94238
94239   /* Generate code for all sub-queries in the FROM clause
94240   */
94241 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
94242   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
94243     struct SrcList_item *pItem = &pTabList->a[i];
94244     SelectDest dest;
94245     Select *pSub = pItem->pSelect;
94246     int isAggSub;
94247
94248     if( pSub==0 || pItem->isPopulated ) continue;
94249
94250     /* Increment Parse.nHeight by the height of the largest expression
94251     ** tree refered to by this, the parent select. The child select
94252     ** may contain expression trees of at most
94253     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
94254     ** more conservative than necessary, but much easier than enforcing
94255     ** an exact limit.
94256     */
94257     pParse->nHeight += sqlite3SelectExprHeight(p);
94258
94259     /* Check to see if the subquery can be absorbed into the parent. */
94260     isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
94261     if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
94262       if( isAggSub ){
94263         isAgg = 1;
94264         p->selFlags |= SF_Aggregate;
94265       }
94266       i = -1;
94267     }else{
94268       sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
94269       assert( pItem->isPopulated==0 );
94270       explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
94271       sqlite3Select(pParse, pSub, &dest);
94272       pItem->isPopulated = 1;
94273       pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
94274     }
94275     if( /*pParse->nErr ||*/ db->mallocFailed ){
94276       goto select_end;
94277     }
94278     pParse->nHeight -= sqlite3SelectExprHeight(p);
94279     pTabList = p->pSrc;
94280     if( !IgnorableOrderby(pDest) ){
94281       pOrderBy = p->pOrderBy;
94282     }
94283   }
94284   pEList = p->pEList;
94285 #endif
94286   pWhere = p->pWhere;
94287   pGroupBy = p->pGroupBy;
94288   pHaving = p->pHaving;
94289   isDistinct = (p->selFlags & SF_Distinct)!=0;
94290
94291 #ifndef SQLITE_OMIT_COMPOUND_SELECT
94292   /* If there is are a sequence of queries, do the earlier ones first.
94293   */
94294   if( p->pPrior ){
94295     if( p->pRightmost==0 ){
94296       Select *pLoop, *pRight = 0;
94297       int cnt = 0;
94298       int mxSelect;
94299       for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
94300         pLoop->pRightmost = p;
94301         pLoop->pNext = pRight;
94302         pRight = pLoop;
94303       }
94304       mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
94305       if( mxSelect && cnt>mxSelect ){
94306         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
94307         goto select_end;
94308       }
94309     }
94310     rc = multiSelect(pParse, p, pDest);
94311     explainSetInteger(pParse->iSelectId, iRestoreSelectId);
94312     return rc;
94313   }
94314 #endif
94315
94316   /* If possible, rewrite the query to use GROUP BY instead of DISTINCT.
94317   ** GROUP BY might use an index, DISTINCT never does.
94318   */
94319   assert( p->pGroupBy==0 || (p->selFlags & SF_Aggregate)!=0 );
94320   if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ){
94321     p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
94322     pGroupBy = p->pGroupBy;
94323     p->selFlags &= ~SF_Distinct;
94324   }
94325
94326   /* If there is both a GROUP BY and an ORDER BY clause and they are
94327   ** identical, then disable the ORDER BY clause since the GROUP BY
94328   ** will cause elements to come out in the correct order.  This is
94329   ** an optimization - the correct answer should result regardless.
94330   ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER
94331   ** to disable this optimization for testing purposes.
94332   */
94333   if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy)==0
94334          && (db->flags & SQLITE_GroupByOrder)==0 ){
94335     pOrderBy = 0;
94336   }
94337
94338   /* If there is an ORDER BY clause, then this sorting
94339   ** index might end up being unused if the data can be 
94340   ** extracted in pre-sorted order.  If that is the case, then the
94341   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
94342   ** we figure out that the sorting index is not needed.  The addrSortIndex
94343   ** variable is used to facilitate that change.
94344   */
94345   if( pOrderBy ){
94346     KeyInfo *pKeyInfo;
94347     pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
94348     pOrderBy->iECursor = pParse->nTab++;
94349     p->addrOpenEphm[2] = addrSortIndex =
94350       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
94351                            pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
94352                            (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
94353   }else{
94354     addrSortIndex = -1;
94355   }
94356
94357   /* If the output is destined for a temporary table, open that table.
94358   */
94359   if( pDest->eDest==SRT_EphemTab ){
94360     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr);
94361   }
94362
94363   /* Set the limiter.
94364   */
94365   iEnd = sqlite3VdbeMakeLabel(v);
94366   p->nSelectRow = (double)LARGEST_INT64;
94367   computeLimitRegisters(pParse, p, iEnd);
94368
94369   /* Open a virtual index to use for the distinct set.
94370   */
94371   if( p->selFlags & SF_Distinct ){
94372     KeyInfo *pKeyInfo;
94373     assert( isAgg || pGroupBy );
94374     distinct = pParse->nTab++;
94375     pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
94376     sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
94377                         (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
94378     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
94379   }else{
94380     distinct = -1;
94381   }
94382
94383   /* Aggregate and non-aggregate queries are handled differently */
94384   if( !isAgg && pGroupBy==0 ){
94385     /* This case is for non-aggregate queries
94386     ** Begin the database scan
94387     */
94388     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, 0);
94389     if( pWInfo==0 ) goto select_end;
94390     if( pWInfo->nRowOut < p->nSelectRow ) p->nSelectRow = pWInfo->nRowOut;
94391
94392     /* If sorting index that was created by a prior OP_OpenEphemeral 
94393     ** instruction ended up not being needed, then change the OP_OpenEphemeral
94394     ** into an OP_Noop.
94395     */
94396     if( addrSortIndex>=0 && pOrderBy==0 ){
94397       sqlite3VdbeChangeToNoop(v, addrSortIndex, 1);
94398       p->addrOpenEphm[2] = -1;
94399     }
94400
94401     /* Use the standard inner loop
94402     */
94403     assert(!isDistinct);
94404     selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, pDest,
94405                     pWInfo->iContinue, pWInfo->iBreak);
94406
94407     /* End the database scan loop.
94408     */
94409     sqlite3WhereEnd(pWInfo);
94410   }else{
94411     /* This is the processing for aggregate queries */
94412     NameContext sNC;    /* Name context for processing aggregate information */
94413     int iAMem;          /* First Mem address for storing current GROUP BY */
94414     int iBMem;          /* First Mem address for previous GROUP BY */
94415     int iUseFlag;       /* Mem address holding flag indicating that at least
94416                         ** one row of the input to the aggregator has been
94417                         ** processed */
94418     int iAbortFlag;     /* Mem address which causes query abort if positive */
94419     int groupBySort;    /* Rows come from source in GROUP BY order */
94420     int addrEnd;        /* End of processing for this SELECT */
94421
94422     /* Remove any and all aliases between the result set and the
94423     ** GROUP BY clause.
94424     */
94425     if( pGroupBy ){
94426       int k;                        /* Loop counter */
94427       struct ExprList_item *pItem;  /* For looping over expression in a list */
94428
94429       for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
94430         pItem->iAlias = 0;
94431       }
94432       for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
94433         pItem->iAlias = 0;
94434       }
94435       if( p->nSelectRow>(double)100 ) p->nSelectRow = (double)100;
94436     }else{
94437       p->nSelectRow = (double)1;
94438     }
94439
94440  
94441     /* Create a label to jump to when we want to abort the query */
94442     addrEnd = sqlite3VdbeMakeLabel(v);
94443
94444     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
94445     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
94446     ** SELECT statement.
94447     */
94448     memset(&sNC, 0, sizeof(sNC));
94449     sNC.pParse = pParse;
94450     sNC.pSrcList = pTabList;
94451     sNC.pAggInfo = &sAggInfo;
94452     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
94453     sAggInfo.pGroupBy = pGroupBy;
94454     sqlite3ExprAnalyzeAggList(&sNC, pEList);
94455     sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
94456     if( pHaving ){
94457       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
94458     }
94459     sAggInfo.nAccumulator = sAggInfo.nColumn;
94460     for(i=0; i<sAggInfo.nFunc; i++){
94461       assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
94462       sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
94463     }
94464     if( db->mallocFailed ) goto select_end;
94465
94466     /* Processing for aggregates with GROUP BY is very different and
94467     ** much more complex than aggregates without a GROUP BY.
94468     */
94469     if( pGroupBy ){
94470       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
94471       int j1;             /* A-vs-B comparision jump */
94472       int addrOutputRow;  /* Start of subroutine that outputs a result row */
94473       int regOutputRow;   /* Return address register for output subroutine */
94474       int addrSetAbort;   /* Set the abort flag and return */
94475       int addrTopOfLoop;  /* Top of the input loop */
94476       int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
94477       int addrReset;      /* Subroutine for resetting the accumulator */
94478       int regReset;       /* Return address register for reset subroutine */
94479
94480       /* If there is a GROUP BY clause we might need a sorting index to
94481       ** implement it.  Allocate that sorting index now.  If it turns out
94482       ** that we do not need it after all, the OpenEphemeral instruction
94483       ** will be converted into a Noop.  
94484       */
94485       sAggInfo.sortingIdx = pParse->nTab++;
94486       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
94487       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, 
94488           sAggInfo.sortingIdx, sAggInfo.nSortingColumn, 
94489           0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
94490
94491       /* Initialize memory locations used by GROUP BY aggregate processing
94492       */
94493       iUseFlag = ++pParse->nMem;
94494       iAbortFlag = ++pParse->nMem;
94495       regOutputRow = ++pParse->nMem;
94496       addrOutputRow = sqlite3VdbeMakeLabel(v);
94497       regReset = ++pParse->nMem;
94498       addrReset = sqlite3VdbeMakeLabel(v);
94499       iAMem = pParse->nMem + 1;
94500       pParse->nMem += pGroupBy->nExpr;
94501       iBMem = pParse->nMem + 1;
94502       pParse->nMem += pGroupBy->nExpr;
94503       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
94504       VdbeComment((v, "clear abort flag"));
94505       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
94506       VdbeComment((v, "indicate accumulator empty"));
94507
94508       /* Begin a loop that will extract all source rows in GROUP BY order.
94509       ** This might involve two separate loops with an OP_Sort in between, or
94510       ** it might be a single loop that uses an index to extract information
94511       ** in the right order to begin with.
94512       */
94513       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
94514       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0);
94515       if( pWInfo==0 ) goto select_end;
94516       if( pGroupBy==0 ){
94517         /* The optimizer is able to deliver rows in group by order so
94518         ** we do not have to sort.  The OP_OpenEphemeral table will be
94519         ** cancelled later because we still need to use the pKeyInfo
94520         */
94521         pGroupBy = p->pGroupBy;
94522         groupBySort = 0;
94523       }else{
94524         /* Rows are coming out in undetermined order.  We have to push
94525         ** each row into a sorting index, terminate the first loop,
94526         ** then loop over the sorting index in order to get the output
94527         ** in sorted order
94528         */
94529         int regBase;
94530         int regRecord;
94531         int nCol;
94532         int nGroupBy;
94533
94534         explainTempTable(pParse, 
94535             isDistinct && !(p->selFlags&SF_Distinct)?"DISTINCT":"GROUP BY");
94536
94537         groupBySort = 1;
94538         nGroupBy = pGroupBy->nExpr;
94539         nCol = nGroupBy + 1;
94540         j = nGroupBy+1;
94541         for(i=0; i<sAggInfo.nColumn; i++){
94542           if( sAggInfo.aCol[i].iSorterColumn>=j ){
94543             nCol++;
94544             j++;
94545           }
94546         }
94547         regBase = sqlite3GetTempRange(pParse, nCol);
94548         sqlite3ExprCacheClear(pParse);
94549         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
94550         sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
94551         j = nGroupBy+1;
94552         for(i=0; i<sAggInfo.nColumn; i++){
94553           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
94554           if( pCol->iSorterColumn>=j ){
94555             int r1 = j + regBase;
94556             int r2;
94557
94558             r2 = sqlite3ExprCodeGetColumn(pParse, 
94559                                pCol->pTab, pCol->iColumn, pCol->iTable, r1);
94560             if( r1!=r2 ){
94561               sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
94562             }
94563             j++;
94564           }
94565         }
94566         regRecord = sqlite3GetTempReg(pParse);
94567         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
94568         sqlite3VdbeAddOp2(v, OP_IdxInsert, sAggInfo.sortingIdx, regRecord);
94569         sqlite3ReleaseTempReg(pParse, regRecord);
94570         sqlite3ReleaseTempRange(pParse, regBase, nCol);
94571         sqlite3WhereEnd(pWInfo);
94572         sqlite3VdbeAddOp2(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
94573         VdbeComment((v, "GROUP BY sort"));
94574         sAggInfo.useSortingIdx = 1;
94575         sqlite3ExprCacheClear(pParse);
94576       }
94577
94578       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
94579       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
94580       ** Then compare the current GROUP BY terms against the GROUP BY terms
94581       ** from the previous row currently stored in a0, a1, a2...
94582       */
94583       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
94584       sqlite3ExprCacheClear(pParse);
94585       for(j=0; j<pGroupBy->nExpr; j++){
94586         if( groupBySort ){
94587           sqlite3VdbeAddOp3(v, OP_Column, sAggInfo.sortingIdx, j, iBMem+j);
94588         }else{
94589           sAggInfo.directMode = 1;
94590           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
94591         }
94592       }
94593       sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
94594                           (char*)pKeyInfo, P4_KEYINFO);
94595       j1 = sqlite3VdbeCurrentAddr(v);
94596       sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
94597
94598       /* Generate code that runs whenever the GROUP BY changes.
94599       ** Changes in the GROUP BY are detected by the previous code
94600       ** block.  If there were no changes, this block is skipped.
94601       **
94602       ** This code copies current group by terms in b0,b1,b2,...
94603       ** over to a0,a1,a2.  It then calls the output subroutine
94604       ** and resets the aggregate accumulator registers in preparation
94605       ** for the next GROUP BY batch.
94606       */
94607       sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
94608       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
94609       VdbeComment((v, "output one row"));
94610       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
94611       VdbeComment((v, "check abort flag"));
94612       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
94613       VdbeComment((v, "reset accumulator"));
94614
94615       /* Update the aggregate accumulators based on the content of
94616       ** the current row
94617       */
94618       sqlite3VdbeJumpHere(v, j1);
94619       updateAccumulator(pParse, &sAggInfo);
94620       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
94621       VdbeComment((v, "indicate data in accumulator"));
94622
94623       /* End of the loop
94624       */
94625       if( groupBySort ){
94626         sqlite3VdbeAddOp2(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
94627       }else{
94628         sqlite3WhereEnd(pWInfo);
94629         sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1);
94630       }
94631
94632       /* Output the final row of result
94633       */
94634       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
94635       VdbeComment((v, "output final row"));
94636
94637       /* Jump over the subroutines
94638       */
94639       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
94640
94641       /* Generate a subroutine that outputs a single row of the result
94642       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
94643       ** is less than or equal to zero, the subroutine is a no-op.  If
94644       ** the processing calls for the query to abort, this subroutine
94645       ** increments the iAbortFlag memory location before returning in
94646       ** order to signal the caller to abort.
94647       */
94648       addrSetAbort = sqlite3VdbeCurrentAddr(v);
94649       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
94650       VdbeComment((v, "set abort flag"));
94651       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
94652       sqlite3VdbeResolveLabel(v, addrOutputRow);
94653       addrOutputRow = sqlite3VdbeCurrentAddr(v);
94654       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
94655       VdbeComment((v, "Groupby result generator entry point"));
94656       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
94657       finalizeAggFunctions(pParse, &sAggInfo);
94658       sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
94659       selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
94660                       distinct, pDest,
94661                       addrOutputRow+1, addrSetAbort);
94662       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
94663       VdbeComment((v, "end groupby result generator"));
94664
94665       /* Generate a subroutine that will reset the group-by accumulator
94666       */
94667       sqlite3VdbeResolveLabel(v, addrReset);
94668       resetAccumulator(pParse, &sAggInfo);
94669       sqlite3VdbeAddOp1(v, OP_Return, regReset);
94670      
94671     } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
94672     else {
94673       ExprList *pDel = 0;
94674 #ifndef SQLITE_OMIT_BTREECOUNT
94675       Table *pTab;
94676       if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
94677         /* If isSimpleCount() returns a pointer to a Table structure, then
94678         ** the SQL statement is of the form:
94679         **
94680         **   SELECT count(*) FROM <tbl>
94681         **
94682         ** where the Table structure returned represents table <tbl>.
94683         **
94684         ** This statement is so common that it is optimized specially. The
94685         ** OP_Count instruction is executed either on the intkey table that
94686         ** contains the data for table <tbl> or on one of its indexes. It
94687         ** is better to execute the op on an index, as indexes are almost
94688         ** always spread across less pages than their corresponding tables.
94689         */
94690         const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
94691         const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
94692         Index *pIdx;                         /* Iterator variable */
94693         KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
94694         Index *pBest = 0;                    /* Best index found so far */
94695         int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
94696
94697         sqlite3CodeVerifySchema(pParse, iDb);
94698         sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
94699
94700         /* Search for the index that has the least amount of columns. If
94701         ** there is such an index, and it has less columns than the table
94702         ** does, then we can assume that it consumes less space on disk and
94703         ** will therefore be cheaper to scan to determine the query result.
94704         ** In this case set iRoot to the root page number of the index b-tree
94705         ** and pKeyInfo to the KeyInfo structure required to navigate the
94706         ** index.
94707         **
94708         ** (2011-04-15) Do not do a full scan of an unordered index.
94709         **
94710         ** In practice the KeyInfo structure will not be used. It is only 
94711         ** passed to keep OP_OpenRead happy.
94712         */
94713         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
94714           if( pIdx->bUnordered==0 && (!pBest || pIdx->nColumn<pBest->nColumn) ){
94715             pBest = pIdx;
94716           }
94717         }
94718         if( pBest && pBest->nColumn<pTab->nCol ){
94719           iRoot = pBest->tnum;
94720           pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
94721         }
94722
94723         /* Open a read-only cursor, execute the OP_Count, close the cursor. */
94724         sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
94725         if( pKeyInfo ){
94726           sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
94727         }
94728         sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
94729         sqlite3VdbeAddOp1(v, OP_Close, iCsr);
94730         explainSimpleCount(pParse, pTab, pBest);
94731       }else
94732 #endif /* SQLITE_OMIT_BTREECOUNT */
94733       {
94734         /* Check if the query is of one of the following forms:
94735         **
94736         **   SELECT min(x) FROM ...
94737         **   SELECT max(x) FROM ...
94738         **
94739         ** If it is, then ask the code in where.c to attempt to sort results
94740         ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause. 
94741         ** If where.c is able to produce results sorted in this order, then
94742         ** add vdbe code to break out of the processing loop after the 
94743         ** first iteration (since the first iteration of the loop is 
94744         ** guaranteed to operate on the row with the minimum or maximum 
94745         ** value of x, the only row required).
94746         **
94747         ** A special flag must be passed to sqlite3WhereBegin() to slightly
94748         ** modify behaviour as follows:
94749         **
94750         **   + If the query is a "SELECT min(x)", then the loop coded by
94751         **     where.c should not iterate over any values with a NULL value
94752         **     for x.
94753         **
94754         **   + The optimizer code in where.c (the thing that decides which
94755         **     index or indices to use) should place a different priority on 
94756         **     satisfying the 'ORDER BY' clause than it does in other cases.
94757         **     Refer to code and comments in where.c for details.
94758         */
94759         ExprList *pMinMax = 0;
94760         u8 flag = minMaxQuery(p);
94761         if( flag ){
94762           assert( !ExprHasProperty(p->pEList->a[0].pExpr, EP_xIsSelect) );
94763           pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->x.pList,0);
94764           pDel = pMinMax;
94765           if( pMinMax && !db->mallocFailed ){
94766             pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
94767             pMinMax->a[0].pExpr->op = TK_COLUMN;
94768           }
94769         }
94770   
94771         /* This case runs if the aggregate has no GROUP BY clause.  The
94772         ** processing is much simpler since there is only a single row
94773         ** of output.
94774         */
94775         resetAccumulator(pParse, &sAggInfo);
94776         pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, flag);
94777         if( pWInfo==0 ){
94778           sqlite3ExprListDelete(db, pDel);
94779           goto select_end;
94780         }
94781         updateAccumulator(pParse, &sAggInfo);
94782         if( !pMinMax && flag ){
94783           sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
94784           VdbeComment((v, "%s() by index",
94785                 (flag==WHERE_ORDERBY_MIN?"min":"max")));
94786         }
94787         sqlite3WhereEnd(pWInfo);
94788         finalizeAggFunctions(pParse, &sAggInfo);
94789       }
94790
94791       pOrderBy = 0;
94792       sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
94793       selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1, 
94794                       pDest, addrEnd, addrEnd);
94795       sqlite3ExprListDelete(db, pDel);
94796     }
94797     sqlite3VdbeResolveLabel(v, addrEnd);
94798     
94799   } /* endif aggregate query */
94800
94801   if( distinct>=0 ){
94802     explainTempTable(pParse, "DISTINCT");
94803   }
94804
94805   /* If there is an ORDER BY clause, then we need to sort the results
94806   ** and send them to the callback one by one.
94807   */
94808   if( pOrderBy ){
94809     explainTempTable(pParse, "ORDER BY");
94810     generateSortTail(pParse, p, v, pEList->nExpr, pDest);
94811   }
94812
94813   /* Jump here to skip this query
94814   */
94815   sqlite3VdbeResolveLabel(v, iEnd);
94816
94817   /* The SELECT was successfully coded.   Set the return code to 0
94818   ** to indicate no errors.
94819   */
94820   rc = 0;
94821
94822   /* Control jumps to here if an error is encountered above, or upon
94823   ** successful coding of the SELECT.
94824   */
94825 select_end:
94826   explainSetInteger(pParse->iSelectId, iRestoreSelectId);
94827
94828   /* Identify column names if results of the SELECT are to be output.
94829   */
94830   if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
94831     generateColumnNames(pParse, pTabList, pEList);
94832   }
94833
94834   sqlite3DbFree(db, sAggInfo.aCol);
94835   sqlite3DbFree(db, sAggInfo.aFunc);
94836   return rc;
94837 }
94838
94839 #if defined(SQLITE_DEBUG)
94840 /*
94841 *******************************************************************************
94842 ** The following code is used for testing and debugging only.  The code
94843 ** that follows does not appear in normal builds.
94844 **
94845 ** These routines are used to print out the content of all or part of a 
94846 ** parse structures such as Select or Expr.  Such printouts are useful
94847 ** for helping to understand what is happening inside the code generator
94848 ** during the execution of complex SELECT statements.
94849 **
94850 ** These routine are not called anywhere from within the normal
94851 ** code base.  Then are intended to be called from within the debugger
94852 ** or from temporary "printf" statements inserted for debugging.
94853 */
94854 SQLITE_PRIVATE void sqlite3PrintExpr(Expr *p){
94855   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
94856     sqlite3DebugPrintf("(%s", p->u.zToken);
94857   }else{
94858     sqlite3DebugPrintf("(%d", p->op);
94859   }
94860   if( p->pLeft ){
94861     sqlite3DebugPrintf(" ");
94862     sqlite3PrintExpr(p->pLeft);
94863   }
94864   if( p->pRight ){
94865     sqlite3DebugPrintf(" ");
94866     sqlite3PrintExpr(p->pRight);
94867   }
94868   sqlite3DebugPrintf(")");
94869 }
94870 SQLITE_PRIVATE void sqlite3PrintExprList(ExprList *pList){
94871   int i;
94872   for(i=0; i<pList->nExpr; i++){
94873     sqlite3PrintExpr(pList->a[i].pExpr);
94874     if( i<pList->nExpr-1 ){
94875       sqlite3DebugPrintf(", ");
94876     }
94877   }
94878 }
94879 SQLITE_PRIVATE void sqlite3PrintSelect(Select *p, int indent){
94880   sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
94881   sqlite3PrintExprList(p->pEList);
94882   sqlite3DebugPrintf("\n");
94883   if( p->pSrc ){
94884     char *zPrefix;
94885     int i;
94886     zPrefix = "FROM";
94887     for(i=0; i<p->pSrc->nSrc; i++){
94888       struct SrcList_item *pItem = &p->pSrc->a[i];
94889       sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
94890       zPrefix = "";
94891       if( pItem->pSelect ){
94892         sqlite3DebugPrintf("(\n");
94893         sqlite3PrintSelect(pItem->pSelect, indent+10);
94894         sqlite3DebugPrintf("%*s)", indent+8, "");
94895       }else if( pItem->zName ){
94896         sqlite3DebugPrintf("%s", pItem->zName);
94897       }
94898       if( pItem->pTab ){
94899         sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
94900       }
94901       if( pItem->zAlias ){
94902         sqlite3DebugPrintf(" AS %s", pItem->zAlias);
94903       }
94904       if( i<p->pSrc->nSrc-1 ){
94905         sqlite3DebugPrintf(",");
94906       }
94907       sqlite3DebugPrintf("\n");
94908     }
94909   }
94910   if( p->pWhere ){
94911     sqlite3DebugPrintf("%*s WHERE ", indent, "");
94912     sqlite3PrintExpr(p->pWhere);
94913     sqlite3DebugPrintf("\n");
94914   }
94915   if( p->pGroupBy ){
94916     sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
94917     sqlite3PrintExprList(p->pGroupBy);
94918     sqlite3DebugPrintf("\n");
94919   }
94920   if( p->pHaving ){
94921     sqlite3DebugPrintf("%*s HAVING ", indent, "");
94922     sqlite3PrintExpr(p->pHaving);
94923     sqlite3DebugPrintf("\n");
94924   }
94925   if( p->pOrderBy ){
94926     sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
94927     sqlite3PrintExprList(p->pOrderBy);
94928     sqlite3DebugPrintf("\n");
94929   }
94930 }
94931 /* End of the structure debug printing code
94932 *****************************************************************************/
94933 #endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
94934
94935 /************** End of select.c **********************************************/
94936 /************** Begin file table.c *******************************************/
94937 /*
94938 ** 2001 September 15
94939 **
94940 ** The author disclaims copyright to this source code.  In place of
94941 ** a legal notice, here is a blessing:
94942 **
94943 **    May you do good and not evil.
94944 **    May you find forgiveness for yourself and forgive others.
94945 **    May you share freely, never taking more than you give.
94946 **
94947 *************************************************************************
94948 ** This file contains the sqlite3_get_table() and sqlite3_free_table()
94949 ** interface routines.  These are just wrappers around the main
94950 ** interface routine of sqlite3_exec().
94951 **
94952 ** These routines are in a separate files so that they will not be linked
94953 ** if they are not used.
94954 */
94955
94956 #ifndef SQLITE_OMIT_GET_TABLE
94957
94958 /*
94959 ** This structure is used to pass data from sqlite3_get_table() through
94960 ** to the callback function is uses to build the result.
94961 */
94962 typedef struct TabResult {
94963   char **azResult;   /* Accumulated output */
94964   char *zErrMsg;     /* Error message text, if an error occurs */
94965   int nAlloc;        /* Slots allocated for azResult[] */
94966   int nRow;          /* Number of rows in the result */
94967   int nColumn;       /* Number of columns in the result */
94968   int nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
94969   int rc;            /* Return code from sqlite3_exec() */
94970 } TabResult;
94971
94972 /*
94973 ** This routine is called once for each row in the result table.  Its job
94974 ** is to fill in the TabResult structure appropriately, allocating new
94975 ** memory as necessary.
94976 */
94977 static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
94978   TabResult *p = (TabResult*)pArg;  /* Result accumulator */
94979   int need;                         /* Slots needed in p->azResult[] */
94980   int i;                            /* Loop counter */
94981   char *z;                          /* A single column of result */
94982
94983   /* Make sure there is enough space in p->azResult to hold everything
94984   ** we need to remember from this invocation of the callback.
94985   */
94986   if( p->nRow==0 && argv!=0 ){
94987     need = nCol*2;
94988   }else{
94989     need = nCol;
94990   }
94991   if( p->nData + need > p->nAlloc ){
94992     char **azNew;
94993     p->nAlloc = p->nAlloc*2 + need;
94994     azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
94995     if( azNew==0 ) goto malloc_failed;
94996     p->azResult = azNew;
94997   }
94998
94999   /* If this is the first row, then generate an extra row containing
95000   ** the names of all columns.
95001   */
95002   if( p->nRow==0 ){
95003     p->nColumn = nCol;
95004     for(i=0; i<nCol; i++){
95005       z = sqlite3_mprintf("%s", colv[i]);
95006       if( z==0 ) goto malloc_failed;
95007       p->azResult[p->nData++] = z;
95008     }
95009   }else if( p->nColumn!=nCol ){
95010     sqlite3_free(p->zErrMsg);
95011     p->zErrMsg = sqlite3_mprintf(
95012        "sqlite3_get_table() called with two or more incompatible queries"
95013     );
95014     p->rc = SQLITE_ERROR;
95015     return 1;
95016   }
95017
95018   /* Copy over the row data
95019   */
95020   if( argv!=0 ){
95021     for(i=0; i<nCol; i++){
95022       if( argv[i]==0 ){
95023         z = 0;
95024       }else{
95025         int n = sqlite3Strlen30(argv[i])+1;
95026         z = sqlite3_malloc( n );
95027         if( z==0 ) goto malloc_failed;
95028         memcpy(z, argv[i], n);
95029       }
95030       p->azResult[p->nData++] = z;
95031     }
95032     p->nRow++;
95033   }
95034   return 0;
95035
95036 malloc_failed:
95037   p->rc = SQLITE_NOMEM;
95038   return 1;
95039 }
95040
95041 /*
95042 ** Query the database.  But instead of invoking a callback for each row,
95043 ** malloc() for space to hold the result and return the entire results
95044 ** at the conclusion of the call.
95045 **
95046 ** The result that is written to ***pazResult is held in memory obtained
95047 ** from malloc().  But the caller cannot free this memory directly.  
95048 ** Instead, the entire table should be passed to sqlite3_free_table() when
95049 ** the calling procedure is finished using it.
95050 */
95051 SQLITE_API int sqlite3_get_table(
95052   sqlite3 *db,                /* The database on which the SQL executes */
95053   const char *zSql,           /* The SQL to be executed */
95054   char ***pazResult,          /* Write the result table here */
95055   int *pnRow,                 /* Write the number of rows in the result here */
95056   int *pnColumn,              /* Write the number of columns of result here */
95057   char **pzErrMsg             /* Write error messages here */
95058 ){
95059   int rc;
95060   TabResult res;
95061
95062   *pazResult = 0;
95063   if( pnColumn ) *pnColumn = 0;
95064   if( pnRow ) *pnRow = 0;
95065   if( pzErrMsg ) *pzErrMsg = 0;
95066   res.zErrMsg = 0;
95067   res.nRow = 0;
95068   res.nColumn = 0;
95069   res.nData = 1;
95070   res.nAlloc = 20;
95071   res.rc = SQLITE_OK;
95072   res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
95073   if( res.azResult==0 ){
95074      db->errCode = SQLITE_NOMEM;
95075      return SQLITE_NOMEM;
95076   }
95077   res.azResult[0] = 0;
95078   rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
95079   assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
95080   res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
95081   if( (rc&0xff)==SQLITE_ABORT ){
95082     sqlite3_free_table(&res.azResult[1]);
95083     if( res.zErrMsg ){
95084       if( pzErrMsg ){
95085         sqlite3_free(*pzErrMsg);
95086         *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
95087       }
95088       sqlite3_free(res.zErrMsg);
95089     }
95090     db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
95091     return res.rc;
95092   }
95093   sqlite3_free(res.zErrMsg);
95094   if( rc!=SQLITE_OK ){
95095     sqlite3_free_table(&res.azResult[1]);
95096     return rc;
95097   }
95098   if( res.nAlloc>res.nData ){
95099     char **azNew;
95100     azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
95101     if( azNew==0 ){
95102       sqlite3_free_table(&res.azResult[1]);
95103       db->errCode = SQLITE_NOMEM;
95104       return SQLITE_NOMEM;
95105     }
95106     res.azResult = azNew;
95107   }
95108   *pazResult = &res.azResult[1];
95109   if( pnColumn ) *pnColumn = res.nColumn;
95110   if( pnRow ) *pnRow = res.nRow;
95111   return rc;
95112 }
95113
95114 /*
95115 ** This routine frees the space the sqlite3_get_table() malloced.
95116 */
95117 SQLITE_API void sqlite3_free_table(
95118   char **azResult            /* Result returned from from sqlite3_get_table() */
95119 ){
95120   if( azResult ){
95121     int i, n;
95122     azResult--;
95123     assert( azResult!=0 );
95124     n = SQLITE_PTR_TO_INT(azResult[0]);
95125     for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
95126     sqlite3_free(azResult);
95127   }
95128 }
95129
95130 #endif /* SQLITE_OMIT_GET_TABLE */
95131
95132 /************** End of table.c ***********************************************/
95133 /************** Begin file trigger.c *****************************************/
95134 /*
95135 **
95136 ** The author disclaims copyright to this source code.  In place of
95137 ** a legal notice, here is a blessing:
95138 **
95139 **    May you do good and not evil.
95140 **    May you find forgiveness for yourself and forgive others.
95141 **    May you share freely, never taking more than you give.
95142 **
95143 *************************************************************************
95144 ** This file contains the implementation for TRIGGERs
95145 */
95146
95147 #ifndef SQLITE_OMIT_TRIGGER
95148 /*
95149 ** Delete a linked list of TriggerStep structures.
95150 */
95151 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
95152   while( pTriggerStep ){
95153     TriggerStep * pTmp = pTriggerStep;
95154     pTriggerStep = pTriggerStep->pNext;
95155
95156     sqlite3ExprDelete(db, pTmp->pWhere);
95157     sqlite3ExprListDelete(db, pTmp->pExprList);
95158     sqlite3SelectDelete(db, pTmp->pSelect);
95159     sqlite3IdListDelete(db, pTmp->pIdList);
95160
95161     sqlite3DbFree(db, pTmp);
95162   }
95163 }
95164
95165 /*
95166 ** Given table pTab, return a list of all the triggers attached to 
95167 ** the table. The list is connected by Trigger.pNext pointers.
95168 **
95169 ** All of the triggers on pTab that are in the same database as pTab
95170 ** are already attached to pTab->pTrigger.  But there might be additional
95171 ** triggers on pTab in the TEMP schema.  This routine prepends all
95172 ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
95173 ** and returns the combined list.
95174 **
95175 ** To state it another way:  This routine returns a list of all triggers
95176 ** that fire off of pTab.  The list will include any TEMP triggers on
95177 ** pTab as well as the triggers lised in pTab->pTrigger.
95178 */
95179 SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
95180   Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
95181   Trigger *pList = 0;                  /* List of triggers to return */
95182
95183   if( pParse->disableTriggers ){
95184     return 0;
95185   }
95186
95187   if( pTmpSchema!=pTab->pSchema ){
95188     HashElem *p;
95189     assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
95190     for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
95191       Trigger *pTrig = (Trigger *)sqliteHashData(p);
95192       if( pTrig->pTabSchema==pTab->pSchema
95193        && 0==sqlite3StrICmp(pTrig->table, pTab->zName) 
95194       ){
95195         pTrig->pNext = (pList ? pList : pTab->pTrigger);
95196         pList = pTrig;
95197       }
95198     }
95199   }
95200
95201   return (pList ? pList : pTab->pTrigger);
95202 }
95203
95204 /*
95205 ** This is called by the parser when it sees a CREATE TRIGGER statement
95206 ** up to the point of the BEGIN before the trigger actions.  A Trigger
95207 ** structure is generated based on the information available and stored
95208 ** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
95209 ** sqlite3FinishTrigger() function is called to complete the trigger
95210 ** construction process.
95211 */
95212 SQLITE_PRIVATE void sqlite3BeginTrigger(
95213   Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
95214   Token *pName1,      /* The name of the trigger */
95215   Token *pName2,      /* The name of the trigger */
95216   int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
95217   int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
95218   IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
95219   SrcList *pTableName,/* The name of the table/view the trigger applies to */
95220   Expr *pWhen,        /* WHEN clause */
95221   int isTemp,         /* True if the TEMPORARY keyword is present */
95222   int noErr           /* Suppress errors if the trigger already exists */
95223 ){
95224   Trigger *pTrigger = 0;  /* The new trigger */
95225   Table *pTab;            /* Table that the trigger fires off of */
95226   char *zName = 0;        /* Name of the trigger */
95227   sqlite3 *db = pParse->db;  /* The database connection */
95228   int iDb;                /* The database to store the trigger in */
95229   Token *pName;           /* The unqualified db name */
95230   DbFixer sFix;           /* State vector for the DB fixer */
95231   int iTabDb;             /* Index of the database holding pTab */
95232
95233   assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
95234   assert( pName2!=0 );
95235   assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
95236   assert( op>0 && op<0xff );
95237   if( isTemp ){
95238     /* If TEMP was specified, then the trigger name may not be qualified. */
95239     if( pName2->n>0 ){
95240       sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
95241       goto trigger_cleanup;
95242     }
95243     iDb = 1;
95244     pName = pName1;
95245   }else{
95246     /* Figure out the db that the the trigger will be created in */
95247     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
95248     if( iDb<0 ){
95249       goto trigger_cleanup;
95250     }
95251   }
95252
95253   /* If the trigger name was unqualified, and the table is a temp table,
95254   ** then set iDb to 1 to create the trigger in the temporary database.
95255   ** If sqlite3SrcListLookup() returns 0, indicating the table does not
95256   ** exist, the error is caught by the block below.
95257   */
95258   if( !pTableName || db->mallocFailed ){
95259     goto trigger_cleanup;
95260   }
95261   pTab = sqlite3SrcListLookup(pParse, pTableName);
95262   if( db->init.busy==0 && pName2->n==0 && pTab
95263         && pTab->pSchema==db->aDb[1].pSchema ){
95264     iDb = 1;
95265   }
95266
95267   /* Ensure the table name matches database name and that the table exists */
95268   if( db->mallocFailed ) goto trigger_cleanup;
95269   assert( pTableName->nSrc==1 );
95270   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) && 
95271       sqlite3FixSrcList(&sFix, pTableName) ){
95272     goto trigger_cleanup;
95273   }
95274   pTab = sqlite3SrcListLookup(pParse, pTableName);
95275   if( !pTab ){
95276     /* The table does not exist. */
95277     if( db->init.iDb==1 ){
95278       /* Ticket #3810.
95279       ** Normally, whenever a table is dropped, all associated triggers are
95280       ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
95281       ** and the table is dropped by a different database connection, the
95282       ** trigger is not visible to the database connection that does the
95283       ** drop so the trigger cannot be dropped.  This results in an
95284       ** "orphaned trigger" - a trigger whose associated table is missing.
95285       */
95286       db->init.orphanTrigger = 1;
95287     }
95288     goto trigger_cleanup;
95289   }
95290   if( IsVirtual(pTab) ){
95291     sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
95292     goto trigger_cleanup;
95293   }
95294
95295   /* Check that the trigger name is not reserved and that no trigger of the
95296   ** specified name exists */
95297   zName = sqlite3NameFromToken(db, pName);
95298   if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
95299     goto trigger_cleanup;
95300   }
95301   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
95302   if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
95303                       zName, sqlite3Strlen30(zName)) ){
95304     if( !noErr ){
95305       sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
95306     }else{
95307       assert( !db->init.busy );
95308       sqlite3CodeVerifySchema(pParse, iDb);
95309     }
95310     goto trigger_cleanup;
95311   }
95312
95313   /* Do not create a trigger on a system table */
95314   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
95315     sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
95316     pParse->nErr++;
95317     goto trigger_cleanup;
95318   }
95319
95320   /* INSTEAD of triggers are only for views and views only support INSTEAD
95321   ** of triggers.
95322   */
95323   if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
95324     sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S", 
95325         (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
95326     goto trigger_cleanup;
95327   }
95328   if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
95329     sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
95330         " trigger on table: %S", pTableName, 0);
95331     goto trigger_cleanup;
95332   }
95333   iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
95334
95335 #ifndef SQLITE_OMIT_AUTHORIZATION
95336   {
95337     int code = SQLITE_CREATE_TRIGGER;
95338     const char *zDb = db->aDb[iTabDb].zName;
95339     const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
95340     if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
95341     if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
95342       goto trigger_cleanup;
95343     }
95344     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
95345       goto trigger_cleanup;
95346     }
95347   }
95348 #endif
95349
95350   /* INSTEAD OF triggers can only appear on views and BEFORE triggers
95351   ** cannot appear on views.  So we might as well translate every
95352   ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
95353   ** elsewhere.
95354   */
95355   if (tr_tm == TK_INSTEAD){
95356     tr_tm = TK_BEFORE;
95357   }
95358
95359   /* Build the Trigger object */
95360   pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
95361   if( pTrigger==0 ) goto trigger_cleanup;
95362   pTrigger->zName = zName;
95363   zName = 0;
95364   pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
95365   pTrigger->pSchema = db->aDb[iDb].pSchema;
95366   pTrigger->pTabSchema = pTab->pSchema;
95367   pTrigger->op = (u8)op;
95368   pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
95369   pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
95370   pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
95371   assert( pParse->pNewTrigger==0 );
95372   pParse->pNewTrigger = pTrigger;
95373
95374 trigger_cleanup:
95375   sqlite3DbFree(db, zName);
95376   sqlite3SrcListDelete(db, pTableName);
95377   sqlite3IdListDelete(db, pColumns);
95378   sqlite3ExprDelete(db, pWhen);
95379   if( !pParse->pNewTrigger ){
95380     sqlite3DeleteTrigger(db, pTrigger);
95381   }else{
95382     assert( pParse->pNewTrigger==pTrigger );
95383   }
95384 }
95385
95386 /*
95387 ** This routine is called after all of the trigger actions have been parsed
95388 ** in order to complete the process of building the trigger.
95389 */
95390 SQLITE_PRIVATE void sqlite3FinishTrigger(
95391   Parse *pParse,          /* Parser context */
95392   TriggerStep *pStepList, /* The triggered program */
95393   Token *pAll             /* Token that describes the complete CREATE TRIGGER */
95394 ){
95395   Trigger *pTrig = pParse->pNewTrigger;   /* Trigger being finished */
95396   char *zName;                            /* Name of trigger */
95397   sqlite3 *db = pParse->db;               /* The database */
95398   DbFixer sFix;                           /* Fixer object */
95399   int iDb;                                /* Database containing the trigger */
95400   Token nameToken;                        /* Trigger name for error reporting */
95401
95402   pParse->pNewTrigger = 0;
95403   if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
95404   zName = pTrig->zName;
95405   iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
95406   pTrig->step_list = pStepList;
95407   while( pStepList ){
95408     pStepList->pTrig = pTrig;
95409     pStepList = pStepList->pNext;
95410   }
95411   nameToken.z = pTrig->zName;
95412   nameToken.n = sqlite3Strlen30(nameToken.z);
95413   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken) 
95414           && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
95415     goto triggerfinish_cleanup;
95416   }
95417
95418   /* if we are not initializing,
95419   ** build the sqlite_master entry
95420   */
95421   if( !db->init.busy ){
95422     Vdbe *v;
95423     char *z;
95424
95425     /* Make an entry in the sqlite_master table */
95426     v = sqlite3GetVdbe(pParse);
95427     if( v==0 ) goto triggerfinish_cleanup;
95428     sqlite3BeginWriteOperation(pParse, 0, iDb);
95429     z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
95430     sqlite3NestedParse(pParse,
95431        "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
95432        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
95433        pTrig->table, z);
95434     sqlite3DbFree(db, z);
95435     sqlite3ChangeCookie(pParse, iDb);
95436     sqlite3VdbeAddParseSchemaOp(v, iDb,
95437         sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
95438   }
95439
95440   if( db->init.busy ){
95441     Trigger *pLink = pTrig;
95442     Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
95443     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
95444     pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
95445     if( pTrig ){
95446       db->mallocFailed = 1;
95447     }else if( pLink->pSchema==pLink->pTabSchema ){
95448       Table *pTab;
95449       int n = sqlite3Strlen30(pLink->table);
95450       pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
95451       assert( pTab!=0 );
95452       pLink->pNext = pTab->pTrigger;
95453       pTab->pTrigger = pLink;
95454     }
95455   }
95456
95457 triggerfinish_cleanup:
95458   sqlite3DeleteTrigger(db, pTrig);
95459   assert( !pParse->pNewTrigger );
95460   sqlite3DeleteTriggerStep(db, pStepList);
95461 }
95462
95463 /*
95464 ** Turn a SELECT statement (that the pSelect parameter points to) into
95465 ** a trigger step.  Return a pointer to a TriggerStep structure.
95466 **
95467 ** The parser calls this routine when it finds a SELECT statement in
95468 ** body of a TRIGGER.  
95469 */
95470 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
95471   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
95472   if( pTriggerStep==0 ) {
95473     sqlite3SelectDelete(db, pSelect);
95474     return 0;
95475   }
95476   pTriggerStep->op = TK_SELECT;
95477   pTriggerStep->pSelect = pSelect;
95478   pTriggerStep->orconf = OE_Default;
95479   return pTriggerStep;
95480 }
95481
95482 /*
95483 ** Allocate space to hold a new trigger step.  The allocated space
95484 ** holds both the TriggerStep object and the TriggerStep.target.z string.
95485 **
95486 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
95487 */
95488 static TriggerStep *triggerStepAllocate(
95489   sqlite3 *db,                /* Database connection */
95490   u8 op,                      /* Trigger opcode */
95491   Token *pName                /* The target name */
95492 ){
95493   TriggerStep *pTriggerStep;
95494
95495   pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
95496   if( pTriggerStep ){
95497     char *z = (char*)&pTriggerStep[1];
95498     memcpy(z, pName->z, pName->n);
95499     pTriggerStep->target.z = z;
95500     pTriggerStep->target.n = pName->n;
95501     pTriggerStep->op = op;
95502   }
95503   return pTriggerStep;
95504 }
95505
95506 /*
95507 ** Build a trigger step out of an INSERT statement.  Return a pointer
95508 ** to the new trigger step.
95509 **
95510 ** The parser calls this routine when it sees an INSERT inside the
95511 ** body of a trigger.
95512 */
95513 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
95514   sqlite3 *db,        /* The database connection */
95515   Token *pTableName,  /* Name of the table into which we insert */
95516   IdList *pColumn,    /* List of columns in pTableName to insert into */
95517   ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
95518   Select *pSelect,    /* A SELECT statement that supplies values */
95519   u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
95520 ){
95521   TriggerStep *pTriggerStep;
95522
95523   assert(pEList == 0 || pSelect == 0);
95524   assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
95525
95526   pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
95527   if( pTriggerStep ){
95528     pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
95529     pTriggerStep->pIdList = pColumn;
95530     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
95531     pTriggerStep->orconf = orconf;
95532   }else{
95533     sqlite3IdListDelete(db, pColumn);
95534   }
95535   sqlite3ExprListDelete(db, pEList);
95536   sqlite3SelectDelete(db, pSelect);
95537
95538   return pTriggerStep;
95539 }
95540
95541 /*
95542 ** Construct a trigger step that implements an UPDATE statement and return
95543 ** a pointer to that trigger step.  The parser calls this routine when it
95544 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
95545 */
95546 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
95547   sqlite3 *db,         /* The database connection */
95548   Token *pTableName,   /* Name of the table to be updated */
95549   ExprList *pEList,    /* The SET clause: list of column and new values */
95550   Expr *pWhere,        /* The WHERE clause */
95551   u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
95552 ){
95553   TriggerStep *pTriggerStep;
95554
95555   pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
95556   if( pTriggerStep ){
95557     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
95558     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
95559     pTriggerStep->orconf = orconf;
95560   }
95561   sqlite3ExprListDelete(db, pEList);
95562   sqlite3ExprDelete(db, pWhere);
95563   return pTriggerStep;
95564 }
95565
95566 /*
95567 ** Construct a trigger step that implements a DELETE statement and return
95568 ** a pointer to that trigger step.  The parser calls this routine when it
95569 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
95570 */
95571 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
95572   sqlite3 *db,            /* Database connection */
95573   Token *pTableName,      /* The table from which rows are deleted */
95574   Expr *pWhere            /* The WHERE clause */
95575 ){
95576   TriggerStep *pTriggerStep;
95577
95578   pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
95579   if( pTriggerStep ){
95580     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
95581     pTriggerStep->orconf = OE_Default;
95582   }
95583   sqlite3ExprDelete(db, pWhere);
95584   return pTriggerStep;
95585 }
95586
95587 /* 
95588 ** Recursively delete a Trigger structure
95589 */
95590 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
95591   if( pTrigger==0 ) return;
95592   sqlite3DeleteTriggerStep(db, pTrigger->step_list);
95593   sqlite3DbFree(db, pTrigger->zName);
95594   sqlite3DbFree(db, pTrigger->table);
95595   sqlite3ExprDelete(db, pTrigger->pWhen);
95596   sqlite3IdListDelete(db, pTrigger->pColumns);
95597   sqlite3DbFree(db, pTrigger);
95598 }
95599
95600 /*
95601 ** This function is called to drop a trigger from the database schema. 
95602 **
95603 ** This may be called directly from the parser and therefore identifies
95604 ** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
95605 ** same job as this routine except it takes a pointer to the trigger
95606 ** instead of the trigger name.
95607 **/
95608 SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
95609   Trigger *pTrigger = 0;
95610   int i;
95611   const char *zDb;
95612   const char *zName;
95613   int nName;
95614   sqlite3 *db = pParse->db;
95615
95616   if( db->mallocFailed ) goto drop_trigger_cleanup;
95617   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
95618     goto drop_trigger_cleanup;
95619   }
95620
95621   assert( pName->nSrc==1 );
95622   zDb = pName->a[0].zDatabase;
95623   zName = pName->a[0].zName;
95624   nName = sqlite3Strlen30(zName);
95625   assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
95626   for(i=OMIT_TEMPDB; i<db->nDb; i++){
95627     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
95628     if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
95629     assert( sqlite3SchemaMutexHeld(db, j, 0) );
95630     pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
95631     if( pTrigger ) break;
95632   }
95633   if( !pTrigger ){
95634     if( !noErr ){
95635       sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
95636     }else{
95637       sqlite3CodeVerifyNamedSchema(pParse, zDb);
95638     }
95639     pParse->checkSchema = 1;
95640     goto drop_trigger_cleanup;
95641   }
95642   sqlite3DropTriggerPtr(pParse, pTrigger);
95643
95644 drop_trigger_cleanup:
95645   sqlite3SrcListDelete(db, pName);
95646 }
95647
95648 /*
95649 ** Return a pointer to the Table structure for the table that a trigger
95650 ** is set on.
95651 */
95652 static Table *tableOfTrigger(Trigger *pTrigger){
95653   int n = sqlite3Strlen30(pTrigger->table);
95654   return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
95655 }
95656
95657
95658 /*
95659 ** Drop a trigger given a pointer to that trigger. 
95660 */
95661 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
95662   Table   *pTable;
95663   Vdbe *v;
95664   sqlite3 *db = pParse->db;
95665   int iDb;
95666
95667   iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
95668   assert( iDb>=0 && iDb<db->nDb );
95669   pTable = tableOfTrigger(pTrigger);
95670   assert( pTable );
95671   assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
95672 #ifndef SQLITE_OMIT_AUTHORIZATION
95673   {
95674     int code = SQLITE_DROP_TRIGGER;
95675     const char *zDb = db->aDb[iDb].zName;
95676     const char *zTab = SCHEMA_TABLE(iDb);
95677     if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
95678     if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
95679       sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
95680       return;
95681     }
95682   }
95683 #endif
95684
95685   /* Generate code to destroy the database record of the trigger.
95686   */
95687   assert( pTable!=0 );
95688   if( (v = sqlite3GetVdbe(pParse))!=0 ){
95689     int base;
95690     static const VdbeOpList dropTrigger[] = {
95691       { OP_Rewind,     0, ADDR(9),  0},
95692       { OP_String8,    0, 1,        0}, /* 1 */
95693       { OP_Column,     0, 1,        2},
95694       { OP_Ne,         2, ADDR(8),  1},
95695       { OP_String8,    0, 1,        0}, /* 4: "trigger" */
95696       { OP_Column,     0, 0,        2},
95697       { OP_Ne,         2, ADDR(8),  1},
95698       { OP_Delete,     0, 0,        0},
95699       { OP_Next,       0, ADDR(1),  0}, /* 8 */
95700     };
95701
95702     sqlite3BeginWriteOperation(pParse, 0, iDb);
95703     sqlite3OpenMasterTable(pParse, iDb);
95704     base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
95705     sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
95706     sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
95707     sqlite3ChangeCookie(pParse, iDb);
95708     sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
95709     sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
95710     if( pParse->nMem<3 ){
95711       pParse->nMem = 3;
95712     }
95713   }
95714 }
95715
95716 /*
95717 ** Remove a trigger from the hash tables of the sqlite* pointer.
95718 */
95719 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
95720   Trigger *pTrigger;
95721   Hash *pHash;
95722
95723   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
95724   pHash = &(db->aDb[iDb].pSchema->trigHash);
95725   pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
95726   if( ALWAYS(pTrigger) ){
95727     if( pTrigger->pSchema==pTrigger->pTabSchema ){
95728       Table *pTab = tableOfTrigger(pTrigger);
95729       Trigger **pp;
95730       for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
95731       *pp = (*pp)->pNext;
95732     }
95733     sqlite3DeleteTrigger(db, pTrigger);
95734     db->flags |= SQLITE_InternChanges;
95735   }
95736 }
95737
95738 /*
95739 ** pEList is the SET clause of an UPDATE statement.  Each entry
95740 ** in pEList is of the format <id>=<expr>.  If any of the entries
95741 ** in pEList have an <id> which matches an identifier in pIdList,
95742 ** then return TRUE.  If pIdList==NULL, then it is considered a
95743 ** wildcard that matches anything.  Likewise if pEList==NULL then
95744 ** it matches anything so always return true.  Return false only
95745 ** if there is no match.
95746 */
95747 static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
95748   int e;
95749   if( pIdList==0 || NEVER(pEList==0) ) return 1;
95750   for(e=0; e<pEList->nExpr; e++){
95751     if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
95752   }
95753   return 0; 
95754 }
95755
95756 /*
95757 ** Return a list of all triggers on table pTab if there exists at least
95758 ** one trigger that must be fired when an operation of type 'op' is 
95759 ** performed on the table, and, if that operation is an UPDATE, if at
95760 ** least one of the columns in pChanges is being modified.
95761 */
95762 SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
95763   Parse *pParse,          /* Parse context */
95764   Table *pTab,            /* The table the contains the triggers */
95765   int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
95766   ExprList *pChanges,     /* Columns that change in an UPDATE statement */
95767   int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
95768 ){
95769   int mask = 0;
95770   Trigger *pList = 0;
95771   Trigger *p;
95772
95773   if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
95774     pList = sqlite3TriggerList(pParse, pTab);
95775   }
95776   assert( pList==0 || IsVirtual(pTab)==0 );
95777   for(p=pList; p; p=p->pNext){
95778     if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
95779       mask |= p->tr_tm;
95780     }
95781   }
95782   if( pMask ){
95783     *pMask = mask;
95784   }
95785   return (mask ? pList : 0);
95786 }
95787
95788 /*
95789 ** Convert the pStep->target token into a SrcList and return a pointer
95790 ** to that SrcList.
95791 **
95792 ** This routine adds a specific database name, if needed, to the target when
95793 ** forming the SrcList.  This prevents a trigger in one database from
95794 ** referring to a target in another database.  An exception is when the
95795 ** trigger is in TEMP in which case it can refer to any other database it
95796 ** wants.
95797 */
95798 static SrcList *targetSrcList(
95799   Parse *pParse,       /* The parsing context */
95800   TriggerStep *pStep   /* The trigger containing the target token */
95801 ){
95802   int iDb;             /* Index of the database to use */
95803   SrcList *pSrc;       /* SrcList to be returned */
95804
95805   pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
95806   if( pSrc ){
95807     assert( pSrc->nSrc>0 );
95808     assert( pSrc->a!=0 );
95809     iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
95810     if( iDb==0 || iDb>=2 ){
95811       sqlite3 *db = pParse->db;
95812       assert( iDb<pParse->db->nDb );
95813       pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
95814     }
95815   }
95816   return pSrc;
95817 }
95818
95819 /*
95820 ** Generate VDBE code for the statements inside the body of a single 
95821 ** trigger.
95822 */
95823 static int codeTriggerProgram(
95824   Parse *pParse,            /* The parser context */
95825   TriggerStep *pStepList,   /* List of statements inside the trigger body */
95826   int orconf                /* Conflict algorithm. (OE_Abort, etc) */  
95827 ){
95828   TriggerStep *pStep;
95829   Vdbe *v = pParse->pVdbe;
95830   sqlite3 *db = pParse->db;
95831
95832   assert( pParse->pTriggerTab && pParse->pToplevel );
95833   assert( pStepList );
95834   assert( v!=0 );
95835   for(pStep=pStepList; pStep; pStep=pStep->pNext){
95836     /* Figure out the ON CONFLICT policy that will be used for this step
95837     ** of the trigger program. If the statement that caused this trigger
95838     ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
95839     ** the ON CONFLICT policy that was specified as part of the trigger
95840     ** step statement. Example:
95841     **
95842     **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
95843     **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
95844     **   END;
95845     **
95846     **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
95847     **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
95848     */
95849     pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
95850
95851     switch( pStep->op ){
95852       case TK_UPDATE: {
95853         sqlite3Update(pParse, 
95854           targetSrcList(pParse, pStep),
95855           sqlite3ExprListDup(db, pStep->pExprList, 0), 
95856           sqlite3ExprDup(db, pStep->pWhere, 0), 
95857           pParse->eOrconf
95858         );
95859         break;
95860       }
95861       case TK_INSERT: {
95862         sqlite3Insert(pParse, 
95863           targetSrcList(pParse, pStep),
95864           sqlite3ExprListDup(db, pStep->pExprList, 0), 
95865           sqlite3SelectDup(db, pStep->pSelect, 0), 
95866           sqlite3IdListDup(db, pStep->pIdList), 
95867           pParse->eOrconf
95868         );
95869         break;
95870       }
95871       case TK_DELETE: {
95872         sqlite3DeleteFrom(pParse, 
95873           targetSrcList(pParse, pStep),
95874           sqlite3ExprDup(db, pStep->pWhere, 0)
95875         );
95876         break;
95877       }
95878       default: assert( pStep->op==TK_SELECT ); {
95879         SelectDest sDest;
95880         Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
95881         sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
95882         sqlite3Select(pParse, pSelect, &sDest);
95883         sqlite3SelectDelete(db, pSelect);
95884         break;
95885       }
95886     } 
95887     if( pStep->op!=TK_SELECT ){
95888       sqlite3VdbeAddOp0(v, OP_ResetCount);
95889     }
95890   }
95891
95892   return 0;
95893 }
95894
95895 #ifdef SQLITE_DEBUG
95896 /*
95897 ** This function is used to add VdbeComment() annotations to a VDBE
95898 ** program. It is not used in production code, only for debugging.
95899 */
95900 static const char *onErrorText(int onError){
95901   switch( onError ){
95902     case OE_Abort:    return "abort";
95903     case OE_Rollback: return "rollback";
95904     case OE_Fail:     return "fail";
95905     case OE_Replace:  return "replace";
95906     case OE_Ignore:   return "ignore";
95907     case OE_Default:  return "default";
95908   }
95909   return "n/a";
95910 }
95911 #endif
95912
95913 /*
95914 ** Parse context structure pFrom has just been used to create a sub-vdbe
95915 ** (trigger program). If an error has occurred, transfer error information
95916 ** from pFrom to pTo.
95917 */
95918 static void transferParseError(Parse *pTo, Parse *pFrom){
95919   assert( pFrom->zErrMsg==0 || pFrom->nErr );
95920   assert( pTo->zErrMsg==0 || pTo->nErr );
95921   if( pTo->nErr==0 ){
95922     pTo->zErrMsg = pFrom->zErrMsg;
95923     pTo->nErr = pFrom->nErr;
95924   }else{
95925     sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
95926   }
95927 }
95928
95929 /*
95930 ** Create and populate a new TriggerPrg object with a sub-program 
95931 ** implementing trigger pTrigger with ON CONFLICT policy orconf.
95932 */
95933 static TriggerPrg *codeRowTrigger(
95934   Parse *pParse,       /* Current parse context */
95935   Trigger *pTrigger,   /* Trigger to code */
95936   Table *pTab,         /* The table pTrigger is attached to */
95937   int orconf           /* ON CONFLICT policy to code trigger program with */
95938 ){
95939   Parse *pTop = sqlite3ParseToplevel(pParse);
95940   sqlite3 *db = pParse->db;   /* Database handle */
95941   TriggerPrg *pPrg;           /* Value to return */
95942   Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
95943   Vdbe *v;                    /* Temporary VM */
95944   NameContext sNC;            /* Name context for sub-vdbe */
95945   SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
95946   Parse *pSubParse;           /* Parse context for sub-vdbe */
95947   int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
95948
95949   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
95950   assert( pTop->pVdbe );
95951
95952   /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
95953   ** are freed if an error occurs, link them into the Parse.pTriggerPrg 
95954   ** list of the top-level Parse object sooner rather than later.  */
95955   pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
95956   if( !pPrg ) return 0;
95957   pPrg->pNext = pTop->pTriggerPrg;
95958   pTop->pTriggerPrg = pPrg;
95959   pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
95960   if( !pProgram ) return 0;
95961   sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
95962   pPrg->pTrigger = pTrigger;
95963   pPrg->orconf = orconf;
95964   pPrg->aColmask[0] = 0xffffffff;
95965   pPrg->aColmask[1] = 0xffffffff;
95966
95967   /* Allocate and populate a new Parse context to use for coding the 
95968   ** trigger sub-program.  */
95969   pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
95970   if( !pSubParse ) return 0;
95971   memset(&sNC, 0, sizeof(sNC));
95972   sNC.pParse = pSubParse;
95973   pSubParse->db = db;
95974   pSubParse->pTriggerTab = pTab;
95975   pSubParse->pToplevel = pTop;
95976   pSubParse->zAuthContext = pTrigger->zName;
95977   pSubParse->eTriggerOp = pTrigger->op;
95978   pSubParse->nQueryLoop = pParse->nQueryLoop;
95979
95980   v = sqlite3GetVdbe(pSubParse);
95981   if( v ){
95982     VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)", 
95983       pTrigger->zName, onErrorText(orconf),
95984       (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
95985         (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
95986         (pTrigger->op==TK_INSERT ? "INSERT" : ""),
95987         (pTrigger->op==TK_DELETE ? "DELETE" : ""),
95988       pTab->zName
95989     ));
95990 #ifndef SQLITE_OMIT_TRACE
95991     sqlite3VdbeChangeP4(v, -1, 
95992       sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
95993     );
95994 #endif
95995
95996     /* If one was specified, code the WHEN clause. If it evaluates to false
95997     ** (or NULL) the sub-vdbe is immediately halted by jumping to the 
95998     ** OP_Halt inserted at the end of the program.  */
95999     if( pTrigger->pWhen ){
96000       pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
96001       if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen) 
96002        && db->mallocFailed==0 
96003       ){
96004         iEndTrigger = sqlite3VdbeMakeLabel(v);
96005         sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
96006       }
96007       sqlite3ExprDelete(db, pWhen);
96008     }
96009
96010     /* Code the trigger program into the sub-vdbe. */
96011     codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
96012
96013     /* Insert an OP_Halt at the end of the sub-program. */
96014     if( iEndTrigger ){
96015       sqlite3VdbeResolveLabel(v, iEndTrigger);
96016     }
96017     sqlite3VdbeAddOp0(v, OP_Halt);
96018     VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
96019
96020     transferParseError(pParse, pSubParse);
96021     if( db->mallocFailed==0 ){
96022       pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
96023     }
96024     pProgram->nMem = pSubParse->nMem;
96025     pProgram->nCsr = pSubParse->nTab;
96026     pProgram->token = (void *)pTrigger;
96027     pPrg->aColmask[0] = pSubParse->oldmask;
96028     pPrg->aColmask[1] = pSubParse->newmask;
96029     sqlite3VdbeDelete(v);
96030   }
96031
96032   assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
96033   assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
96034   sqlite3StackFree(db, pSubParse);
96035
96036   return pPrg;
96037 }
96038     
96039 /*
96040 ** Return a pointer to a TriggerPrg object containing the sub-program for
96041 ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
96042 ** TriggerPrg object exists, a new object is allocated and populated before
96043 ** being returned.
96044 */
96045 static TriggerPrg *getRowTrigger(
96046   Parse *pParse,       /* Current parse context */
96047   Trigger *pTrigger,   /* Trigger to code */
96048   Table *pTab,         /* The table trigger pTrigger is attached to */
96049   int orconf           /* ON CONFLICT algorithm. */
96050 ){
96051   Parse *pRoot = sqlite3ParseToplevel(pParse);
96052   TriggerPrg *pPrg;
96053
96054   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
96055
96056   /* It may be that this trigger has already been coded (or is in the
96057   ** process of being coded). If this is the case, then an entry with
96058   ** a matching TriggerPrg.pTrigger field will be present somewhere
96059   ** in the Parse.pTriggerPrg list. Search for such an entry.  */
96060   for(pPrg=pRoot->pTriggerPrg; 
96061       pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf); 
96062       pPrg=pPrg->pNext
96063   );
96064
96065   /* If an existing TriggerPrg could not be located, create a new one. */
96066   if( !pPrg ){
96067     pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
96068   }
96069
96070   return pPrg;
96071 }
96072
96073 /*
96074 ** Generate code for the trigger program associated with trigger p on 
96075 ** table pTab. The reg, orconf and ignoreJump parameters passed to this
96076 ** function are the same as those described in the header function for
96077 ** sqlite3CodeRowTrigger()
96078 */
96079 SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
96080   Parse *pParse,       /* Parse context */
96081   Trigger *p,          /* Trigger to code */
96082   Table *pTab,         /* The table to code triggers from */
96083   int reg,             /* Reg array containing OLD.* and NEW.* values */
96084   int orconf,          /* ON CONFLICT policy */
96085   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
96086 ){
96087   Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
96088   TriggerPrg *pPrg;
96089   pPrg = getRowTrigger(pParse, p, pTab, orconf);
96090   assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
96091
96092   /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program 
96093   ** is a pointer to the sub-vdbe containing the trigger program.  */
96094   if( pPrg ){
96095     int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
96096
96097     sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
96098     sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
96099     VdbeComment(
96100         (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
96101
96102     /* Set the P5 operand of the OP_Program instruction to non-zero if
96103     ** recursive invocation of this trigger program is disallowed. Recursive
96104     ** invocation is disallowed if (a) the sub-program is really a trigger,
96105     ** not a foreign key action, and (b) the flag to enable recursive triggers
96106     ** is clear.  */
96107     sqlite3VdbeChangeP5(v, (u8)bRecursive);
96108   }
96109 }
96110
96111 /*
96112 ** This is called to code the required FOR EACH ROW triggers for an operation
96113 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
96114 ** is given by the op paramater. The tr_tm parameter determines whether the
96115 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
96116 ** parameter pChanges is passed the list of columns being modified.
96117 **
96118 ** If there are no triggers that fire at the specified time for the specified
96119 ** operation on pTab, this function is a no-op.
96120 **
96121 ** The reg argument is the address of the first in an array of registers 
96122 ** that contain the values substituted for the new.* and old.* references
96123 ** in the trigger program. If N is the number of columns in table pTab
96124 ** (a copy of pTab->nCol), then registers are populated as follows:
96125 **
96126 **   Register       Contains
96127 **   ------------------------------------------------------
96128 **   reg+0          OLD.rowid
96129 **   reg+1          OLD.* value of left-most column of pTab
96130 **   ...            ...
96131 **   reg+N          OLD.* value of right-most column of pTab
96132 **   reg+N+1        NEW.rowid
96133 **   reg+N+2        OLD.* value of left-most column of pTab
96134 **   ...            ...
96135 **   reg+N+N+1      NEW.* value of right-most column of pTab
96136 **
96137 ** For ON DELETE triggers, the registers containing the NEW.* values will
96138 ** never be accessed by the trigger program, so they are not allocated or 
96139 ** populated by the caller (there is no data to populate them with anyway). 
96140 ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
96141 ** are never accessed, and so are not allocated by the caller. So, for an
96142 ** ON INSERT trigger, the value passed to this function as parameter reg
96143 ** is not a readable register, although registers (reg+N) through 
96144 ** (reg+N+N+1) are.
96145 **
96146 ** Parameter orconf is the default conflict resolution algorithm for the
96147 ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
96148 ** is the instruction that control should jump to if a trigger program
96149 ** raises an IGNORE exception.
96150 */
96151 SQLITE_PRIVATE void sqlite3CodeRowTrigger(
96152   Parse *pParse,       /* Parse context */
96153   Trigger *pTrigger,   /* List of triggers on table pTab */
96154   int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
96155   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
96156   int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
96157   Table *pTab,         /* The table to code triggers from */
96158   int reg,             /* The first in an array of registers (see above) */
96159   int orconf,          /* ON CONFLICT policy */
96160   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
96161 ){
96162   Trigger *p;          /* Used to iterate through pTrigger list */
96163
96164   assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
96165   assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
96166   assert( (op==TK_UPDATE)==(pChanges!=0) );
96167
96168   for(p=pTrigger; p; p=p->pNext){
96169
96170     /* Sanity checking:  The schema for the trigger and for the table are
96171     ** always defined.  The trigger must be in the same schema as the table
96172     ** or else it must be a TEMP trigger. */
96173     assert( p->pSchema!=0 );
96174     assert( p->pTabSchema!=0 );
96175     assert( p->pSchema==p->pTabSchema 
96176          || p->pSchema==pParse->db->aDb[1].pSchema );
96177
96178     /* Determine whether we should code this trigger */
96179     if( p->op==op 
96180      && p->tr_tm==tr_tm 
96181      && checkColumnOverlap(p->pColumns, pChanges)
96182     ){
96183       sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
96184     }
96185   }
96186 }
96187
96188 /*
96189 ** Triggers may access values stored in the old.* or new.* pseudo-table. 
96190 ** This function returns a 32-bit bitmask indicating which columns of the 
96191 ** old.* or new.* tables actually are used by triggers. This information 
96192 ** may be used by the caller, for example, to avoid having to load the entire
96193 ** old.* record into memory when executing an UPDATE or DELETE command.
96194 **
96195 ** Bit 0 of the returned mask is set if the left-most column of the
96196 ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
96197 ** the second leftmost column value is required, and so on. If there
96198 ** are more than 32 columns in the table, and at least one of the columns
96199 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
96200 **
96201 ** It is not possible to determine if the old.rowid or new.rowid column is 
96202 ** accessed by triggers. The caller must always assume that it is.
96203 **
96204 ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
96205 ** applies to the old.* table. If 1, the new.* table.
96206 **
96207 ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
96208 ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
96209 ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
96210 ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
96211 ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
96212 */
96213 SQLITE_PRIVATE u32 sqlite3TriggerColmask(
96214   Parse *pParse,       /* Parse context */
96215   Trigger *pTrigger,   /* List of triggers on table pTab */
96216   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
96217   int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
96218   int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
96219   Table *pTab,         /* The table to code triggers from */
96220   int orconf           /* Default ON CONFLICT policy for trigger steps */
96221 ){
96222   const int op = pChanges ? TK_UPDATE : TK_DELETE;
96223   u32 mask = 0;
96224   Trigger *p;
96225
96226   assert( isNew==1 || isNew==0 );
96227   for(p=pTrigger; p; p=p->pNext){
96228     if( p->op==op && (tr_tm&p->tr_tm)
96229      && checkColumnOverlap(p->pColumns,pChanges)
96230     ){
96231       TriggerPrg *pPrg;
96232       pPrg = getRowTrigger(pParse, p, pTab, orconf);
96233       if( pPrg ){
96234         mask |= pPrg->aColmask[isNew];
96235       }
96236     }
96237   }
96238
96239   return mask;
96240 }
96241
96242 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
96243
96244 /************** End of trigger.c *********************************************/
96245 /************** Begin file update.c ******************************************/
96246 /*
96247 ** 2001 September 15
96248 **
96249 ** The author disclaims copyright to this source code.  In place of
96250 ** a legal notice, here is a blessing:
96251 **
96252 **    May you do good and not evil.
96253 **    May you find forgiveness for yourself and forgive others.
96254 **    May you share freely, never taking more than you give.
96255 **
96256 *************************************************************************
96257 ** This file contains C code routines that are called by the parser
96258 ** to handle UPDATE statements.
96259 */
96260
96261 #ifndef SQLITE_OMIT_VIRTUALTABLE
96262 /* Forward declaration */
96263 static void updateVirtualTable(
96264   Parse *pParse,       /* The parsing context */
96265   SrcList *pSrc,       /* The virtual table to be modified */
96266   Table *pTab,         /* The virtual table */
96267   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
96268   Expr *pRowidExpr,    /* Expression used to recompute the rowid */
96269   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
96270   Expr *pWhere,        /* WHERE clause of the UPDATE statement */
96271   int onError          /* ON CONFLICT strategy */
96272 );
96273 #endif /* SQLITE_OMIT_VIRTUALTABLE */
96274
96275 /*
96276 ** The most recently coded instruction was an OP_Column to retrieve the
96277 ** i-th column of table pTab. This routine sets the P4 parameter of the 
96278 ** OP_Column to the default value, if any.
96279 **
96280 ** The default value of a column is specified by a DEFAULT clause in the 
96281 ** column definition. This was either supplied by the user when the table
96282 ** was created, or added later to the table definition by an ALTER TABLE
96283 ** command. If the latter, then the row-records in the table btree on disk
96284 ** may not contain a value for the column and the default value, taken
96285 ** from the P4 parameter of the OP_Column instruction, is returned instead.
96286 ** If the former, then all row-records are guaranteed to include a value
96287 ** for the column and the P4 value is not required.
96288 **
96289 ** Column definitions created by an ALTER TABLE command may only have 
96290 ** literal default values specified: a number, null or a string. (If a more
96291 ** complicated default expression value was provided, it is evaluated 
96292 ** when the ALTER TABLE is executed and one of the literal values written
96293 ** into the sqlite_master table.)
96294 **
96295 ** Therefore, the P4 parameter is only required if the default value for
96296 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
96297 ** function is capable of transforming these types of expressions into
96298 ** sqlite3_value objects.
96299 **
96300 ** If parameter iReg is not negative, code an OP_RealAffinity instruction
96301 ** on register iReg. This is used when an equivalent integer value is 
96302 ** stored in place of an 8-byte floating point value in order to save 
96303 ** space.
96304 */
96305 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
96306   assert( pTab!=0 );
96307   if( !pTab->pSelect ){
96308     sqlite3_value *pValue;
96309     u8 enc = ENC(sqlite3VdbeDb(v));
96310     Column *pCol = &pTab->aCol[i];
96311     VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
96312     assert( i<pTab->nCol );
96313     sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc, 
96314                          pCol->affinity, &pValue);
96315     if( pValue ){
96316       sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
96317     }
96318 #ifndef SQLITE_OMIT_FLOATING_POINT
96319     if( iReg>=0 && pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
96320       sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
96321     }
96322 #endif
96323   }
96324 }
96325
96326 /*
96327 ** Process an UPDATE statement.
96328 **
96329 **   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
96330 **          \_______/ \________/     \______/       \________________/
96331 *            onError   pTabList      pChanges             pWhere
96332 */
96333 SQLITE_PRIVATE void sqlite3Update(
96334   Parse *pParse,         /* The parser context */
96335   SrcList *pTabList,     /* The table in which we should change things */
96336   ExprList *pChanges,    /* Things to be changed */
96337   Expr *pWhere,          /* The WHERE clause.  May be null */
96338   int onError            /* How to handle constraint errors */
96339 ){
96340   int i, j;              /* Loop counters */
96341   Table *pTab;           /* The table to be updated */
96342   int addr = 0;          /* VDBE instruction address of the start of the loop */
96343   WhereInfo *pWInfo;     /* Information about the WHERE clause */
96344   Vdbe *v;               /* The virtual database engine */
96345   Index *pIdx;           /* For looping over indices */
96346   int nIdx;              /* Number of indices that need updating */
96347   int iCur;              /* VDBE Cursor number of pTab */
96348   sqlite3 *db;           /* The database structure */
96349   int *aRegIdx = 0;      /* One register assigned to each index to be updated */
96350   int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
96351                          ** an expression for the i-th column of the table.
96352                          ** aXRef[i]==-1 if the i-th column is not changed. */
96353   int chngRowid;         /* True if the record number is being changed */
96354   Expr *pRowidExpr = 0;  /* Expression defining the new record number */
96355   int openAll = 0;       /* True if all indices need to be opened */
96356   AuthContext sContext;  /* The authorization context */
96357   NameContext sNC;       /* The name-context to resolve expressions in */
96358   int iDb;               /* Database containing the table being updated */
96359   int okOnePass;         /* True for one-pass algorithm without the FIFO */
96360   int hasFK;             /* True if foreign key processing is required */
96361
96362 #ifndef SQLITE_OMIT_TRIGGER
96363   int isView;            /* True when updating a view (INSTEAD OF trigger) */
96364   Trigger *pTrigger;     /* List of triggers on pTab, if required */
96365   int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
96366 #endif
96367   int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
96368
96369   /* Register Allocations */
96370   int regRowCount = 0;   /* A count of rows changed */
96371   int regOldRowid;       /* The old rowid */
96372   int regNewRowid;       /* The new rowid */
96373   int regNew;
96374   int regOld = 0;
96375   int regRowSet = 0;     /* Rowset of rows to be updated */
96376
96377   memset(&sContext, 0, sizeof(sContext));
96378   db = pParse->db;
96379   if( pParse->nErr || db->mallocFailed ){
96380     goto update_cleanup;
96381   }
96382   assert( pTabList->nSrc==1 );
96383
96384   /* Locate the table which we want to update. 
96385   */
96386   pTab = sqlite3SrcListLookup(pParse, pTabList);
96387   if( pTab==0 ) goto update_cleanup;
96388   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
96389
96390   /* Figure out if we have any triggers and if the table being
96391   ** updated is a view.
96392   */
96393 #ifndef SQLITE_OMIT_TRIGGER
96394   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
96395   isView = pTab->pSelect!=0;
96396   assert( pTrigger || tmask==0 );
96397 #else
96398 # define pTrigger 0
96399 # define isView 0
96400 # define tmask 0
96401 #endif
96402 #ifdef SQLITE_OMIT_VIEW
96403 # undef isView
96404 # define isView 0
96405 #endif
96406
96407   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
96408     goto update_cleanup;
96409   }
96410   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
96411     goto update_cleanup;
96412   }
96413   aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
96414   if( aXRef==0 ) goto update_cleanup;
96415   for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
96416
96417   /* Allocate a cursors for the main database table and for all indices.
96418   ** The index cursors might not be used, but if they are used they
96419   ** need to occur right after the database cursor.  So go ahead and
96420   ** allocate enough space, just in case.
96421   */
96422   pTabList->a[0].iCursor = iCur = pParse->nTab++;
96423   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
96424     pParse->nTab++;
96425   }
96426
96427   /* Initialize the name-context */
96428   memset(&sNC, 0, sizeof(sNC));
96429   sNC.pParse = pParse;
96430   sNC.pSrcList = pTabList;
96431
96432   /* Resolve the column names in all the expressions of the
96433   ** of the UPDATE statement.  Also find the column index
96434   ** for each column to be updated in the pChanges array.  For each
96435   ** column to be updated, make sure we have authorization to change
96436   ** that column.
96437   */
96438   chngRowid = 0;
96439   for(i=0; i<pChanges->nExpr; i++){
96440     if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
96441       goto update_cleanup;
96442     }
96443     for(j=0; j<pTab->nCol; j++){
96444       if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
96445         if( j==pTab->iPKey ){
96446           chngRowid = 1;
96447           pRowidExpr = pChanges->a[i].pExpr;
96448         }
96449         aXRef[j] = i;
96450         break;
96451       }
96452     }
96453     if( j>=pTab->nCol ){
96454       if( sqlite3IsRowid(pChanges->a[i].zName) ){
96455         chngRowid = 1;
96456         pRowidExpr = pChanges->a[i].pExpr;
96457       }else{
96458         sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
96459         pParse->checkSchema = 1;
96460         goto update_cleanup;
96461       }
96462     }
96463 #ifndef SQLITE_OMIT_AUTHORIZATION
96464     {
96465       int rc;
96466       rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
96467                            pTab->aCol[j].zName, db->aDb[iDb].zName);
96468       if( rc==SQLITE_DENY ){
96469         goto update_cleanup;
96470       }else if( rc==SQLITE_IGNORE ){
96471         aXRef[j] = -1;
96472       }
96473     }
96474 #endif
96475   }
96476
96477   hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid);
96478
96479   /* Allocate memory for the array aRegIdx[].  There is one entry in the
96480   ** array for each index associated with table being updated.  Fill in
96481   ** the value with a register number for indices that are to be used
96482   ** and with zero for unused indices.
96483   */
96484   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
96485   if( nIdx>0 ){
96486     aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
96487     if( aRegIdx==0 ) goto update_cleanup;
96488   }
96489   for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
96490     int reg;
96491     if( hasFK || chngRowid ){
96492       reg = ++pParse->nMem;
96493     }else{
96494       reg = 0;
96495       for(i=0; i<pIdx->nColumn; i++){
96496         if( aXRef[pIdx->aiColumn[i]]>=0 ){
96497           reg = ++pParse->nMem;
96498           break;
96499         }
96500       }
96501     }
96502     aRegIdx[j] = reg;
96503   }
96504
96505   /* Begin generating code. */
96506   v = sqlite3GetVdbe(pParse);
96507   if( v==0 ) goto update_cleanup;
96508   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
96509   sqlite3BeginWriteOperation(pParse, 1, iDb);
96510
96511 #ifndef SQLITE_OMIT_VIRTUALTABLE
96512   /* Virtual tables must be handled separately */
96513   if( IsVirtual(pTab) ){
96514     updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
96515                        pWhere, onError);
96516     pWhere = 0;
96517     pTabList = 0;
96518     goto update_cleanup;
96519   }
96520 #endif
96521
96522   /* Allocate required registers. */
96523   regOldRowid = regNewRowid = ++pParse->nMem;
96524   if( pTrigger || hasFK ){
96525     regOld = pParse->nMem + 1;
96526     pParse->nMem += pTab->nCol;
96527   }
96528   if( chngRowid || pTrigger || hasFK ){
96529     regNewRowid = ++pParse->nMem;
96530   }
96531   regNew = pParse->nMem + 1;
96532   pParse->nMem += pTab->nCol;
96533
96534   /* Start the view context. */
96535   if( isView ){
96536     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
96537   }
96538
96539   /* If we are trying to update a view, realize that view into
96540   ** a ephemeral table.
96541   */
96542 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
96543   if( isView ){
96544     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
96545   }
96546 #endif
96547
96548   /* Resolve the column names in all the expressions in the
96549   ** WHERE clause.
96550   */
96551   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
96552     goto update_cleanup;
96553   }
96554
96555   /* Begin the database scan
96556   */
96557   sqlite3VdbeAddOp2(v, OP_Null, 0, regOldRowid);
96558   pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0, WHERE_ONEPASS_DESIRED);
96559   if( pWInfo==0 ) goto update_cleanup;
96560   okOnePass = pWInfo->okOnePass;
96561
96562   /* Remember the rowid of every item to be updated.
96563   */
96564   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
96565   if( !okOnePass ){
96566     regRowSet = ++pParse->nMem;
96567     sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
96568   }
96569
96570   /* End the database scan loop.
96571   */
96572   sqlite3WhereEnd(pWInfo);
96573
96574   /* Initialize the count of updated rows
96575   */
96576   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
96577     regRowCount = ++pParse->nMem;
96578     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
96579   }
96580
96581   if( !isView ){
96582     /* 
96583     ** Open every index that needs updating.  Note that if any
96584     ** index could potentially invoke a REPLACE conflict resolution 
96585     ** action, then we need to open all indices because we might need
96586     ** to be deleting some records.
96587     */
96588     if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite); 
96589     if( onError==OE_Replace ){
96590       openAll = 1;
96591     }else{
96592       openAll = 0;
96593       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
96594         if( pIdx->onError==OE_Replace ){
96595           openAll = 1;
96596           break;
96597         }
96598       }
96599     }
96600     for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
96601       if( openAll || aRegIdx[i]>0 ){
96602         KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
96603         sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
96604                        (char*)pKey, P4_KEYINFO_HANDOFF);
96605         assert( pParse->nTab>iCur+i+1 );
96606       }
96607     }
96608   }
96609
96610   /* Top of the update loop */
96611   if( okOnePass ){
96612     int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
96613     addr = sqlite3VdbeAddOp0(v, OP_Goto);
96614     sqlite3VdbeJumpHere(v, a1);
96615   }else{
96616     addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
96617   }
96618
96619   /* Make cursor iCur point to the record that is being updated. If
96620   ** this record does not exist for some reason (deleted by a trigger,
96621   ** for example, then jump to the next iteration of the RowSet loop.  */
96622   sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
96623
96624   /* If the record number will change, set register regNewRowid to
96625   ** contain the new value. If the record number is not being modified,
96626   ** then regNewRowid is the same register as regOldRowid, which is
96627   ** already populated.  */
96628   assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );
96629   if( chngRowid ){
96630     sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
96631     sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
96632   }
96633
96634   /* If there are triggers on this table, populate an array of registers 
96635   ** with the required old.* column data.  */
96636   if( hasFK || pTrigger ){
96637     u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
96638     oldmask |= sqlite3TriggerColmask(pParse, 
96639         pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
96640     );
96641     for(i=0; i<pTab->nCol; i++){
96642       if( aXRef[i]<0 || oldmask==0xffffffff || (i<32 && (oldmask & (1<<i))) ){
96643         sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOld+i);
96644       }else{
96645         sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
96646       }
96647     }
96648     if( chngRowid==0 ){
96649       sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
96650     }
96651   }
96652
96653   /* Populate the array of registers beginning at regNew with the new
96654   ** row data. This array is used to check constaints, create the new
96655   ** table and index records, and as the values for any new.* references
96656   ** made by triggers.
96657   **
96658   ** If there are one or more BEFORE triggers, then do not populate the
96659   ** registers associated with columns that are (a) not modified by
96660   ** this UPDATE statement and (b) not accessed by new.* references. The
96661   ** values for registers not modified by the UPDATE must be reloaded from 
96662   ** the database after the BEFORE triggers are fired anyway (as the trigger 
96663   ** may have modified them). So not loading those that are not going to
96664   ** be used eliminates some redundant opcodes.
96665   */
96666   newmask = sqlite3TriggerColmask(
96667       pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
96668   );
96669   for(i=0; i<pTab->nCol; i++){
96670     if( i==pTab->iPKey ){
96671       sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
96672     }else{
96673       j = aXRef[i];
96674       if( j>=0 ){
96675         sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
96676       }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<<i)) ){
96677         /* This branch loads the value of a column that will not be changed 
96678         ** into a register. This is done if there are no BEFORE triggers, or
96679         ** if there are one or more BEFORE triggers that use this value via
96680         ** a new.* reference in a trigger program.
96681         */
96682         testcase( i==31 );
96683         testcase( i==32 );
96684         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
96685         sqlite3ColumnDefault(v, pTab, i, regNew+i);
96686       }
96687     }
96688   }
96689
96690   /* Fire any BEFORE UPDATE triggers. This happens before constraints are
96691   ** verified. One could argue that this is wrong.
96692   */
96693   if( tmask&TRIGGER_BEFORE ){
96694     sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
96695     sqlite3TableAffinityStr(v, pTab);
96696     sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
96697         TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);
96698
96699     /* The row-trigger may have deleted the row being updated. In this
96700     ** case, jump to the next row. No updates or AFTER triggers are 
96701     ** required. This behaviour - what happens when the row being updated
96702     ** is deleted or renamed by a BEFORE trigger - is left undefined in the
96703     ** documentation.
96704     */
96705     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
96706
96707     /* If it did not delete it, the row-trigger may still have modified 
96708     ** some of the columns of the row being updated. Load the values for 
96709     ** all columns not modified by the update statement into their 
96710     ** registers in case this has happened.
96711     */
96712     for(i=0; i<pTab->nCol; i++){
96713       if( aXRef[i]<0 && i!=pTab->iPKey ){
96714         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
96715         sqlite3ColumnDefault(v, pTab, i, regNew+i);
96716       }
96717     }
96718   }
96719
96720   if( !isView ){
96721     int j1;                       /* Address of jump instruction */
96722
96723     /* Do constraint checks. */
96724     sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
96725         aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);
96726
96727     /* Do FK constraint checks. */
96728     if( hasFK ){
96729       sqlite3FkCheck(pParse, pTab, regOldRowid, 0);
96730     }
96731
96732     /* Delete the index entries associated with the current record.  */
96733     j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
96734     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
96735   
96736     /* If changing the record number, delete the old record.  */
96737     if( hasFK || chngRowid ){
96738       sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
96739     }
96740     sqlite3VdbeJumpHere(v, j1);
96741
96742     if( hasFK ){
96743       sqlite3FkCheck(pParse, pTab, 0, regNewRowid);
96744     }
96745   
96746     /* Insert the new index entries and the new record. */
96747     sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);
96748
96749     /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
96750     ** handle rows (possibly in other tables) that refer via a foreign key
96751     ** to the row just updated. */ 
96752     if( hasFK ){
96753       sqlite3FkActions(pParse, pTab, pChanges, regOldRowid);
96754     }
96755   }
96756
96757   /* Increment the row counter 
96758   */
96759   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
96760     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
96761   }
96762
96763   sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
96764       TRIGGER_AFTER, pTab, regOldRowid, onError, addr);
96765
96766   /* Repeat the above with the next record to be updated, until
96767   ** all record selected by the WHERE clause have been updated.
96768   */
96769   sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
96770   sqlite3VdbeJumpHere(v, addr);
96771
96772   /* Close all tables */
96773   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
96774     if( openAll || aRegIdx[i]>0 ){
96775       sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
96776     }
96777   }
96778   sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
96779
96780   /* Update the sqlite_sequence table by storing the content of the
96781   ** maximum rowid counter values recorded while inserting into
96782   ** autoincrement tables.
96783   */
96784   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
96785     sqlite3AutoincrementEnd(pParse);
96786   }
96787
96788   /*
96789   ** Return the number of rows that were changed. If this routine is 
96790   ** generating code because of a call to sqlite3NestedParse(), do not
96791   ** invoke the callback function.
96792   */
96793   if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
96794     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
96795     sqlite3VdbeSetNumCols(v, 1);
96796     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
96797   }
96798
96799 update_cleanup:
96800   sqlite3AuthContextPop(&sContext);
96801   sqlite3DbFree(db, aRegIdx);
96802   sqlite3DbFree(db, aXRef);
96803   sqlite3SrcListDelete(db, pTabList);
96804   sqlite3ExprListDelete(db, pChanges);
96805   sqlite3ExprDelete(db, pWhere);
96806   return;
96807 }
96808 /* Make sure "isView" and other macros defined above are undefined. Otherwise
96809 ** thely may interfere with compilation of other functions in this file
96810 ** (or in another file, if this file becomes part of the amalgamation).  */
96811 #ifdef isView
96812  #undef isView
96813 #endif
96814 #ifdef pTrigger
96815  #undef pTrigger
96816 #endif
96817
96818 #ifndef SQLITE_OMIT_VIRTUALTABLE
96819 /*
96820 ** Generate code for an UPDATE of a virtual table.
96821 **
96822 ** The strategy is that we create an ephemerial table that contains
96823 ** for each row to be changed:
96824 **
96825 **   (A)  The original rowid of that row.
96826 **   (B)  The revised rowid for the row. (note1)
96827 **   (C)  The content of every column in the row.
96828 **
96829 ** Then we loop over this ephemeral table and for each row in
96830 ** the ephermeral table call VUpdate.
96831 **
96832 ** When finished, drop the ephemeral table.
96833 **
96834 ** (note1) Actually, if we know in advance that (A) is always the same
96835 ** as (B) we only store (A), then duplicate (A) when pulling
96836 ** it out of the ephemeral table before calling VUpdate.
96837 */
96838 static void updateVirtualTable(
96839   Parse *pParse,       /* The parsing context */
96840   SrcList *pSrc,       /* The virtual table to be modified */
96841   Table *pTab,         /* The virtual table */
96842   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
96843   Expr *pRowid,        /* Expression used to recompute the rowid */
96844   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
96845   Expr *pWhere,        /* WHERE clause of the UPDATE statement */
96846   int onError          /* ON CONFLICT strategy */
96847 ){
96848   Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
96849   ExprList *pEList = 0;     /* The result set of the SELECT statement */
96850   Select *pSelect = 0;      /* The SELECT statement */
96851   Expr *pExpr;              /* Temporary expression */
96852   int ephemTab;             /* Table holding the result of the SELECT */
96853   int i;                    /* Loop counter */
96854   int addr;                 /* Address of top of loop */
96855   int iReg;                 /* First register in set passed to OP_VUpdate */
96856   sqlite3 *db = pParse->db; /* Database connection */
96857   const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
96858   SelectDest dest;
96859
96860   /* Construct the SELECT statement that will find the new values for
96861   ** all updated rows. 
96862   */
96863   pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
96864   if( pRowid ){
96865     pEList = sqlite3ExprListAppend(pParse, pEList,
96866                                    sqlite3ExprDup(db, pRowid, 0));
96867   }
96868   assert( pTab->iPKey<0 );
96869   for(i=0; i<pTab->nCol; i++){
96870     if( aXRef[i]>=0 ){
96871       pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
96872     }else{
96873       pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
96874     }
96875     pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
96876   }
96877   pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
96878   
96879   /* Create the ephemeral table into which the update results will
96880   ** be stored.
96881   */
96882   assert( v );
96883   ephemTab = pParse->nTab++;
96884   sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
96885   sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
96886
96887   /* fill the ephemeral table 
96888   */
96889   sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
96890   sqlite3Select(pParse, pSelect, &dest);
96891
96892   /* Generate code to scan the ephemeral table and call VUpdate. */
96893   iReg = ++pParse->nMem;
96894   pParse->nMem += pTab->nCol+1;
96895   addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
96896   sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
96897   sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
96898   for(i=0; i<pTab->nCol; i++){
96899     sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
96900   }
96901   sqlite3VtabMakeWritable(pParse, pTab);
96902   sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
96903   sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
96904   sqlite3MayAbort(pParse);
96905   sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
96906   sqlite3VdbeJumpHere(v, addr);
96907   sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
96908
96909   /* Cleanup */
96910   sqlite3SelectDelete(db, pSelect);  
96911 }
96912 #endif /* SQLITE_OMIT_VIRTUALTABLE */
96913
96914 /************** End of update.c **********************************************/
96915 /************** Begin file vacuum.c ******************************************/
96916 /*
96917 ** 2003 April 6
96918 **
96919 ** The author disclaims copyright to this source code.  In place of
96920 ** a legal notice, here is a blessing:
96921 **
96922 **    May you do good and not evil.
96923 **    May you find forgiveness for yourself and forgive others.
96924 **    May you share freely, never taking more than you give.
96925 **
96926 *************************************************************************
96927 ** This file contains code used to implement the VACUUM command.
96928 **
96929 ** Most of the code in this file may be omitted by defining the
96930 ** SQLITE_OMIT_VACUUM macro.
96931 */
96932
96933 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
96934 /*
96935 ** Finalize a prepared statement.  If there was an error, store the
96936 ** text of the error message in *pzErrMsg.  Return the result code.
96937 */
96938 static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
96939   int rc;
96940   rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
96941   if( rc ){
96942     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
96943   }
96944   return rc;
96945 }
96946
96947 /*
96948 ** Execute zSql on database db. Return an error code.
96949 */
96950 static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
96951   sqlite3_stmt *pStmt;
96952   VVA_ONLY( int rc; )
96953   if( !zSql ){
96954     return SQLITE_NOMEM;
96955   }
96956   if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
96957     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
96958     return sqlite3_errcode(db);
96959   }
96960   VVA_ONLY( rc = ) sqlite3_step(pStmt);
96961   assert( rc!=SQLITE_ROW );
96962   return vacuumFinalize(db, pStmt, pzErrMsg);
96963 }
96964
96965 /*
96966 ** Execute zSql on database db. The statement returns exactly
96967 ** one column. Execute this as SQL on the same database.
96968 */
96969 static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
96970   sqlite3_stmt *pStmt;
96971   int rc;
96972
96973   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
96974   if( rc!=SQLITE_OK ) return rc;
96975
96976   while( SQLITE_ROW==sqlite3_step(pStmt) ){
96977     rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
96978     if( rc!=SQLITE_OK ){
96979       vacuumFinalize(db, pStmt, pzErrMsg);
96980       return rc;
96981     }
96982   }
96983
96984   return vacuumFinalize(db, pStmt, pzErrMsg);
96985 }
96986
96987 /*
96988 ** The non-standard VACUUM command is used to clean up the database,
96989 ** collapse free space, etc.  It is modelled after the VACUUM command
96990 ** in PostgreSQL.
96991 **
96992 ** In version 1.0.x of SQLite, the VACUUM command would call
96993 ** gdbm_reorganize() on all the database tables.  But beginning
96994 ** with 2.0.0, SQLite no longer uses GDBM so this command has
96995 ** become a no-op.
96996 */
96997 SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
96998   Vdbe *v = sqlite3GetVdbe(pParse);
96999   if( v ){
97000     sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
97001   }
97002   return;
97003 }
97004
97005 /*
97006 ** This routine implements the OP_Vacuum opcode of the VDBE.
97007 */
97008 SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
97009   int rc = SQLITE_OK;     /* Return code from service routines */
97010   Btree *pMain;           /* The database being vacuumed */
97011   Btree *pTemp;           /* The temporary database we vacuum into */
97012   char *zSql = 0;         /* SQL statements */
97013   int saved_flags;        /* Saved value of the db->flags */
97014   int saved_nChange;      /* Saved value of db->nChange */
97015   int saved_nTotalChange; /* Saved value of db->nTotalChange */
97016   void (*saved_xTrace)(void*,const char*);  /* Saved db->xTrace */
97017   Db *pDb = 0;            /* Database to detach at end of vacuum */
97018   int isMemDb;            /* True if vacuuming a :memory: database */
97019   int nRes;               /* Bytes of reserved space at the end of each page */
97020   int nDb;                /* Number of attached databases */
97021
97022   if( !db->autoCommit ){
97023     sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
97024     return SQLITE_ERROR;
97025   }
97026   if( db->activeVdbeCnt>1 ){
97027     sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
97028     return SQLITE_ERROR;
97029   }
97030
97031   /* Save the current value of the database flags so that it can be 
97032   ** restored before returning. Then set the writable-schema flag, and
97033   ** disable CHECK and foreign key constraints.  */
97034   saved_flags = db->flags;
97035   saved_nChange = db->nChange;
97036   saved_nTotalChange = db->nTotalChange;
97037   saved_xTrace = db->xTrace;
97038   db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
97039   db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
97040   db->xTrace = 0;
97041
97042   pMain = db->aDb[0].pBt;
97043   isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
97044
97045   /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
97046   ** can be set to 'off' for this file, as it is not recovered if a crash
97047   ** occurs anyway. The integrity of the database is maintained by a
97048   ** (possibly synchronous) transaction opened on the main database before
97049   ** sqlite3BtreeCopyFile() is called.
97050   **
97051   ** An optimisation would be to use a non-journaled pager.
97052   ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
97053   ** that actually made the VACUUM run slower.  Very little journalling
97054   ** actually occurs when doing a vacuum since the vacuum_db is initially
97055   ** empty.  Only the journal header is written.  Apparently it takes more
97056   ** time to parse and run the PRAGMA to turn journalling off than it does
97057   ** to write the journal header file.
97058   */
97059   nDb = db->nDb;
97060   if( sqlite3TempInMemory(db) ){
97061     zSql = "ATTACH ':memory:' AS vacuum_db;";
97062   }else{
97063     zSql = "ATTACH '' AS vacuum_db;";
97064   }
97065   rc = execSql(db, pzErrMsg, zSql);
97066   if( db->nDb>nDb ){
97067     pDb = &db->aDb[db->nDb-1];
97068     assert( strcmp(pDb->zName,"vacuum_db")==0 );
97069   }
97070   if( rc!=SQLITE_OK ) goto end_of_vacuum;
97071   pTemp = db->aDb[db->nDb-1].pBt;
97072
97073   /* The call to execSql() to attach the temp database has left the file
97074   ** locked (as there was more than one active statement when the transaction
97075   ** to read the schema was concluded. Unlock it here so that this doesn't
97076   ** cause problems for the call to BtreeSetPageSize() below.  */
97077   sqlite3BtreeCommit(pTemp);
97078
97079   nRes = sqlite3BtreeGetReserve(pMain);
97080
97081   /* A VACUUM cannot change the pagesize of an encrypted database. */
97082 #ifdef SQLITE_HAS_CODEC
97083   if( db->nextPagesize ){
97084     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
97085     int nKey;
97086     char *zKey;
97087     sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
97088     if( nKey ) db->nextPagesize = 0;
97089   }
97090 #endif
97091
97092   /* Do not attempt to change the page size for a WAL database */
97093   if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
97094                                                ==PAGER_JOURNALMODE_WAL ){
97095     db->nextPagesize = 0;
97096   }
97097
97098   if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
97099    || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
97100    || NEVER(db->mallocFailed)
97101   ){
97102     rc = SQLITE_NOMEM;
97103     goto end_of_vacuum;
97104   }
97105   rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
97106   if( rc!=SQLITE_OK ){
97107     goto end_of_vacuum;
97108   }
97109
97110 #ifndef SQLITE_OMIT_AUTOVACUUM
97111   sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
97112                                            sqlite3BtreeGetAutoVacuum(pMain));
97113 #endif
97114
97115   /* Begin a transaction */
97116   rc = execSql(db, pzErrMsg, "BEGIN EXCLUSIVE;");
97117   if( rc!=SQLITE_OK ) goto end_of_vacuum;
97118
97119   /* Query the schema of the main database. Create a mirror schema
97120   ** in the temporary database.
97121   */
97122   rc = execExecSql(db, pzErrMsg,
97123       "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
97124       "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
97125       "   AND rootpage>0"
97126   );
97127   if( rc!=SQLITE_OK ) goto end_of_vacuum;
97128   rc = execExecSql(db, pzErrMsg,
97129       "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
97130       "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
97131   if( rc!=SQLITE_OK ) goto end_of_vacuum;
97132   rc = execExecSql(db, pzErrMsg,
97133       "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
97134       "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
97135   if( rc!=SQLITE_OK ) goto end_of_vacuum;
97136
97137   /* Loop through the tables in the main database. For each, do
97138   ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
97139   ** the contents to the temporary database.
97140   */
97141   rc = execExecSql(db, pzErrMsg,
97142       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
97143       "|| ' SELECT * FROM main.' || quote(name) || ';'"
97144       "FROM main.sqlite_master "
97145       "WHERE type = 'table' AND name!='sqlite_sequence' "
97146       "  AND rootpage>0"
97147   );
97148   if( rc!=SQLITE_OK ) goto end_of_vacuum;
97149
97150   /* Copy over the sequence table
97151   */
97152   rc = execExecSql(db, pzErrMsg,
97153       "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
97154       "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
97155   );
97156   if( rc!=SQLITE_OK ) goto end_of_vacuum;
97157   rc = execExecSql(db, pzErrMsg,
97158       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
97159       "|| ' SELECT * FROM main.' || quote(name) || ';' "
97160       "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
97161   );
97162   if( rc!=SQLITE_OK ) goto end_of_vacuum;
97163
97164
97165   /* Copy the triggers, views, and virtual tables from the main database
97166   ** over to the temporary database.  None of these objects has any
97167   ** associated storage, so all we have to do is copy their entries
97168   ** from the SQLITE_MASTER table.
97169   */
97170   rc = execSql(db, pzErrMsg,
97171       "INSERT INTO vacuum_db.sqlite_master "
97172       "  SELECT type, name, tbl_name, rootpage, sql"
97173       "    FROM main.sqlite_master"
97174       "   WHERE type='view' OR type='trigger'"
97175       "      OR (type='table' AND rootpage=0)"
97176   );
97177   if( rc ) goto end_of_vacuum;
97178
97179   /* At this point, unless the main db was completely empty, there is now a
97180   ** transaction open on the vacuum database, but not on the main database.
97181   ** Open a btree level transaction on the main database. This allows a
97182   ** call to sqlite3BtreeCopyFile(). The main database btree level
97183   ** transaction is then committed, so the SQL level never knows it was
97184   ** opened for writing. This way, the SQL transaction used to create the
97185   ** temporary database never needs to be committed.
97186   */
97187   {
97188     u32 meta;
97189     int i;
97190
97191     /* This array determines which meta meta values are preserved in the
97192     ** vacuum.  Even entries are the meta value number and odd entries
97193     ** are an increment to apply to the meta value after the vacuum.
97194     ** The increment is used to increase the schema cookie so that other
97195     ** connections to the same database will know to reread the schema.
97196     */
97197     static const unsigned char aCopy[] = {
97198        BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
97199        BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
97200        BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
97201        BTREE_USER_VERSION,       0,  /* Preserve the user version */
97202     };
97203
97204     assert( 1==sqlite3BtreeIsInTrans(pTemp) );
97205     assert( 1==sqlite3BtreeIsInTrans(pMain) );
97206
97207     /* Copy Btree meta values */
97208     for(i=0; i<ArraySize(aCopy); i+=2){
97209       /* GetMeta() and UpdateMeta() cannot fail in this context because
97210       ** we already have page 1 loaded into cache and marked dirty. */
97211       sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
97212       rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
97213       if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
97214     }
97215
97216     rc = sqlite3BtreeCopyFile(pMain, pTemp);
97217     if( rc!=SQLITE_OK ) goto end_of_vacuum;
97218     rc = sqlite3BtreeCommit(pTemp);
97219     if( rc!=SQLITE_OK ) goto end_of_vacuum;
97220 #ifndef SQLITE_OMIT_AUTOVACUUM
97221     sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
97222 #endif
97223   }
97224
97225   assert( rc==SQLITE_OK );
97226   rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
97227
97228 end_of_vacuum:
97229   /* Restore the original value of db->flags */
97230   db->flags = saved_flags;
97231   db->nChange = saved_nChange;
97232   db->nTotalChange = saved_nTotalChange;
97233   db->xTrace = saved_xTrace;
97234   sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
97235
97236   /* Currently there is an SQL level transaction open on the vacuum
97237   ** database. No locks are held on any other files (since the main file
97238   ** was committed at the btree level). So it safe to end the transaction
97239   ** by manually setting the autoCommit flag to true and detaching the
97240   ** vacuum database. The vacuum_db journal file is deleted when the pager
97241   ** is closed by the DETACH.
97242   */
97243   db->autoCommit = 1;
97244
97245   if( pDb ){
97246     sqlite3BtreeClose(pDb->pBt);
97247     pDb->pBt = 0;
97248     pDb->pSchema = 0;
97249   }
97250
97251   /* This both clears the schemas and reduces the size of the db->aDb[]
97252   ** array. */ 
97253   sqlite3ResetInternalSchema(db, -1);
97254
97255   return rc;
97256 }
97257
97258 #endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
97259
97260 /************** End of vacuum.c **********************************************/
97261 /************** Begin file vtab.c ********************************************/
97262 /*
97263 ** 2006 June 10
97264 **
97265 ** The author disclaims copyright to this source code.  In place of
97266 ** a legal notice, here is a blessing:
97267 **
97268 **    May you do good and not evil.
97269 **    May you find forgiveness for yourself and forgive others.
97270 **    May you share freely, never taking more than you give.
97271 **
97272 *************************************************************************
97273 ** This file contains code used to help implement virtual tables.
97274 */
97275 #ifndef SQLITE_OMIT_VIRTUALTABLE
97276
97277 /*
97278 ** Before a virtual table xCreate() or xConnect() method is invoked, the
97279 ** sqlite3.pVtabCtx member variable is set to point to an instance of
97280 ** this struct allocated on the stack. It is used by the implementation of 
97281 ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
97282 ** are invoked only from within xCreate and xConnect methods.
97283 */
97284 struct VtabCtx {
97285   Table *pTab;
97286   VTable *pVTable;
97287 };
97288
97289 /*
97290 ** The actual function that does the work of creating a new module.
97291 ** This function implements the sqlite3_create_module() and
97292 ** sqlite3_create_module_v2() interfaces.
97293 */
97294 static int createModule(
97295   sqlite3 *db,                    /* Database in which module is registered */
97296   const char *zName,              /* Name assigned to this module */
97297   const sqlite3_module *pModule,  /* The definition of the module */
97298   void *pAux,                     /* Context pointer for xCreate/xConnect */
97299   void (*xDestroy)(void *)        /* Module destructor function */
97300 ){
97301   int rc, nName;
97302   Module *pMod;
97303
97304   sqlite3_mutex_enter(db->mutex);
97305   nName = sqlite3Strlen30(zName);
97306   pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
97307   if( pMod ){
97308     Module *pDel;
97309     char *zCopy = (char *)(&pMod[1]);
97310     memcpy(zCopy, zName, nName+1);
97311     pMod->zName = zCopy;
97312     pMod->pModule = pModule;
97313     pMod->pAux = pAux;
97314     pMod->xDestroy = xDestroy;
97315     pDel = (Module *)sqlite3HashInsert(&db->aModule, zCopy, nName, (void*)pMod);
97316     if( pDel && pDel->xDestroy ){
97317       sqlite3ResetInternalSchema(db, -1);
97318       pDel->xDestroy(pDel->pAux);
97319     }
97320     sqlite3DbFree(db, pDel);
97321     if( pDel==pMod ){
97322       db->mallocFailed = 1;
97323     }
97324   }else if( xDestroy ){
97325     xDestroy(pAux);
97326   }
97327   rc = sqlite3ApiExit(db, SQLITE_OK);
97328   sqlite3_mutex_leave(db->mutex);
97329   return rc;
97330 }
97331
97332
97333 /*
97334 ** External API function used to create a new virtual-table module.
97335 */
97336 SQLITE_API int sqlite3_create_module(
97337   sqlite3 *db,                    /* Database in which module is registered */
97338   const char *zName,              /* Name assigned to this module */
97339   const sqlite3_module *pModule,  /* The definition of the module */
97340   void *pAux                      /* Context pointer for xCreate/xConnect */
97341 ){
97342   return createModule(db, zName, pModule, pAux, 0);
97343 }
97344
97345 /*
97346 ** External API function used to create a new virtual-table module.
97347 */
97348 SQLITE_API int sqlite3_create_module_v2(
97349   sqlite3 *db,                    /* Database in which module is registered */
97350   const char *zName,              /* Name assigned to this module */
97351   const sqlite3_module *pModule,  /* The definition of the module */
97352   void *pAux,                     /* Context pointer for xCreate/xConnect */
97353   void (*xDestroy)(void *)        /* Module destructor function */
97354 ){
97355   return createModule(db, zName, pModule, pAux, xDestroy);
97356 }
97357
97358 /*
97359 ** Lock the virtual table so that it cannot be disconnected.
97360 ** Locks nest.  Every lock should have a corresponding unlock.
97361 ** If an unlock is omitted, resources leaks will occur.  
97362 **
97363 ** If a disconnect is attempted while a virtual table is locked,
97364 ** the disconnect is deferred until all locks have been removed.
97365 */
97366 SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
97367   pVTab->nRef++;
97368 }
97369
97370
97371 /*
97372 ** pTab is a pointer to a Table structure representing a virtual-table.
97373 ** Return a pointer to the VTable object used by connection db to access 
97374 ** this virtual-table, if one has been created, or NULL otherwise.
97375 */
97376 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
97377   VTable *pVtab;
97378   assert( IsVirtual(pTab) );
97379   for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
97380   return pVtab;
97381 }
97382
97383 /*
97384 ** Decrement the ref-count on a virtual table object. When the ref-count
97385 ** reaches zero, call the xDisconnect() method to delete the object.
97386 */
97387 SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
97388   sqlite3 *db = pVTab->db;
97389
97390   assert( db );
97391   assert( pVTab->nRef>0 );
97392   assert( sqlite3SafetyCheckOk(db) );
97393
97394   pVTab->nRef--;
97395   if( pVTab->nRef==0 ){
97396     sqlite3_vtab *p = pVTab->pVtab;
97397     if( p ){
97398       p->pModule->xDisconnect(p);
97399     }
97400     sqlite3DbFree(db, pVTab);
97401   }
97402 }
97403
97404 /*
97405 ** Table p is a virtual table. This function moves all elements in the
97406 ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
97407 ** database connections to be disconnected at the next opportunity. 
97408 ** Except, if argument db is not NULL, then the entry associated with
97409 ** connection db is left in the p->pVTable list.
97410 */
97411 static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
97412   VTable *pRet = 0;
97413   VTable *pVTable = p->pVTable;
97414   p->pVTable = 0;
97415
97416   /* Assert that the mutex (if any) associated with the BtShared database 
97417   ** that contains table p is held by the caller. See header comments 
97418   ** above function sqlite3VtabUnlockList() for an explanation of why
97419   ** this makes it safe to access the sqlite3.pDisconnect list of any
97420   ** database connection that may have an entry in the p->pVTable list.
97421   */
97422   assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
97423
97424   while( pVTable ){
97425     sqlite3 *db2 = pVTable->db;
97426     VTable *pNext = pVTable->pNext;
97427     assert( db2 );
97428     if( db2==db ){
97429       pRet = pVTable;
97430       p->pVTable = pRet;
97431       pRet->pNext = 0;
97432     }else{
97433       pVTable->pNext = db2->pDisconnect;
97434       db2->pDisconnect = pVTable;
97435     }
97436     pVTable = pNext;
97437   }
97438
97439   assert( !db || pRet );
97440   return pRet;
97441 }
97442
97443
97444 /*
97445 ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
97446 **
97447 ** This function may only be called when the mutexes associated with all
97448 ** shared b-tree databases opened using connection db are held by the 
97449 ** caller. This is done to protect the sqlite3.pDisconnect list. The
97450 ** sqlite3.pDisconnect list is accessed only as follows:
97451 **
97452 **   1) By this function. In this case, all BtShared mutexes and the mutex
97453 **      associated with the database handle itself must be held.
97454 **
97455 **   2) By function vtabDisconnectAll(), when it adds a VTable entry to
97456 **      the sqlite3.pDisconnect list. In this case either the BtShared mutex
97457 **      associated with the database the virtual table is stored in is held
97458 **      or, if the virtual table is stored in a non-sharable database, then
97459 **      the database handle mutex is held.
97460 **
97461 ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously 
97462 ** by multiple threads. It is thread-safe.
97463 */
97464 SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
97465   VTable *p = db->pDisconnect;
97466   db->pDisconnect = 0;
97467
97468   assert( sqlite3BtreeHoldsAllMutexes(db) );
97469   assert( sqlite3_mutex_held(db->mutex) );
97470
97471   if( p ){
97472     sqlite3ExpirePreparedStatements(db);
97473     do {
97474       VTable *pNext = p->pNext;
97475       sqlite3VtabUnlock(p);
97476       p = pNext;
97477     }while( p );
97478   }
97479 }
97480
97481 /*
97482 ** Clear any and all virtual-table information from the Table record.
97483 ** This routine is called, for example, just before deleting the Table
97484 ** record.
97485 **
97486 ** Since it is a virtual-table, the Table structure contains a pointer
97487 ** to the head of a linked list of VTable structures. Each VTable 
97488 ** structure is associated with a single sqlite3* user of the schema.
97489 ** The reference count of the VTable structure associated with database 
97490 ** connection db is decremented immediately (which may lead to the 
97491 ** structure being xDisconnected and free). Any other VTable structures
97492 ** in the list are moved to the sqlite3.pDisconnect list of the associated 
97493 ** database connection.
97494 */
97495 SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
97496   if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
97497   if( p->azModuleArg ){
97498     int i;
97499     for(i=0; i<p->nModuleArg; i++){
97500       sqlite3DbFree(db, p->azModuleArg[i]);
97501     }
97502     sqlite3DbFree(db, p->azModuleArg);
97503   }
97504 }
97505
97506 /*
97507 ** Add a new module argument to pTable->azModuleArg[].
97508 ** The string is not copied - the pointer is stored.  The
97509 ** string will be freed automatically when the table is
97510 ** deleted.
97511 */
97512 static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
97513   int i = pTable->nModuleArg++;
97514   int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
97515   char **azModuleArg;
97516   azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
97517   if( azModuleArg==0 ){
97518     int j;
97519     for(j=0; j<i; j++){
97520       sqlite3DbFree(db, pTable->azModuleArg[j]);
97521     }
97522     sqlite3DbFree(db, zArg);
97523     sqlite3DbFree(db, pTable->azModuleArg);
97524     pTable->nModuleArg = 0;
97525   }else{
97526     azModuleArg[i] = zArg;
97527     azModuleArg[i+1] = 0;
97528   }
97529   pTable->azModuleArg = azModuleArg;
97530 }
97531
97532 /*
97533 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
97534 ** statement.  The module name has been parsed, but the optional list
97535 ** of parameters that follow the module name are still pending.
97536 */
97537 SQLITE_PRIVATE void sqlite3VtabBeginParse(
97538   Parse *pParse,        /* Parsing context */
97539   Token *pName1,        /* Name of new table, or database name */
97540   Token *pName2,        /* Name of new table or NULL */
97541   Token *pModuleName    /* Name of the module for the virtual table */
97542 ){
97543   int iDb;              /* The database the table is being created in */
97544   Table *pTable;        /* The new virtual table */
97545   sqlite3 *db;          /* Database connection */
97546
97547   sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, 0);
97548   pTable = pParse->pNewTable;
97549   if( pTable==0 ) return;
97550   assert( 0==pTable->pIndex );
97551
97552   db = pParse->db;
97553   iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
97554   assert( iDb>=0 );
97555
97556   pTable->tabFlags |= TF_Virtual;
97557   pTable->nModuleArg = 0;
97558   addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
97559   addModuleArgument(db, pTable, sqlite3DbStrDup(db, db->aDb[iDb].zName));
97560   addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
97561   pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
97562
97563 #ifndef SQLITE_OMIT_AUTHORIZATION
97564   /* Creating a virtual table invokes the authorization callback twice.
97565   ** The first invocation, to obtain permission to INSERT a row into the
97566   ** sqlite_master table, has already been made by sqlite3StartTable().
97567   ** The second call, to obtain permission to create the table, is made now.
97568   */
97569   if( pTable->azModuleArg ){
97570     sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName, 
97571             pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
97572   }
97573 #endif
97574 }
97575
97576 /*
97577 ** This routine takes the module argument that has been accumulating
97578 ** in pParse->zArg[] and appends it to the list of arguments on the
97579 ** virtual table currently under construction in pParse->pTable.
97580 */
97581 static void addArgumentToVtab(Parse *pParse){
97582   if( pParse->sArg.z && ALWAYS(pParse->pNewTable) ){
97583     const char *z = (const char*)pParse->sArg.z;
97584     int n = pParse->sArg.n;
97585     sqlite3 *db = pParse->db;
97586     addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
97587   }
97588 }
97589
97590 /*
97591 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
97592 ** has been completely parsed.
97593 */
97594 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
97595   Table *pTab = pParse->pNewTable;  /* The table being constructed */
97596   sqlite3 *db = pParse->db;         /* The database connection */
97597
97598   if( pTab==0 ) return;
97599   addArgumentToVtab(pParse);
97600   pParse->sArg.z = 0;
97601   if( pTab->nModuleArg<1 ) return;
97602   
97603   /* If the CREATE VIRTUAL TABLE statement is being entered for the
97604   ** first time (in other words if the virtual table is actually being
97605   ** created now instead of just being read out of sqlite_master) then
97606   ** do additional initialization work and store the statement text
97607   ** in the sqlite_master table.
97608   */
97609   if( !db->init.busy ){
97610     char *zStmt;
97611     char *zWhere;
97612     int iDb;
97613     Vdbe *v;
97614
97615     /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
97616     if( pEnd ){
97617       pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
97618     }
97619     zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
97620
97621     /* A slot for the record has already been allocated in the 
97622     ** SQLITE_MASTER table.  We just need to update that slot with all
97623     ** the information we've collected.  
97624     **
97625     ** The VM register number pParse->regRowid holds the rowid of an
97626     ** entry in the sqlite_master table tht was created for this vtab
97627     ** by sqlite3StartTable().
97628     */
97629     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
97630     sqlite3NestedParse(pParse,
97631       "UPDATE %Q.%s "
97632          "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
97633        "WHERE rowid=#%d",
97634       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
97635       pTab->zName,
97636       pTab->zName,
97637       zStmt,
97638       pParse->regRowid
97639     );
97640     sqlite3DbFree(db, zStmt);
97641     v = sqlite3GetVdbe(pParse);
97642     sqlite3ChangeCookie(pParse, iDb);
97643
97644     sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
97645     zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
97646     sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
97647     sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0, 
97648                          pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
97649   }
97650
97651   /* If we are rereading the sqlite_master table create the in-memory
97652   ** record of the table. The xConnect() method is not called until
97653   ** the first time the virtual table is used in an SQL statement. This
97654   ** allows a schema that contains virtual tables to be loaded before
97655   ** the required virtual table implementations are registered.  */
97656   else {
97657     Table *pOld;
97658     Schema *pSchema = pTab->pSchema;
97659     const char *zName = pTab->zName;
97660     int nName = sqlite3Strlen30(zName);
97661     assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
97662     pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
97663     if( pOld ){
97664       db->mallocFailed = 1;
97665       assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
97666       return;
97667     }
97668     pParse->pNewTable = 0;
97669   }
97670 }
97671
97672 /*
97673 ** The parser calls this routine when it sees the first token
97674 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
97675 */
97676 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
97677   addArgumentToVtab(pParse);
97678   pParse->sArg.z = 0;
97679   pParse->sArg.n = 0;
97680 }
97681
97682 /*
97683 ** The parser calls this routine for each token after the first token
97684 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
97685 */
97686 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
97687   Token *pArg = &pParse->sArg;
97688   if( pArg->z==0 ){
97689     pArg->z = p->z;
97690     pArg->n = p->n;
97691   }else{
97692     assert(pArg->z < p->z);
97693     pArg->n = (int)(&p->z[p->n] - pArg->z);
97694   }
97695 }
97696
97697 /*
97698 ** Invoke a virtual table constructor (either xCreate or xConnect). The
97699 ** pointer to the function to invoke is passed as the fourth parameter
97700 ** to this procedure.
97701 */
97702 static int vtabCallConstructor(
97703   sqlite3 *db, 
97704   Table *pTab,
97705   Module *pMod,
97706   int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
97707   char **pzErr
97708 ){
97709   VtabCtx sCtx;
97710   VTable *pVTable;
97711   int rc;
97712   const char *const*azArg = (const char *const*)pTab->azModuleArg;
97713   int nArg = pTab->nModuleArg;
97714   char *zErr = 0;
97715   char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
97716
97717   if( !zModuleName ){
97718     return SQLITE_NOMEM;
97719   }
97720
97721   pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
97722   if( !pVTable ){
97723     sqlite3DbFree(db, zModuleName);
97724     return SQLITE_NOMEM;
97725   }
97726   pVTable->db = db;
97727   pVTable->pMod = pMod;
97728
97729   /* Invoke the virtual table constructor */
97730   assert( &db->pVtabCtx );
97731   assert( xConstruct );
97732   sCtx.pTab = pTab;
97733   sCtx.pVTable = pVTable;
97734   db->pVtabCtx = &sCtx;
97735   rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
97736   db->pVtabCtx = 0;
97737   if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
97738
97739   if( SQLITE_OK!=rc ){
97740     if( zErr==0 ){
97741       *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
97742     }else {
97743       *pzErr = sqlite3MPrintf(db, "%s", zErr);
97744       sqlite3_free(zErr);
97745     }
97746     sqlite3DbFree(db, pVTable);
97747   }else if( ALWAYS(pVTable->pVtab) ){
97748     /* Justification of ALWAYS():  A correct vtab constructor must allocate
97749     ** the sqlite3_vtab object if successful.  */
97750     pVTable->pVtab->pModule = pMod->pModule;
97751     pVTable->nRef = 1;
97752     if( sCtx.pTab ){
97753       const char *zFormat = "vtable constructor did not declare schema: %s";
97754       *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
97755       sqlite3VtabUnlock(pVTable);
97756       rc = SQLITE_ERROR;
97757     }else{
97758       int iCol;
97759       /* If everything went according to plan, link the new VTable structure
97760       ** into the linked list headed by pTab->pVTable. Then loop through the 
97761       ** columns of the table to see if any of them contain the token "hidden".
97762       ** If so, set the Column.isHidden flag and remove the token from
97763       ** the type string.  */
97764       pVTable->pNext = pTab->pVTable;
97765       pTab->pVTable = pVTable;
97766
97767       for(iCol=0; iCol<pTab->nCol; iCol++){
97768         char *zType = pTab->aCol[iCol].zType;
97769         int nType;
97770         int i = 0;
97771         if( !zType ) continue;
97772         nType = sqlite3Strlen30(zType);
97773         if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
97774           for(i=0; i<nType; i++){
97775             if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
97776              && (zType[i+7]=='\0' || zType[i+7]==' ')
97777             ){
97778               i++;
97779               break;
97780             }
97781           }
97782         }
97783         if( i<nType ){
97784           int j;
97785           int nDel = 6 + (zType[i+6] ? 1 : 0);
97786           for(j=i; (j+nDel)<=nType; j++){
97787             zType[j] = zType[j+nDel];
97788           }
97789           if( zType[i]=='\0' && i>0 ){
97790             assert(zType[i-1]==' ');
97791             zType[i-1] = '\0';
97792           }
97793           pTab->aCol[iCol].isHidden = 1;
97794         }
97795       }
97796     }
97797   }
97798
97799   sqlite3DbFree(db, zModuleName);
97800   return rc;
97801 }
97802
97803 /*
97804 ** This function is invoked by the parser to call the xConnect() method
97805 ** of the virtual table pTab. If an error occurs, an error code is returned 
97806 ** and an error left in pParse.
97807 **
97808 ** This call is a no-op if table pTab is not a virtual table.
97809 */
97810 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
97811   sqlite3 *db = pParse->db;
97812   const char *zMod;
97813   Module *pMod;
97814   int rc;
97815
97816   assert( pTab );
97817   if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
97818     return SQLITE_OK;
97819   }
97820
97821   /* Locate the required virtual table module */
97822   zMod = pTab->azModuleArg[0];
97823   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
97824
97825   if( !pMod ){
97826     const char *zModule = pTab->azModuleArg[0];
97827     sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
97828     rc = SQLITE_ERROR;
97829   }else{
97830     char *zErr = 0;
97831     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
97832     if( rc!=SQLITE_OK ){
97833       sqlite3ErrorMsg(pParse, "%s", zErr);
97834     }
97835     sqlite3DbFree(db, zErr);
97836   }
97837
97838   return rc;
97839 }
97840 /*
97841 ** Grow the db->aVTrans[] array so that there is room for at least one
97842 ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
97843 */
97844 static int growVTrans(sqlite3 *db){
97845   const int ARRAY_INCR = 5;
97846
97847   /* Grow the sqlite3.aVTrans array if required */
97848   if( (db->nVTrans%ARRAY_INCR)==0 ){
97849     VTable **aVTrans;
97850     int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
97851     aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
97852     if( !aVTrans ){
97853       return SQLITE_NOMEM;
97854     }
97855     memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
97856     db->aVTrans = aVTrans;
97857   }
97858
97859   return SQLITE_OK;
97860 }
97861
97862 /*
97863 ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
97864 ** have already been reserved using growVTrans().
97865 */
97866 static void addToVTrans(sqlite3 *db, VTable *pVTab){
97867   /* Add pVtab to the end of sqlite3.aVTrans */
97868   db->aVTrans[db->nVTrans++] = pVTab;
97869   sqlite3VtabLock(pVTab);
97870 }
97871
97872 /*
97873 ** This function is invoked by the vdbe to call the xCreate method
97874 ** of the virtual table named zTab in database iDb. 
97875 **
97876 ** If an error occurs, *pzErr is set to point an an English language
97877 ** description of the error and an SQLITE_XXX error code is returned.
97878 ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
97879 */
97880 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
97881   int rc = SQLITE_OK;
97882   Table *pTab;
97883   Module *pMod;
97884   const char *zMod;
97885
97886   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
97887   assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
97888
97889   /* Locate the required virtual table module */
97890   zMod = pTab->azModuleArg[0];
97891   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
97892
97893   /* If the module has been registered and includes a Create method, 
97894   ** invoke it now. If the module has not been registered, return an 
97895   ** error. Otherwise, do nothing.
97896   */
97897   if( !pMod ){
97898     *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
97899     rc = SQLITE_ERROR;
97900   }else{
97901     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
97902   }
97903
97904   /* Justification of ALWAYS():  The xConstructor method is required to
97905   ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
97906   if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
97907     rc = growVTrans(db);
97908     if( rc==SQLITE_OK ){
97909       addToVTrans(db, sqlite3GetVTable(db, pTab));
97910     }
97911   }
97912
97913   return rc;
97914 }
97915
97916 /*
97917 ** This function is used to set the schema of a virtual table.  It is only
97918 ** valid to call this function from within the xCreate() or xConnect() of a
97919 ** virtual table module.
97920 */
97921 SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
97922   Parse *pParse;
97923
97924   int rc = SQLITE_OK;
97925   Table *pTab;
97926   char *zErr = 0;
97927
97928   sqlite3_mutex_enter(db->mutex);
97929   if( !db->pVtabCtx || !(pTab = db->pVtabCtx->pTab) ){
97930     sqlite3Error(db, SQLITE_MISUSE, 0);
97931     sqlite3_mutex_leave(db->mutex);
97932     return SQLITE_MISUSE_BKPT;
97933   }
97934   assert( (pTab->tabFlags & TF_Virtual)!=0 );
97935
97936   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
97937   if( pParse==0 ){
97938     rc = SQLITE_NOMEM;
97939   }else{
97940     pParse->declareVtab = 1;
97941     pParse->db = db;
97942     pParse->nQueryLoop = 1;
97943   
97944     if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr) 
97945      && pParse->pNewTable
97946      && !db->mallocFailed
97947      && !pParse->pNewTable->pSelect
97948      && (pParse->pNewTable->tabFlags & TF_Virtual)==0
97949     ){
97950       if( !pTab->aCol ){
97951         pTab->aCol = pParse->pNewTable->aCol;
97952         pTab->nCol = pParse->pNewTable->nCol;
97953         pParse->pNewTable->nCol = 0;
97954         pParse->pNewTable->aCol = 0;
97955       }
97956       db->pVtabCtx->pTab = 0;
97957     }else{
97958       sqlite3Error(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
97959       sqlite3DbFree(db, zErr);
97960       rc = SQLITE_ERROR;
97961     }
97962     pParse->declareVtab = 0;
97963   
97964     if( pParse->pVdbe ){
97965       sqlite3VdbeFinalize(pParse->pVdbe);
97966     }
97967     sqlite3DeleteTable(db, pParse->pNewTable);
97968     sqlite3StackFree(db, pParse);
97969   }
97970
97971   assert( (rc&0xff)==rc );
97972   rc = sqlite3ApiExit(db, rc);
97973   sqlite3_mutex_leave(db->mutex);
97974   return rc;
97975 }
97976
97977 /*
97978 ** This function is invoked by the vdbe to call the xDestroy method
97979 ** of the virtual table named zTab in database iDb. This occurs
97980 ** when a DROP TABLE is mentioned.
97981 **
97982 ** This call is a no-op if zTab is not a virtual table.
97983 */
97984 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
97985   int rc = SQLITE_OK;
97986   Table *pTab;
97987
97988   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
97989   if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
97990     VTable *p = vtabDisconnectAll(db, pTab);
97991
97992     assert( rc==SQLITE_OK );
97993     rc = p->pMod->pModule->xDestroy(p->pVtab);
97994
97995     /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
97996     if( rc==SQLITE_OK ){
97997       assert( pTab->pVTable==p && p->pNext==0 );
97998       p->pVtab = 0;
97999       pTab->pVTable = 0;
98000       sqlite3VtabUnlock(p);
98001     }
98002   }
98003
98004   return rc;
98005 }
98006
98007 /*
98008 ** This function invokes either the xRollback or xCommit method
98009 ** of each of the virtual tables in the sqlite3.aVTrans array. The method
98010 ** called is identified by the second argument, "offset", which is
98011 ** the offset of the method to call in the sqlite3_module structure.
98012 **
98013 ** The array is cleared after invoking the callbacks. 
98014 */
98015 static void callFinaliser(sqlite3 *db, int offset){
98016   int i;
98017   if( db->aVTrans ){
98018     for(i=0; i<db->nVTrans; i++){
98019       VTable *pVTab = db->aVTrans[i];
98020       sqlite3_vtab *p = pVTab->pVtab;
98021       if( p ){
98022         int (*x)(sqlite3_vtab *);
98023         x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
98024         if( x ) x(p);
98025       }
98026       pVTab->iSavepoint = 0;
98027       sqlite3VtabUnlock(pVTab);
98028     }
98029     sqlite3DbFree(db, db->aVTrans);
98030     db->nVTrans = 0;
98031     db->aVTrans = 0;
98032   }
98033 }
98034
98035 /*
98036 ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
98037 ** array. Return the error code for the first error that occurs, or
98038 ** SQLITE_OK if all xSync operations are successful.
98039 **
98040 ** Set *pzErrmsg to point to a buffer that should be released using 
98041 ** sqlite3DbFree() containing an error message, if one is available.
98042 */
98043 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **pzErrmsg){
98044   int i;
98045   int rc = SQLITE_OK;
98046   VTable **aVTrans = db->aVTrans;
98047
98048   db->aVTrans = 0;
98049   for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
98050     int (*x)(sqlite3_vtab *);
98051     sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
98052     if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
98053       rc = x(pVtab);
98054       sqlite3DbFree(db, *pzErrmsg);
98055       *pzErrmsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
98056       sqlite3_free(pVtab->zErrMsg);
98057     }
98058   }
98059   db->aVTrans = aVTrans;
98060   return rc;
98061 }
98062
98063 /*
98064 ** Invoke the xRollback method of all virtual tables in the 
98065 ** sqlite3.aVTrans array. Then clear the array itself.
98066 */
98067 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
98068   callFinaliser(db, offsetof(sqlite3_module,xRollback));
98069   return SQLITE_OK;
98070 }
98071
98072 /*
98073 ** Invoke the xCommit method of all virtual tables in the 
98074 ** sqlite3.aVTrans array. Then clear the array itself.
98075 */
98076 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
98077   callFinaliser(db, offsetof(sqlite3_module,xCommit));
98078   return SQLITE_OK;
98079 }
98080
98081 /*
98082 ** If the virtual table pVtab supports the transaction interface
98083 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
98084 ** not currently open, invoke the xBegin method now.
98085 **
98086 ** If the xBegin call is successful, place the sqlite3_vtab pointer
98087 ** in the sqlite3.aVTrans array.
98088 */
98089 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
98090   int rc = SQLITE_OK;
98091   const sqlite3_module *pModule;
98092
98093   /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
98094   ** than zero, then this function is being called from within a
98095   ** virtual module xSync() callback. It is illegal to write to 
98096   ** virtual module tables in this case, so return SQLITE_LOCKED.
98097   */
98098   if( sqlite3VtabInSync(db) ){
98099     return SQLITE_LOCKED;
98100   }
98101   if( !pVTab ){
98102     return SQLITE_OK;
98103   } 
98104   pModule = pVTab->pVtab->pModule;
98105
98106   if( pModule->xBegin ){
98107     int i;
98108
98109     /* If pVtab is already in the aVTrans array, return early */
98110     for(i=0; i<db->nVTrans; i++){
98111       if( db->aVTrans[i]==pVTab ){
98112         return SQLITE_OK;
98113       }
98114     }
98115
98116     /* Invoke the xBegin method. If successful, add the vtab to the 
98117     ** sqlite3.aVTrans[] array. */
98118     rc = growVTrans(db);
98119     if( rc==SQLITE_OK ){
98120       rc = pModule->xBegin(pVTab->pVtab);
98121       if( rc==SQLITE_OK ){
98122         addToVTrans(db, pVTab);
98123       }
98124     }
98125   }
98126   return rc;
98127 }
98128
98129 /*
98130 ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
98131 ** virtual tables that currently have an open transaction. Pass iSavepoint
98132 ** as the second argument to the virtual table method invoked.
98133 **
98134 ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
98135 ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is 
98136 ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
98137 ** an open transaction is invoked.
98138 **
98139 ** If any virtual table method returns an error code other than SQLITE_OK, 
98140 ** processing is abandoned and the error returned to the caller of this
98141 ** function immediately. If all calls to virtual table methods are successful,
98142 ** SQLITE_OK is returned.
98143 */
98144 SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
98145   int rc = SQLITE_OK;
98146
98147   assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
98148   assert( iSavepoint>=0 );
98149   if( db->aVTrans ){
98150     int i;
98151     for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
98152       VTable *pVTab = db->aVTrans[i];
98153       const sqlite3_module *pMod = pVTab->pMod->pModule;
98154       if( pMod->iVersion>=2 ){
98155         int (*xMethod)(sqlite3_vtab *, int);
98156         switch( op ){
98157           case SAVEPOINT_BEGIN:
98158             xMethod = pMod->xSavepoint;
98159             pVTab->iSavepoint = iSavepoint+1;
98160             break;
98161           case SAVEPOINT_ROLLBACK:
98162             xMethod = pMod->xRollbackTo;
98163             break;
98164           default:
98165             xMethod = pMod->xRelease;
98166             break;
98167         }
98168         if( xMethod && pVTab->iSavepoint>iSavepoint ){
98169           rc = xMethod(db->aVTrans[i]->pVtab, iSavepoint);
98170         }
98171       }
98172     }
98173   }
98174   return rc;
98175 }
98176
98177 /*
98178 ** The first parameter (pDef) is a function implementation.  The
98179 ** second parameter (pExpr) is the first argument to this function.
98180 ** If pExpr is a column in a virtual table, then let the virtual
98181 ** table implementation have an opportunity to overload the function.
98182 **
98183 ** This routine is used to allow virtual table implementations to
98184 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
98185 **
98186 ** Return either the pDef argument (indicating no change) or a 
98187 ** new FuncDef structure that is marked as ephemeral using the
98188 ** SQLITE_FUNC_EPHEM flag.
98189 */
98190 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
98191   sqlite3 *db,    /* Database connection for reporting malloc problems */
98192   FuncDef *pDef,  /* Function to possibly overload */
98193   int nArg,       /* Number of arguments to the function */
98194   Expr *pExpr     /* First argument to the function */
98195 ){
98196   Table *pTab;
98197   sqlite3_vtab *pVtab;
98198   sqlite3_module *pMod;
98199   void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
98200   void *pArg = 0;
98201   FuncDef *pNew;
98202   int rc = 0;
98203   char *zLowerName;
98204   unsigned char *z;
98205
98206
98207   /* Check to see the left operand is a column in a virtual table */
98208   if( NEVER(pExpr==0) ) return pDef;
98209   if( pExpr->op!=TK_COLUMN ) return pDef;
98210   pTab = pExpr->pTab;
98211   if( NEVER(pTab==0) ) return pDef;
98212   if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
98213   pVtab = sqlite3GetVTable(db, pTab)->pVtab;
98214   assert( pVtab!=0 );
98215   assert( pVtab->pModule!=0 );
98216   pMod = (sqlite3_module *)pVtab->pModule;
98217   if( pMod->xFindFunction==0 ) return pDef;
98218  
98219   /* Call the xFindFunction method on the virtual table implementation
98220   ** to see if the implementation wants to overload this function 
98221   */
98222   zLowerName = sqlite3DbStrDup(db, pDef->zName);
98223   if( zLowerName ){
98224     for(z=(unsigned char*)zLowerName; *z; z++){
98225       *z = sqlite3UpperToLower[*z];
98226     }
98227     rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
98228     sqlite3DbFree(db, zLowerName);
98229   }
98230   if( rc==0 ){
98231     return pDef;
98232   }
98233
98234   /* Create a new ephemeral function definition for the overloaded
98235   ** function */
98236   pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
98237                              + sqlite3Strlen30(pDef->zName) + 1);
98238   if( pNew==0 ){
98239     return pDef;
98240   }
98241   *pNew = *pDef;
98242   pNew->zName = (char *)&pNew[1];
98243   memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
98244   pNew->xFunc = xFunc;
98245   pNew->pUserData = pArg;
98246   pNew->flags |= SQLITE_FUNC_EPHEM;
98247   return pNew;
98248 }
98249
98250 /*
98251 ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
98252 ** array so that an OP_VBegin will get generated for it.  Add pTab to the
98253 ** array if it is missing.  If pTab is already in the array, this routine
98254 ** is a no-op.
98255 */
98256 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
98257   Parse *pToplevel = sqlite3ParseToplevel(pParse);
98258   int i, n;
98259   Table **apVtabLock;
98260
98261   assert( IsVirtual(pTab) );
98262   for(i=0; i<pToplevel->nVtabLock; i++){
98263     if( pTab==pToplevel->apVtabLock[i] ) return;
98264   }
98265   n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
98266   apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
98267   if( apVtabLock ){
98268     pToplevel->apVtabLock = apVtabLock;
98269     pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
98270   }else{
98271     pToplevel->db->mallocFailed = 1;
98272   }
98273 }
98274
98275 /*
98276 ** Return the ON CONFLICT resolution mode in effect for the virtual
98277 ** table update operation currently in progress.
98278 **
98279 ** The results of this routine are undefined unless it is called from
98280 ** within an xUpdate method.
98281 */
98282 SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
98283   static const unsigned char aMap[] = { 
98284     SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE 
98285   };
98286   assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
98287   assert( OE_Ignore==4 && OE_Replace==5 );
98288   assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
98289   return (int)aMap[db->vtabOnConflict-1];
98290 }
98291
98292 /*
98293 ** Call from within the xCreate() or xConnect() methods to provide 
98294 ** the SQLite core with additional information about the behavior
98295 ** of the virtual table being implemented.
98296 */
98297 SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
98298   va_list ap;
98299   int rc = SQLITE_OK;
98300
98301   sqlite3_mutex_enter(db->mutex);
98302
98303   va_start(ap, op);
98304   switch( op ){
98305     case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
98306       VtabCtx *p = db->pVtabCtx;
98307       if( !p ){
98308         rc = SQLITE_MISUSE_BKPT;
98309       }else{
98310         assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
98311         p->pVTable->bConstraint = (u8)va_arg(ap, int);
98312       }
98313       break;
98314     }
98315     default:
98316       rc = SQLITE_MISUSE_BKPT;
98317       break;
98318   }
98319   va_end(ap);
98320
98321   if( rc!=SQLITE_OK ) sqlite3Error(db, rc, 0);
98322   sqlite3_mutex_leave(db->mutex);
98323   return rc;
98324 }
98325
98326 #endif /* SQLITE_OMIT_VIRTUALTABLE */
98327
98328 /************** End of vtab.c ************************************************/
98329 /************** Begin file where.c *******************************************/
98330 /*
98331 ** 2001 September 15
98332 **
98333 ** The author disclaims copyright to this source code.  In place of
98334 ** a legal notice, here is a blessing:
98335 **
98336 **    May you do good and not evil.
98337 **    May you find forgiveness for yourself and forgive others.
98338 **    May you share freely, never taking more than you give.
98339 **
98340 *************************************************************************
98341 ** This module contains C code that generates VDBE code used to process
98342 ** the WHERE clause of SQL statements.  This module is responsible for
98343 ** generating the code that loops through a table looking for applicable
98344 ** rows.  Indices are selected and used to speed the search when doing
98345 ** so is applicable.  Because this module is responsible for selecting
98346 ** indices, you might also think of this module as the "query optimizer".
98347 */
98348
98349
98350 /*
98351 ** Trace output macros
98352 */
98353 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
98354 SQLITE_PRIVATE int sqlite3WhereTrace = 0;
98355 #endif
98356 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
98357 # define WHERETRACE(X)  if(sqlite3WhereTrace) sqlite3DebugPrintf X
98358 #else
98359 # define WHERETRACE(X)
98360 #endif
98361
98362 /* Forward reference
98363 */
98364 typedef struct WhereClause WhereClause;
98365 typedef struct WhereMaskSet WhereMaskSet;
98366 typedef struct WhereOrInfo WhereOrInfo;
98367 typedef struct WhereAndInfo WhereAndInfo;
98368 typedef struct WhereCost WhereCost;
98369
98370 /*
98371 ** The query generator uses an array of instances of this structure to
98372 ** help it analyze the subexpressions of the WHERE clause.  Each WHERE
98373 ** clause subexpression is separated from the others by AND operators,
98374 ** usually, or sometimes subexpressions separated by OR.
98375 **
98376 ** All WhereTerms are collected into a single WhereClause structure.  
98377 ** The following identity holds:
98378 **
98379 **        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
98380 **
98381 ** When a term is of the form:
98382 **
98383 **              X <op> <expr>
98384 **
98385 ** where X is a column name and <op> is one of certain operators,
98386 ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
98387 ** cursor number and column number for X.  WhereTerm.eOperator records
98388 ** the <op> using a bitmask encoding defined by WO_xxx below.  The
98389 ** use of a bitmask encoding for the operator allows us to search
98390 ** quickly for terms that match any of several different operators.
98391 **
98392 ** A WhereTerm might also be two or more subterms connected by OR:
98393 **
98394 **         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
98395 **
98396 ** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
98397 ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
98398 ** is collected about the
98399 **
98400 ** If a term in the WHERE clause does not match either of the two previous
98401 ** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
98402 ** to the original subexpression content and wtFlags is set up appropriately
98403 ** but no other fields in the WhereTerm object are meaningful.
98404 **
98405 ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
98406 ** but they do so indirectly.  A single WhereMaskSet structure translates
98407 ** cursor number into bits and the translated bit is stored in the prereq
98408 ** fields.  The translation is used in order to maximize the number of
98409 ** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
98410 ** spread out over the non-negative integers.  For example, the cursor
98411 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
98412 ** translates these sparse cursor numbers into consecutive integers
98413 ** beginning with 0 in order to make the best possible use of the available
98414 ** bits in the Bitmask.  So, in the example above, the cursor numbers
98415 ** would be mapped into integers 0 through 7.
98416 **
98417 ** The number of terms in a join is limited by the number of bits
98418 ** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
98419 ** is only able to process joins with 64 or fewer tables.
98420 */
98421 typedef struct WhereTerm WhereTerm;
98422 struct WhereTerm {
98423   Expr *pExpr;            /* Pointer to the subexpression that is this term */
98424   int iParent;            /* Disable pWC->a[iParent] when this term disabled */
98425   int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
98426   union {
98427     int leftColumn;         /* Column number of X in "X <op> <expr>" */
98428     WhereOrInfo *pOrInfo;   /* Extra information if eOperator==WO_OR */
98429     WhereAndInfo *pAndInfo; /* Extra information if eOperator==WO_AND */
98430   } u;
98431   u16 eOperator;          /* A WO_xx value describing <op> */
98432   u8 wtFlags;             /* TERM_xxx bit flags.  See below */
98433   u8 nChild;              /* Number of children that must disable us */
98434   WhereClause *pWC;       /* The clause this term is part of */
98435   Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
98436   Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
98437 };
98438
98439 /*
98440 ** Allowed values of WhereTerm.wtFlags
98441 */
98442 #define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
98443 #define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
98444 #define TERM_CODED      0x04   /* This term is already coded */
98445 #define TERM_COPIED     0x08   /* Has a child */
98446 #define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
98447 #define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
98448 #define TERM_OR_OK      0x40   /* Used during OR-clause processing */
98449 #ifdef SQLITE_ENABLE_STAT2
98450 #  define TERM_VNULL    0x80   /* Manufactured x>NULL or x<=NULL term */
98451 #else
98452 #  define TERM_VNULL    0x00   /* Disabled if not using stat2 */
98453 #endif
98454
98455 /*
98456 ** An instance of the following structure holds all information about a
98457 ** WHERE clause.  Mostly this is a container for one or more WhereTerms.
98458 */
98459 struct WhereClause {
98460   Parse *pParse;           /* The parser context */
98461   WhereMaskSet *pMaskSet;  /* Mapping of table cursor numbers to bitmasks */
98462   Bitmask vmask;           /* Bitmask identifying virtual table cursors */
98463   u8 op;                   /* Split operator.  TK_AND or TK_OR */
98464   int nTerm;               /* Number of terms */
98465   int nSlot;               /* Number of entries in a[] */
98466   WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
98467 #if defined(SQLITE_SMALL_STACK)
98468   WhereTerm aStatic[1];    /* Initial static space for a[] */
98469 #else
98470   WhereTerm aStatic[8];    /* Initial static space for a[] */
98471 #endif
98472 };
98473
98474 /*
98475 ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
98476 ** a dynamically allocated instance of the following structure.
98477 */
98478 struct WhereOrInfo {
98479   WhereClause wc;          /* Decomposition into subterms */
98480   Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
98481 };
98482
98483 /*
98484 ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
98485 ** a dynamically allocated instance of the following structure.
98486 */
98487 struct WhereAndInfo {
98488   WhereClause wc;          /* The subexpression broken out */
98489 };
98490
98491 /*
98492 ** An instance of the following structure keeps track of a mapping
98493 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
98494 **
98495 ** The VDBE cursor numbers are small integers contained in 
98496 ** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE 
98497 ** clause, the cursor numbers might not begin with 0 and they might
98498 ** contain gaps in the numbering sequence.  But we want to make maximum
98499 ** use of the bits in our bitmasks.  This structure provides a mapping
98500 ** from the sparse cursor numbers into consecutive integers beginning
98501 ** with 0.
98502 **
98503 ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
98504 ** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
98505 **
98506 ** For example, if the WHERE clause expression used these VDBE
98507 ** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
98508 ** would map those cursor numbers into bits 0 through 5.
98509 **
98510 ** Note that the mapping is not necessarily ordered.  In the example
98511 ** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
98512 ** 57->5, 73->4.  Or one of 719 other combinations might be used. It
98513 ** does not really matter.  What is important is that sparse cursor
98514 ** numbers all get mapped into bit numbers that begin with 0 and contain
98515 ** no gaps.
98516 */
98517 struct WhereMaskSet {
98518   int n;                        /* Number of assigned cursor values */
98519   int ix[BMS];                  /* Cursor assigned to each bit */
98520 };
98521
98522 /*
98523 ** A WhereCost object records a lookup strategy and the estimated
98524 ** cost of pursuing that strategy.
98525 */
98526 struct WhereCost {
98527   WherePlan plan;    /* The lookup strategy */
98528   double rCost;      /* Overall cost of pursuing this search strategy */
98529   Bitmask used;      /* Bitmask of cursors used by this plan */
98530 };
98531
98532 /*
98533 ** Bitmasks for the operators that indices are able to exploit.  An
98534 ** OR-ed combination of these values can be used when searching for
98535 ** terms in the where clause.
98536 */
98537 #define WO_IN     0x001
98538 #define WO_EQ     0x002
98539 #define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
98540 #define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
98541 #define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
98542 #define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
98543 #define WO_MATCH  0x040
98544 #define WO_ISNULL 0x080
98545 #define WO_OR     0x100       /* Two or more OR-connected terms */
98546 #define WO_AND    0x200       /* Two or more AND-connected terms */
98547 #define WO_NOOP   0x800       /* This term does not restrict search space */
98548
98549 #define WO_ALL    0xfff       /* Mask of all possible WO_* values */
98550 #define WO_SINGLE 0x0ff       /* Mask of all non-compound WO_* values */
98551
98552 /*
98553 ** Value for wsFlags returned by bestIndex() and stored in
98554 ** WhereLevel.wsFlags.  These flags determine which search
98555 ** strategies are appropriate.
98556 **
98557 ** The least significant 12 bits is reserved as a mask for WO_ values above.
98558 ** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
98559 ** But if the table is the right table of a left join, WhereLevel.wsFlags
98560 ** is set to WO_IN|WO_EQ.  The WhereLevel.wsFlags field can then be used as
98561 ** the "op" parameter to findTerm when we are resolving equality constraints.
98562 ** ISNULL constraints will then not be used on the right table of a left
98563 ** join.  Tickets #2177 and #2189.
98564 */
98565 #define WHERE_ROWID_EQ     0x00001000  /* rowid=EXPR or rowid IN (...) */
98566 #define WHERE_ROWID_RANGE  0x00002000  /* rowid<EXPR and/or rowid>EXPR */
98567 #define WHERE_COLUMN_EQ    0x00010000  /* x=EXPR or x IN (...) or x IS NULL */
98568 #define WHERE_COLUMN_RANGE 0x00020000  /* x<EXPR and/or x>EXPR */
98569 #define WHERE_COLUMN_IN    0x00040000  /* x IN (...) */
98570 #define WHERE_COLUMN_NULL  0x00080000  /* x IS NULL */
98571 #define WHERE_INDEXED      0x000f0000  /* Anything that uses an index */
98572 #define WHERE_NOT_FULLSCAN 0x100f3000  /* Does not do a full table scan */
98573 #define WHERE_IN_ABLE      0x000f1000  /* Able to support an IN operator */
98574 #define WHERE_TOP_LIMIT    0x00100000  /* x<EXPR or x<=EXPR constraint */
98575 #define WHERE_BTM_LIMIT    0x00200000  /* x>EXPR or x>=EXPR constraint */
98576 #define WHERE_BOTH_LIMIT   0x00300000  /* Both x>EXPR and x<EXPR */
98577 #define WHERE_IDX_ONLY     0x00800000  /* Use index only - omit table */
98578 #define WHERE_ORDERBY      0x01000000  /* Output will appear in correct order */
98579 #define WHERE_REVERSE      0x02000000  /* Scan in reverse order */
98580 #define WHERE_UNIQUE       0x04000000  /* Selects no more than one row */
98581 #define WHERE_VIRTUALTABLE 0x08000000  /* Use virtual-table processing */
98582 #define WHERE_MULTI_OR     0x10000000  /* OR using multiple indices */
98583 #define WHERE_TEMP_INDEX   0x20000000  /* Uses an ephemeral index */
98584
98585 /*
98586 ** Initialize a preallocated WhereClause structure.
98587 */
98588 static void whereClauseInit(
98589   WhereClause *pWC,        /* The WhereClause to be initialized */
98590   Parse *pParse,           /* The parsing context */
98591   WhereMaskSet *pMaskSet   /* Mapping from table cursor numbers to bitmasks */
98592 ){
98593   pWC->pParse = pParse;
98594   pWC->pMaskSet = pMaskSet;
98595   pWC->nTerm = 0;
98596   pWC->nSlot = ArraySize(pWC->aStatic);
98597   pWC->a = pWC->aStatic;
98598   pWC->vmask = 0;
98599 }
98600
98601 /* Forward reference */
98602 static void whereClauseClear(WhereClause*);
98603
98604 /*
98605 ** Deallocate all memory associated with a WhereOrInfo object.
98606 */
98607 static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
98608   whereClauseClear(&p->wc);
98609   sqlite3DbFree(db, p);
98610 }
98611
98612 /*
98613 ** Deallocate all memory associated with a WhereAndInfo object.
98614 */
98615 static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
98616   whereClauseClear(&p->wc);
98617   sqlite3DbFree(db, p);
98618 }
98619
98620 /*
98621 ** Deallocate a WhereClause structure.  The WhereClause structure
98622 ** itself is not freed.  This routine is the inverse of whereClauseInit().
98623 */
98624 static void whereClauseClear(WhereClause *pWC){
98625   int i;
98626   WhereTerm *a;
98627   sqlite3 *db = pWC->pParse->db;
98628   for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
98629     if( a->wtFlags & TERM_DYNAMIC ){
98630       sqlite3ExprDelete(db, a->pExpr);
98631     }
98632     if( a->wtFlags & TERM_ORINFO ){
98633       whereOrInfoDelete(db, a->u.pOrInfo);
98634     }else if( a->wtFlags & TERM_ANDINFO ){
98635       whereAndInfoDelete(db, a->u.pAndInfo);
98636     }
98637   }
98638   if( pWC->a!=pWC->aStatic ){
98639     sqlite3DbFree(db, pWC->a);
98640   }
98641 }
98642
98643 /*
98644 ** Add a single new WhereTerm entry to the WhereClause object pWC.
98645 ** The new WhereTerm object is constructed from Expr p and with wtFlags.
98646 ** The index in pWC->a[] of the new WhereTerm is returned on success.
98647 ** 0 is returned if the new WhereTerm could not be added due to a memory
98648 ** allocation error.  The memory allocation failure will be recorded in
98649 ** the db->mallocFailed flag so that higher-level functions can detect it.
98650 **
98651 ** This routine will increase the size of the pWC->a[] array as necessary.
98652 **
98653 ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
98654 ** for freeing the expression p is assumed by the WhereClause object pWC.
98655 ** This is true even if this routine fails to allocate a new WhereTerm.
98656 **
98657 ** WARNING:  This routine might reallocate the space used to store
98658 ** WhereTerms.  All pointers to WhereTerms should be invalidated after
98659 ** calling this routine.  Such pointers may be reinitialized by referencing
98660 ** the pWC->a[] array.
98661 */
98662 static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
98663   WhereTerm *pTerm;
98664   int idx;
98665   testcase( wtFlags & TERM_VIRTUAL );  /* EV: R-00211-15100 */
98666   if( pWC->nTerm>=pWC->nSlot ){
98667     WhereTerm *pOld = pWC->a;
98668     sqlite3 *db = pWC->pParse->db;
98669     pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
98670     if( pWC->a==0 ){
98671       if( wtFlags & TERM_DYNAMIC ){
98672         sqlite3ExprDelete(db, p);
98673       }
98674       pWC->a = pOld;
98675       return 0;
98676     }
98677     memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
98678     if( pOld!=pWC->aStatic ){
98679       sqlite3DbFree(db, pOld);
98680     }
98681     pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
98682   }
98683   pTerm = &pWC->a[idx = pWC->nTerm++];
98684   pTerm->pExpr = p;
98685   pTerm->wtFlags = wtFlags;
98686   pTerm->pWC = pWC;
98687   pTerm->iParent = -1;
98688   return idx;
98689 }
98690
98691 /*
98692 ** This routine identifies subexpressions in the WHERE clause where
98693 ** each subexpression is separated by the AND operator or some other
98694 ** operator specified in the op parameter.  The WhereClause structure
98695 ** is filled with pointers to subexpressions.  For example:
98696 **
98697 **    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
98698 **           \________/     \_______________/     \________________/
98699 **            slot[0]            slot[1]               slot[2]
98700 **
98701 ** The original WHERE clause in pExpr is unaltered.  All this routine
98702 ** does is make slot[] entries point to substructure within pExpr.
98703 **
98704 ** In the previous sentence and in the diagram, "slot[]" refers to
98705 ** the WhereClause.a[] array.  The slot[] array grows as needed to contain
98706 ** all terms of the WHERE clause.
98707 */
98708 static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
98709   pWC->op = (u8)op;
98710   if( pExpr==0 ) return;
98711   if( pExpr->op!=op ){
98712     whereClauseInsert(pWC, pExpr, 0);
98713   }else{
98714     whereSplit(pWC, pExpr->pLeft, op);
98715     whereSplit(pWC, pExpr->pRight, op);
98716   }
98717 }
98718
98719 /*
98720 ** Initialize an expression mask set (a WhereMaskSet object)
98721 */
98722 #define initMaskSet(P)  memset(P, 0, sizeof(*P))
98723
98724 /*
98725 ** Return the bitmask for the given cursor number.  Return 0 if
98726 ** iCursor is not in the set.
98727 */
98728 static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
98729   int i;
98730   assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
98731   for(i=0; i<pMaskSet->n; i++){
98732     if( pMaskSet->ix[i]==iCursor ){
98733       return ((Bitmask)1)<<i;
98734     }
98735   }
98736   return 0;
98737 }
98738
98739 /*
98740 ** Create a new mask for cursor iCursor.
98741 **
98742 ** There is one cursor per table in the FROM clause.  The number of
98743 ** tables in the FROM clause is limited by a test early in the
98744 ** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
98745 ** array will never overflow.
98746 */
98747 static void createMask(WhereMaskSet *pMaskSet, int iCursor){
98748   assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
98749   pMaskSet->ix[pMaskSet->n++] = iCursor;
98750 }
98751
98752 /*
98753 ** This routine walks (recursively) an expression tree and generates
98754 ** a bitmask indicating which tables are used in that expression
98755 ** tree.
98756 **
98757 ** In order for this routine to work, the calling function must have
98758 ** previously invoked sqlite3ResolveExprNames() on the expression.  See
98759 ** the header comment on that routine for additional information.
98760 ** The sqlite3ResolveExprNames() routines looks for column names and
98761 ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
98762 ** the VDBE cursor number of the table.  This routine just has to
98763 ** translate the cursor numbers into bitmask values and OR all
98764 ** the bitmasks together.
98765 */
98766 static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
98767 static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
98768 static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
98769   Bitmask mask = 0;
98770   if( p==0 ) return 0;
98771   if( p->op==TK_COLUMN ){
98772     mask = getMask(pMaskSet, p->iTable);
98773     return mask;
98774   }
98775   mask = exprTableUsage(pMaskSet, p->pRight);
98776   mask |= exprTableUsage(pMaskSet, p->pLeft);
98777   if( ExprHasProperty(p, EP_xIsSelect) ){
98778     mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
98779   }else{
98780     mask |= exprListTableUsage(pMaskSet, p->x.pList);
98781   }
98782   return mask;
98783 }
98784 static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
98785   int i;
98786   Bitmask mask = 0;
98787   if( pList ){
98788     for(i=0; i<pList->nExpr; i++){
98789       mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
98790     }
98791   }
98792   return mask;
98793 }
98794 static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
98795   Bitmask mask = 0;
98796   while( pS ){
98797     mask |= exprListTableUsage(pMaskSet, pS->pEList);
98798     mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
98799     mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
98800     mask |= exprTableUsage(pMaskSet, pS->pWhere);
98801     mask |= exprTableUsage(pMaskSet, pS->pHaving);
98802     pS = pS->pPrior;
98803   }
98804   return mask;
98805 }
98806
98807 /*
98808 ** Return TRUE if the given operator is one of the operators that is
98809 ** allowed for an indexable WHERE clause term.  The allowed operators are
98810 ** "=", "<", ">", "<=", ">=", and "IN".
98811 **
98812 ** IMPLEMENTATION-OF: R-59926-26393 To be usable by an index a term must be
98813 ** of one of the following forms: column = expression column > expression
98814 ** column >= expression column < expression column <= expression
98815 ** expression = column expression > column expression >= column
98816 ** expression < column expression <= column column IN
98817 ** (expression-list) column IN (subquery) column IS NULL
98818 */
98819 static int allowedOp(int op){
98820   assert( TK_GT>TK_EQ && TK_GT<TK_GE );
98821   assert( TK_LT>TK_EQ && TK_LT<TK_GE );
98822   assert( TK_LE>TK_EQ && TK_LE<TK_GE );
98823   assert( TK_GE==TK_EQ+4 );
98824   return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
98825 }
98826
98827 /*
98828 ** Swap two objects of type TYPE.
98829 */
98830 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
98831
98832 /*
98833 ** Commute a comparison operator.  Expressions of the form "X op Y"
98834 ** are converted into "Y op X".
98835 **
98836 ** If a collation sequence is associated with either the left or right
98837 ** side of the comparison, it remains associated with the same side after
98838 ** the commutation. So "Y collate NOCASE op X" becomes 
98839 ** "X collate NOCASE op Y". This is because any collation sequence on
98840 ** the left hand side of a comparison overrides any collation sequence 
98841 ** attached to the right. For the same reason the EP_ExpCollate flag
98842 ** is not commuted.
98843 */
98844 static void exprCommute(Parse *pParse, Expr *pExpr){
98845   u16 expRight = (pExpr->pRight->flags & EP_ExpCollate);
98846   u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate);
98847   assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
98848   pExpr->pRight->pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
98849   pExpr->pLeft->pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
98850   SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
98851   pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft;
98852   pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight;
98853   SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
98854   if( pExpr->op>=TK_GT ){
98855     assert( TK_LT==TK_GT+2 );
98856     assert( TK_GE==TK_LE+2 );
98857     assert( TK_GT>TK_EQ );
98858     assert( TK_GT<TK_LE );
98859     assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
98860     pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
98861   }
98862 }
98863
98864 /*
98865 ** Translate from TK_xx operator to WO_xx bitmask.
98866 */
98867 static u16 operatorMask(int op){
98868   u16 c;
98869   assert( allowedOp(op) );
98870   if( op==TK_IN ){
98871     c = WO_IN;
98872   }else if( op==TK_ISNULL ){
98873     c = WO_ISNULL;
98874   }else{
98875     assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
98876     c = (u16)(WO_EQ<<(op-TK_EQ));
98877   }
98878   assert( op!=TK_ISNULL || c==WO_ISNULL );
98879   assert( op!=TK_IN || c==WO_IN );
98880   assert( op!=TK_EQ || c==WO_EQ );
98881   assert( op!=TK_LT || c==WO_LT );
98882   assert( op!=TK_LE || c==WO_LE );
98883   assert( op!=TK_GT || c==WO_GT );
98884   assert( op!=TK_GE || c==WO_GE );
98885   return c;
98886 }
98887
98888 /*
98889 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
98890 ** where X is a reference to the iColumn of table iCur and <op> is one of
98891 ** the WO_xx operator codes specified by the op parameter.
98892 ** Return a pointer to the term.  Return 0 if not found.
98893 */
98894 static WhereTerm *findTerm(
98895   WhereClause *pWC,     /* The WHERE clause to be searched */
98896   int iCur,             /* Cursor number of LHS */
98897   int iColumn,          /* Column number of LHS */
98898   Bitmask notReady,     /* RHS must not overlap with this mask */
98899   u32 op,               /* Mask of WO_xx values describing operator */
98900   Index *pIdx           /* Must be compatible with this index, if not NULL */
98901 ){
98902   WhereTerm *pTerm;
98903   int k;
98904   assert( iCur>=0 );
98905   op &= WO_ALL;
98906   for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
98907     if( pTerm->leftCursor==iCur
98908        && (pTerm->prereqRight & notReady)==0
98909        && pTerm->u.leftColumn==iColumn
98910        && (pTerm->eOperator & op)!=0
98911     ){
98912       if( pIdx && pTerm->eOperator!=WO_ISNULL ){
98913         Expr *pX = pTerm->pExpr;
98914         CollSeq *pColl;
98915         char idxaff;
98916         int j;
98917         Parse *pParse = pWC->pParse;
98918
98919         idxaff = pIdx->pTable->aCol[iColumn].affinity;
98920         if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
98921
98922         /* Figure out the collation sequence required from an index for
98923         ** it to be useful for optimising expression pX. Store this
98924         ** value in variable pColl.
98925         */
98926         assert(pX->pLeft);
98927         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
98928         assert(pColl || pParse->nErr);
98929
98930         for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
98931           if( NEVER(j>=pIdx->nColumn) ) return 0;
98932         }
98933         if( pColl && sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
98934       }
98935       return pTerm;
98936     }
98937   }
98938   return 0;
98939 }
98940
98941 /* Forward reference */
98942 static void exprAnalyze(SrcList*, WhereClause*, int);
98943
98944 /*
98945 ** Call exprAnalyze on all terms in a WHERE clause.  
98946 **
98947 **
98948 */
98949 static void exprAnalyzeAll(
98950   SrcList *pTabList,       /* the FROM clause */
98951   WhereClause *pWC         /* the WHERE clause to be analyzed */
98952 ){
98953   int i;
98954   for(i=pWC->nTerm-1; i>=0; i--){
98955     exprAnalyze(pTabList, pWC, i);
98956   }
98957 }
98958
98959 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
98960 /*
98961 ** Check to see if the given expression is a LIKE or GLOB operator that
98962 ** can be optimized using inequality constraints.  Return TRUE if it is
98963 ** so and false if not.
98964 **
98965 ** In order for the operator to be optimizible, the RHS must be a string
98966 ** literal that does not begin with a wildcard.  
98967 */
98968 static int isLikeOrGlob(
98969   Parse *pParse,    /* Parsing and code generating context */
98970   Expr *pExpr,      /* Test this expression */
98971   Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
98972   int *pisComplete, /* True if the only wildcard is % in the last character */
98973   int *pnoCase      /* True if uppercase is equivalent to lowercase */
98974 ){
98975   const char *z = 0;         /* String on RHS of LIKE operator */
98976   Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
98977   ExprList *pList;           /* List of operands to the LIKE operator */
98978   int c;                     /* One character in z[] */
98979   int cnt;                   /* Number of non-wildcard prefix characters */
98980   char wc[3];                /* Wildcard characters */
98981   sqlite3 *db = pParse->db;  /* Database connection */
98982   sqlite3_value *pVal = 0;
98983   int op;                    /* Opcode of pRight */
98984
98985   if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
98986     return 0;
98987   }
98988 #ifdef SQLITE_EBCDIC
98989   if( *pnoCase ) return 0;
98990 #endif
98991   pList = pExpr->x.pList;
98992   pLeft = pList->a[1].pExpr;
98993   if( pLeft->op!=TK_COLUMN || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT ){
98994     /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
98995     ** be the name of an indexed column with TEXT affinity. */
98996     return 0;
98997   }
98998   assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
98999
99000   pRight = pList->a[0].pExpr;
99001   op = pRight->op;
99002   if( op==TK_REGISTER ){
99003     op = pRight->op2;
99004   }
99005   if( op==TK_VARIABLE ){
99006     Vdbe *pReprepare = pParse->pReprepare;
99007     int iCol = pRight->iColumn;
99008     pVal = sqlite3VdbeGetValue(pReprepare, iCol, SQLITE_AFF_NONE);
99009     if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
99010       z = (char *)sqlite3_value_text(pVal);
99011     }
99012     sqlite3VdbeSetVarmask(pParse->pVdbe, iCol); /* IMP: R-23257-02778 */
99013     assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
99014   }else if( op==TK_STRING ){
99015     z = pRight->u.zToken;
99016   }
99017   if( z ){
99018     cnt = 0;
99019     while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
99020       cnt++;
99021     }
99022     if( cnt!=0 && 255!=(u8)z[cnt-1] ){
99023       Expr *pPrefix;
99024       *pisComplete = c==wc[0] && z[cnt+1]==0;
99025       pPrefix = sqlite3Expr(db, TK_STRING, z);
99026       if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
99027       *ppPrefix = pPrefix;
99028       if( op==TK_VARIABLE ){
99029         Vdbe *v = pParse->pVdbe;
99030         sqlite3VdbeSetVarmask(v, pRight->iColumn); /* IMP: R-23257-02778 */
99031         if( *pisComplete && pRight->u.zToken[1] ){
99032           /* If the rhs of the LIKE expression is a variable, and the current
99033           ** value of the variable means there is no need to invoke the LIKE
99034           ** function, then no OP_Variable will be added to the program.
99035           ** This causes problems for the sqlite3_bind_parameter_name()
99036           ** API. To workaround them, add a dummy OP_Variable here.
99037           */ 
99038           int r1 = sqlite3GetTempReg(pParse);
99039           sqlite3ExprCodeTarget(pParse, pRight, r1);
99040           sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
99041           sqlite3ReleaseTempReg(pParse, r1);
99042         }
99043       }
99044     }else{
99045       z = 0;
99046     }
99047   }
99048
99049   sqlite3ValueFree(pVal);
99050   return (z!=0);
99051 }
99052 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
99053
99054
99055 #ifndef SQLITE_OMIT_VIRTUALTABLE
99056 /*
99057 ** Check to see if the given expression is of the form
99058 **
99059 **         column MATCH expr
99060 **
99061 ** If it is then return TRUE.  If not, return FALSE.
99062 */
99063 static int isMatchOfColumn(
99064   Expr *pExpr      /* Test this expression */
99065 ){
99066   ExprList *pList;
99067
99068   if( pExpr->op!=TK_FUNCTION ){
99069     return 0;
99070   }
99071   if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
99072     return 0;
99073   }
99074   pList = pExpr->x.pList;
99075   if( pList->nExpr!=2 ){
99076     return 0;
99077   }
99078   if( pList->a[1].pExpr->op != TK_COLUMN ){
99079     return 0;
99080   }
99081   return 1;
99082 }
99083 #endif /* SQLITE_OMIT_VIRTUALTABLE */
99084
99085 /*
99086 ** If the pBase expression originated in the ON or USING clause of
99087 ** a join, then transfer the appropriate markings over to derived.
99088 */
99089 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
99090   pDerived->flags |= pBase->flags & EP_FromJoin;
99091   pDerived->iRightJoinTable = pBase->iRightJoinTable;
99092 }
99093
99094 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
99095 /*
99096 ** Analyze a term that consists of two or more OR-connected
99097 ** subterms.  So in:
99098 **
99099 **     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
99100 **                          ^^^^^^^^^^^^^^^^^^^^
99101 **
99102 ** This routine analyzes terms such as the middle term in the above example.
99103 ** A WhereOrTerm object is computed and attached to the term under
99104 ** analysis, regardless of the outcome of the analysis.  Hence:
99105 **
99106 **     WhereTerm.wtFlags   |=  TERM_ORINFO
99107 **     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
99108 **
99109 ** The term being analyzed must have two or more of OR-connected subterms.
99110 ** A single subterm might be a set of AND-connected sub-subterms.
99111 ** Examples of terms under analysis:
99112 **
99113 **     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
99114 **     (B)     x=expr1 OR expr2=x OR x=expr3
99115 **     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
99116 **     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
99117 **     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
99118 **
99119 ** CASE 1:
99120 **
99121 ** If all subterms are of the form T.C=expr for some single column of C
99122 ** a single table T (as shown in example B above) then create a new virtual
99123 ** term that is an equivalent IN expression.  In other words, if the term
99124 ** being analyzed is:
99125 **
99126 **      x = expr1  OR  expr2 = x  OR  x = expr3
99127 **
99128 ** then create a new virtual term like this:
99129 **
99130 **      x IN (expr1,expr2,expr3)
99131 **
99132 ** CASE 2:
99133 **
99134 ** If all subterms are indexable by a single table T, then set
99135 **
99136 **     WhereTerm.eOperator              =  WO_OR
99137 **     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
99138 **
99139 ** A subterm is "indexable" if it is of the form
99140 ** "T.C <op> <expr>" where C is any column of table T and 
99141 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
99142 ** A subterm is also indexable if it is an AND of two or more
99143 ** subsubterms at least one of which is indexable.  Indexable AND 
99144 ** subterms have their eOperator set to WO_AND and they have
99145 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
99146 **
99147 ** From another point of view, "indexable" means that the subterm could
99148 ** potentially be used with an index if an appropriate index exists.
99149 ** This analysis does not consider whether or not the index exists; that
99150 ** is something the bestIndex() routine will determine.  This analysis
99151 ** only looks at whether subterms appropriate for indexing exist.
99152 **
99153 ** All examples A through E above all satisfy case 2.  But if a term
99154 ** also statisfies case 1 (such as B) we know that the optimizer will
99155 ** always prefer case 1, so in that case we pretend that case 2 is not
99156 ** satisfied.
99157 **
99158 ** It might be the case that multiple tables are indexable.  For example,
99159 ** (E) above is indexable on tables P, Q, and R.
99160 **
99161 ** Terms that satisfy case 2 are candidates for lookup by using
99162 ** separate indices to find rowids for each subterm and composing
99163 ** the union of all rowids using a RowSet object.  This is similar
99164 ** to "bitmap indices" in other database engines.
99165 **
99166 ** OTHERWISE:
99167 **
99168 ** If neither case 1 nor case 2 apply, then leave the eOperator set to
99169 ** zero.  This term is not useful for search.
99170 */
99171 static void exprAnalyzeOrTerm(
99172   SrcList *pSrc,            /* the FROM clause */
99173   WhereClause *pWC,         /* the complete WHERE clause */
99174   int idxTerm               /* Index of the OR-term to be analyzed */
99175 ){
99176   Parse *pParse = pWC->pParse;            /* Parser context */
99177   sqlite3 *db = pParse->db;               /* Database connection */
99178   WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
99179   Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
99180   WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
99181   int i;                                  /* Loop counters */
99182   WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
99183   WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
99184   WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
99185   Bitmask chngToIN;         /* Tables that might satisfy case 1 */
99186   Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
99187
99188   /*
99189   ** Break the OR clause into its separate subterms.  The subterms are
99190   ** stored in a WhereClause structure containing within the WhereOrInfo
99191   ** object that is attached to the original OR clause term.
99192   */
99193   assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
99194   assert( pExpr->op==TK_OR );
99195   pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
99196   if( pOrInfo==0 ) return;
99197   pTerm->wtFlags |= TERM_ORINFO;
99198   pOrWc = &pOrInfo->wc;
99199   whereClauseInit(pOrWc, pWC->pParse, pMaskSet);
99200   whereSplit(pOrWc, pExpr, TK_OR);
99201   exprAnalyzeAll(pSrc, pOrWc);
99202   if( db->mallocFailed ) return;
99203   assert( pOrWc->nTerm>=2 );
99204
99205   /*
99206   ** Compute the set of tables that might satisfy cases 1 or 2.
99207   */
99208   indexable = ~(Bitmask)0;
99209   chngToIN = ~(pWC->vmask);
99210   for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
99211     if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
99212       WhereAndInfo *pAndInfo;
99213       assert( pOrTerm->eOperator==0 );
99214       assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
99215       chngToIN = 0;
99216       pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
99217       if( pAndInfo ){
99218         WhereClause *pAndWC;
99219         WhereTerm *pAndTerm;
99220         int j;
99221         Bitmask b = 0;
99222         pOrTerm->u.pAndInfo = pAndInfo;
99223         pOrTerm->wtFlags |= TERM_ANDINFO;
99224         pOrTerm->eOperator = WO_AND;
99225         pAndWC = &pAndInfo->wc;
99226         whereClauseInit(pAndWC, pWC->pParse, pMaskSet);
99227         whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
99228         exprAnalyzeAll(pSrc, pAndWC);
99229         testcase( db->mallocFailed );
99230         if( !db->mallocFailed ){
99231           for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
99232             assert( pAndTerm->pExpr );
99233             if( allowedOp(pAndTerm->pExpr->op) ){
99234               b |= getMask(pMaskSet, pAndTerm->leftCursor);
99235             }
99236           }
99237         }
99238         indexable &= b;
99239       }
99240     }else if( pOrTerm->wtFlags & TERM_COPIED ){
99241       /* Skip this term for now.  We revisit it when we process the
99242       ** corresponding TERM_VIRTUAL term */
99243     }else{
99244       Bitmask b;
99245       b = getMask(pMaskSet, pOrTerm->leftCursor);
99246       if( pOrTerm->wtFlags & TERM_VIRTUAL ){
99247         WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
99248         b |= getMask(pMaskSet, pOther->leftCursor);
99249       }
99250       indexable &= b;
99251       if( pOrTerm->eOperator!=WO_EQ ){
99252         chngToIN = 0;
99253       }else{
99254         chngToIN &= b;
99255       }
99256     }
99257   }
99258
99259   /*
99260   ** Record the set of tables that satisfy case 2.  The set might be
99261   ** empty.
99262   */
99263   pOrInfo->indexable = indexable;
99264   pTerm->eOperator = indexable==0 ? 0 : WO_OR;
99265
99266   /*
99267   ** chngToIN holds a set of tables that *might* satisfy case 1.  But
99268   ** we have to do some additional checking to see if case 1 really
99269   ** is satisfied.
99270   **
99271   ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
99272   ** that there is no possibility of transforming the OR clause into an
99273   ** IN operator because one or more terms in the OR clause contain
99274   ** something other than == on a column in the single table.  The 1-bit
99275   ** case means that every term of the OR clause is of the form
99276   ** "table.column=expr" for some single table.  The one bit that is set
99277   ** will correspond to the common table.  We still need to check to make
99278   ** sure the same column is used on all terms.  The 2-bit case is when
99279   ** the all terms are of the form "table1.column=table2.column".  It
99280   ** might be possible to form an IN operator with either table1.column
99281   ** or table2.column as the LHS if either is common to every term of
99282   ** the OR clause.
99283   **
99284   ** Note that terms of the form "table.column1=table.column2" (the
99285   ** same table on both sizes of the ==) cannot be optimized.
99286   */
99287   if( chngToIN ){
99288     int okToChngToIN = 0;     /* True if the conversion to IN is valid */
99289     int iColumn = -1;         /* Column index on lhs of IN operator */
99290     int iCursor = -1;         /* Table cursor common to all terms */
99291     int j = 0;                /* Loop counter */
99292
99293     /* Search for a table and column that appears on one side or the
99294     ** other of the == operator in every subterm.  That table and column
99295     ** will be recorded in iCursor and iColumn.  There might not be any
99296     ** such table and column.  Set okToChngToIN if an appropriate table
99297     ** and column is found but leave okToChngToIN false if not found.
99298     */
99299     for(j=0; j<2 && !okToChngToIN; j++){
99300       pOrTerm = pOrWc->a;
99301       for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
99302         assert( pOrTerm->eOperator==WO_EQ );
99303         pOrTerm->wtFlags &= ~TERM_OR_OK;
99304         if( pOrTerm->leftCursor==iCursor ){
99305           /* This is the 2-bit case and we are on the second iteration and
99306           ** current term is from the first iteration.  So skip this term. */
99307           assert( j==1 );
99308           continue;
99309         }
99310         if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ){
99311           /* This term must be of the form t1.a==t2.b where t2 is in the
99312           ** chngToIN set but t1 is not.  This term will be either preceeded
99313           ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term 
99314           ** and use its inversion. */
99315           testcase( pOrTerm->wtFlags & TERM_COPIED );
99316           testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
99317           assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
99318           continue;
99319         }
99320         iColumn = pOrTerm->u.leftColumn;
99321         iCursor = pOrTerm->leftCursor;
99322         break;
99323       }
99324       if( i<0 ){
99325         /* No candidate table+column was found.  This can only occur
99326         ** on the second iteration */
99327         assert( j==1 );
99328         assert( (chngToIN&(chngToIN-1))==0 );
99329         assert( chngToIN==getMask(pMaskSet, iCursor) );
99330         break;
99331       }
99332       testcase( j==1 );
99333
99334       /* We have found a candidate table and column.  Check to see if that
99335       ** table and column is common to every term in the OR clause */
99336       okToChngToIN = 1;
99337       for(; i>=0 && okToChngToIN; i--, pOrTerm++){
99338         assert( pOrTerm->eOperator==WO_EQ );
99339         if( pOrTerm->leftCursor!=iCursor ){
99340           pOrTerm->wtFlags &= ~TERM_OR_OK;
99341         }else if( pOrTerm->u.leftColumn!=iColumn ){
99342           okToChngToIN = 0;
99343         }else{
99344           int affLeft, affRight;
99345           /* If the right-hand side is also a column, then the affinities
99346           ** of both right and left sides must be such that no type
99347           ** conversions are required on the right.  (Ticket #2249)
99348           */
99349           affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
99350           affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
99351           if( affRight!=0 && affRight!=affLeft ){
99352             okToChngToIN = 0;
99353           }else{
99354             pOrTerm->wtFlags |= TERM_OR_OK;
99355           }
99356         }
99357       }
99358     }
99359
99360     /* At this point, okToChngToIN is true if original pTerm satisfies
99361     ** case 1.  In that case, construct a new virtual term that is 
99362     ** pTerm converted into an IN operator.
99363     **
99364     ** EV: R-00211-15100
99365     */
99366     if( okToChngToIN ){
99367       Expr *pDup;            /* A transient duplicate expression */
99368       ExprList *pList = 0;   /* The RHS of the IN operator */
99369       Expr *pLeft = 0;       /* The LHS of the IN operator */
99370       Expr *pNew;            /* The complete IN operator */
99371
99372       for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
99373         if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
99374         assert( pOrTerm->eOperator==WO_EQ );
99375         assert( pOrTerm->leftCursor==iCursor );
99376         assert( pOrTerm->u.leftColumn==iColumn );
99377         pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
99378         pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup);
99379         pLeft = pOrTerm->pExpr->pLeft;
99380       }
99381       assert( pLeft!=0 );
99382       pDup = sqlite3ExprDup(db, pLeft, 0);
99383       pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
99384       if( pNew ){
99385         int idxNew;
99386         transferJoinMarkings(pNew, pExpr);
99387         assert( !ExprHasProperty(pNew, EP_xIsSelect) );
99388         pNew->x.pList = pList;
99389         idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
99390         testcase( idxNew==0 );
99391         exprAnalyze(pSrc, pWC, idxNew);
99392         pTerm = &pWC->a[idxTerm];
99393         pWC->a[idxNew].iParent = idxTerm;
99394         pTerm->nChild = 1;
99395       }else{
99396         sqlite3ExprListDelete(db, pList);
99397       }
99398       pTerm->eOperator = WO_NOOP;  /* case 1 trumps case 2 */
99399     }
99400   }
99401 }
99402 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
99403
99404
99405 /*
99406 ** The input to this routine is an WhereTerm structure with only the
99407 ** "pExpr" field filled in.  The job of this routine is to analyze the
99408 ** subexpression and populate all the other fields of the WhereTerm
99409 ** structure.
99410 **
99411 ** If the expression is of the form "<expr> <op> X" it gets commuted
99412 ** to the standard form of "X <op> <expr>".
99413 **
99414 ** If the expression is of the form "X <op> Y" where both X and Y are
99415 ** columns, then the original expression is unchanged and a new virtual
99416 ** term of the form "Y <op> X" is added to the WHERE clause and
99417 ** analyzed separately.  The original term is marked with TERM_COPIED
99418 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
99419 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
99420 ** is a commuted copy of a prior term.)  The original term has nChild=1
99421 ** and the copy has idxParent set to the index of the original term.
99422 */
99423 static void exprAnalyze(
99424   SrcList *pSrc,            /* the FROM clause */
99425   WhereClause *pWC,         /* the WHERE clause */
99426   int idxTerm               /* Index of the term to be analyzed */
99427 ){
99428   WhereTerm *pTerm;                /* The term to be analyzed */
99429   WhereMaskSet *pMaskSet;          /* Set of table index masks */
99430   Expr *pExpr;                     /* The expression to be analyzed */
99431   Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
99432   Bitmask prereqAll;               /* Prerequesites of pExpr */
99433   Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */
99434   Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
99435   int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
99436   int noCase = 0;                  /* LIKE/GLOB distinguishes case */
99437   int op;                          /* Top-level operator.  pExpr->op */
99438   Parse *pParse = pWC->pParse;     /* Parsing context */
99439   sqlite3 *db = pParse->db;        /* Database connection */
99440
99441   if( db->mallocFailed ){
99442     return;
99443   }
99444   pTerm = &pWC->a[idxTerm];
99445   pMaskSet = pWC->pMaskSet;
99446   pExpr = pTerm->pExpr;
99447   prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
99448   op = pExpr->op;
99449   if( op==TK_IN ){
99450     assert( pExpr->pRight==0 );
99451     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
99452       pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
99453     }else{
99454       pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
99455     }
99456   }else if( op==TK_ISNULL ){
99457     pTerm->prereqRight = 0;
99458   }else{
99459     pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
99460   }
99461   prereqAll = exprTableUsage(pMaskSet, pExpr);
99462   if( ExprHasProperty(pExpr, EP_FromJoin) ){
99463     Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
99464     prereqAll |= x;
99465     extraRight = x-1;  /* ON clause terms may not be used with an index
99466                        ** on left table of a LEFT JOIN.  Ticket #3015 */
99467   }
99468   pTerm->prereqAll = prereqAll;
99469   pTerm->leftCursor = -1;
99470   pTerm->iParent = -1;
99471   pTerm->eOperator = 0;
99472   if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
99473     Expr *pLeft = pExpr->pLeft;
99474     Expr *pRight = pExpr->pRight;
99475     if( pLeft->op==TK_COLUMN ){
99476       pTerm->leftCursor = pLeft->iTable;
99477       pTerm->u.leftColumn = pLeft->iColumn;
99478       pTerm->eOperator = operatorMask(op);
99479     }
99480     if( pRight && pRight->op==TK_COLUMN ){
99481       WhereTerm *pNew;
99482       Expr *pDup;
99483       if( pTerm->leftCursor>=0 ){
99484         int idxNew;
99485         pDup = sqlite3ExprDup(db, pExpr, 0);
99486         if( db->mallocFailed ){
99487           sqlite3ExprDelete(db, pDup);
99488           return;
99489         }
99490         idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
99491         if( idxNew==0 ) return;
99492         pNew = &pWC->a[idxNew];
99493         pNew->iParent = idxTerm;
99494         pTerm = &pWC->a[idxTerm];
99495         pTerm->nChild = 1;
99496         pTerm->wtFlags |= TERM_COPIED;
99497       }else{
99498         pDup = pExpr;
99499         pNew = pTerm;
99500       }
99501       exprCommute(pParse, pDup);
99502       pLeft = pDup->pLeft;
99503       pNew->leftCursor = pLeft->iTable;
99504       pNew->u.leftColumn = pLeft->iColumn;
99505       testcase( (prereqLeft | extraRight) != prereqLeft );
99506       pNew->prereqRight = prereqLeft | extraRight;
99507       pNew->prereqAll = prereqAll;
99508       pNew->eOperator = operatorMask(pDup->op);
99509     }
99510   }
99511
99512 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
99513   /* If a term is the BETWEEN operator, create two new virtual terms
99514   ** that define the range that the BETWEEN implements.  For example:
99515   **
99516   **      a BETWEEN b AND c
99517   **
99518   ** is converted into:
99519   **
99520   **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
99521   **
99522   ** The two new terms are added onto the end of the WhereClause object.
99523   ** The new terms are "dynamic" and are children of the original BETWEEN
99524   ** term.  That means that if the BETWEEN term is coded, the children are
99525   ** skipped.  Or, if the children are satisfied by an index, the original
99526   ** BETWEEN term is skipped.
99527   */
99528   else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
99529     ExprList *pList = pExpr->x.pList;
99530     int i;
99531     static const u8 ops[] = {TK_GE, TK_LE};
99532     assert( pList!=0 );
99533     assert( pList->nExpr==2 );
99534     for(i=0; i<2; i++){
99535       Expr *pNewExpr;
99536       int idxNew;
99537       pNewExpr = sqlite3PExpr(pParse, ops[i], 
99538                              sqlite3ExprDup(db, pExpr->pLeft, 0),
99539                              sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
99540       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
99541       testcase( idxNew==0 );
99542       exprAnalyze(pSrc, pWC, idxNew);
99543       pTerm = &pWC->a[idxTerm];
99544       pWC->a[idxNew].iParent = idxTerm;
99545     }
99546     pTerm->nChild = 2;
99547   }
99548 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
99549
99550 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
99551   /* Analyze a term that is composed of two or more subterms connected by
99552   ** an OR operator.
99553   */
99554   else if( pExpr->op==TK_OR ){
99555     assert( pWC->op==TK_AND );
99556     exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
99557     pTerm = &pWC->a[idxTerm];
99558   }
99559 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
99560
99561 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
99562   /* Add constraints to reduce the search space on a LIKE or GLOB
99563   ** operator.
99564   **
99565   ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
99566   **
99567   **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
99568   **
99569   ** The last character of the prefix "abc" is incremented to form the
99570   ** termination condition "abd".
99571   */
99572   if( pWC->op==TK_AND 
99573    && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
99574   ){
99575     Expr *pLeft;       /* LHS of LIKE/GLOB operator */
99576     Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
99577     Expr *pNewExpr1;
99578     Expr *pNewExpr2;
99579     int idxNew1;
99580     int idxNew2;
99581     CollSeq *pColl;    /* Collating sequence to use */
99582
99583     pLeft = pExpr->x.pList->a[1].pExpr;
99584     pStr2 = sqlite3ExprDup(db, pStr1, 0);
99585     if( !db->mallocFailed ){
99586       u8 c, *pC;       /* Last character before the first wildcard */
99587       pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
99588       c = *pC;
99589       if( noCase ){
99590         /* The point is to increment the last character before the first
99591         ** wildcard.  But if we increment '@', that will push it into the
99592         ** alphabetic range where case conversions will mess up the 
99593         ** inequality.  To avoid this, make sure to also run the full
99594         ** LIKE on all candidate expressions by clearing the isComplete flag
99595         */
99596         if( c=='A'-1 ) isComplete = 0;   /* EV: R-64339-08207 */
99597
99598
99599         c = sqlite3UpperToLower[c];
99600       }
99601       *pC = c + 1;
99602     }
99603     pColl = sqlite3FindCollSeq(db, SQLITE_UTF8, noCase ? "NOCASE" : "BINARY",0);
99604     pNewExpr1 = sqlite3PExpr(pParse, TK_GE, 
99605                      sqlite3ExprSetColl(sqlite3ExprDup(db,pLeft,0), pColl),
99606                      pStr1, 0);
99607     idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
99608     testcase( idxNew1==0 );
99609     exprAnalyze(pSrc, pWC, idxNew1);
99610     pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
99611                      sqlite3ExprSetColl(sqlite3ExprDup(db,pLeft,0), pColl),
99612                      pStr2, 0);
99613     idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
99614     testcase( idxNew2==0 );
99615     exprAnalyze(pSrc, pWC, idxNew2);
99616     pTerm = &pWC->a[idxTerm];
99617     if( isComplete ){
99618       pWC->a[idxNew1].iParent = idxTerm;
99619       pWC->a[idxNew2].iParent = idxTerm;
99620       pTerm->nChild = 2;
99621     }
99622   }
99623 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
99624
99625 #ifndef SQLITE_OMIT_VIRTUALTABLE
99626   /* Add a WO_MATCH auxiliary term to the constraint set if the
99627   ** current expression is of the form:  column MATCH expr.
99628   ** This information is used by the xBestIndex methods of
99629   ** virtual tables.  The native query optimizer does not attempt
99630   ** to do anything with MATCH functions.
99631   */
99632   if( isMatchOfColumn(pExpr) ){
99633     int idxNew;
99634     Expr *pRight, *pLeft;
99635     WhereTerm *pNewTerm;
99636     Bitmask prereqColumn, prereqExpr;
99637
99638     pRight = pExpr->x.pList->a[0].pExpr;
99639     pLeft = pExpr->x.pList->a[1].pExpr;
99640     prereqExpr = exprTableUsage(pMaskSet, pRight);
99641     prereqColumn = exprTableUsage(pMaskSet, pLeft);
99642     if( (prereqExpr & prereqColumn)==0 ){
99643       Expr *pNewExpr;
99644       pNewExpr = sqlite3PExpr(pParse, TK_MATCH, 
99645                               0, sqlite3ExprDup(db, pRight, 0), 0);
99646       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
99647       testcase( idxNew==0 );
99648       pNewTerm = &pWC->a[idxNew];
99649       pNewTerm->prereqRight = prereqExpr;
99650       pNewTerm->leftCursor = pLeft->iTable;
99651       pNewTerm->u.leftColumn = pLeft->iColumn;
99652       pNewTerm->eOperator = WO_MATCH;
99653       pNewTerm->iParent = idxTerm;
99654       pTerm = &pWC->a[idxTerm];
99655       pTerm->nChild = 1;
99656       pTerm->wtFlags |= TERM_COPIED;
99657       pNewTerm->prereqAll = pTerm->prereqAll;
99658     }
99659   }
99660 #endif /* SQLITE_OMIT_VIRTUALTABLE */
99661
99662 #ifdef SQLITE_ENABLE_STAT2
99663   /* When sqlite_stat2 histogram data is available an operator of the
99664   ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
99665   ** as "x>NULL" if x is not an INTEGER PRIMARY KEY.  So construct a
99666   ** virtual term of that form.
99667   **
99668   ** Note that the virtual term must be tagged with TERM_VNULL.  This
99669   ** TERM_VNULL tag will suppress the not-null check at the beginning
99670   ** of the loop.  Without the TERM_VNULL flag, the not-null check at
99671   ** the start of the loop will prevent any results from being returned.
99672   */
99673   if( pExpr->op==TK_NOTNULL
99674    && pExpr->pLeft->op==TK_COLUMN
99675    && pExpr->pLeft->iColumn>=0
99676   ){
99677     Expr *pNewExpr;
99678     Expr *pLeft = pExpr->pLeft;
99679     int idxNew;
99680     WhereTerm *pNewTerm;
99681
99682     pNewExpr = sqlite3PExpr(pParse, TK_GT,
99683                             sqlite3ExprDup(db, pLeft, 0),
99684                             sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
99685
99686     idxNew = whereClauseInsert(pWC, pNewExpr,
99687                               TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
99688     if( idxNew ){
99689       pNewTerm = &pWC->a[idxNew];
99690       pNewTerm->prereqRight = 0;
99691       pNewTerm->leftCursor = pLeft->iTable;
99692       pNewTerm->u.leftColumn = pLeft->iColumn;
99693       pNewTerm->eOperator = WO_GT;
99694       pNewTerm->iParent = idxTerm;
99695       pTerm = &pWC->a[idxTerm];
99696       pTerm->nChild = 1;
99697       pTerm->wtFlags |= TERM_COPIED;
99698       pNewTerm->prereqAll = pTerm->prereqAll;
99699     }
99700   }
99701 #endif /* SQLITE_ENABLE_STAT2 */
99702
99703   /* Prevent ON clause terms of a LEFT JOIN from being used to drive
99704   ** an index for tables to the left of the join.
99705   */
99706   pTerm->prereqRight |= extraRight;
99707 }
99708
99709 /*
99710 ** Return TRUE if any of the expressions in pList->a[iFirst...] contain
99711 ** a reference to any table other than the iBase table.
99712 */
99713 static int referencesOtherTables(
99714   ExprList *pList,          /* Search expressions in ths list */
99715   WhereMaskSet *pMaskSet,   /* Mapping from tables to bitmaps */
99716   int iFirst,               /* Be searching with the iFirst-th expression */
99717   int iBase                 /* Ignore references to this table */
99718 ){
99719   Bitmask allowed = ~getMask(pMaskSet, iBase);
99720   while( iFirst<pList->nExpr ){
99721     if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
99722       return 1;
99723     }
99724   }
99725   return 0;
99726 }
99727
99728
99729 /*
99730 ** This routine decides if pIdx can be used to satisfy the ORDER BY
99731 ** clause.  If it can, it returns 1.  If pIdx cannot satisfy the
99732 ** ORDER BY clause, this routine returns 0.
99733 **
99734 ** pOrderBy is an ORDER BY clause from a SELECT statement.  pTab is the
99735 ** left-most table in the FROM clause of that same SELECT statement and
99736 ** the table has a cursor number of "base".  pIdx is an index on pTab.
99737 **
99738 ** nEqCol is the number of columns of pIdx that are used as equality
99739 ** constraints.  Any of these columns may be missing from the ORDER BY
99740 ** clause and the match can still be a success.
99741 **
99742 ** All terms of the ORDER BY that match against the index must be either
99743 ** ASC or DESC.  (Terms of the ORDER BY clause past the end of a UNIQUE
99744 ** index do not need to satisfy this constraint.)  The *pbRev value is
99745 ** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
99746 ** the ORDER BY clause is all ASC.
99747 */
99748 static int isSortingIndex(
99749   Parse *pParse,          /* Parsing context */
99750   WhereMaskSet *pMaskSet, /* Mapping from table cursor numbers to bitmaps */
99751   Index *pIdx,            /* The index we are testing */
99752   int base,               /* Cursor number for the table to be sorted */
99753   ExprList *pOrderBy,     /* The ORDER BY clause */
99754   int nEqCol,             /* Number of index columns with == constraints */
99755   int wsFlags,            /* Index usages flags */
99756   int *pbRev              /* Set to 1 if ORDER BY is DESC */
99757 ){
99758   int i, j;                       /* Loop counters */
99759   int sortOrder = 0;              /* XOR of index and ORDER BY sort direction */
99760   int nTerm;                      /* Number of ORDER BY terms */
99761   struct ExprList_item *pTerm;    /* A term of the ORDER BY clause */
99762   sqlite3 *db = pParse->db;
99763
99764   assert( pOrderBy!=0 );
99765   nTerm = pOrderBy->nExpr;
99766   assert( nTerm>0 );
99767
99768   /* Argument pIdx must either point to a 'real' named index structure, 
99769   ** or an index structure allocated on the stack by bestBtreeIndex() to
99770   ** represent the rowid index that is part of every table.  */
99771   assert( pIdx->zName || (pIdx->nColumn==1 && pIdx->aiColumn[0]==-1) );
99772
99773   /* Match terms of the ORDER BY clause against columns of
99774   ** the index.
99775   **
99776   ** Note that indices have pIdx->nColumn regular columns plus
99777   ** one additional column containing the rowid.  The rowid column
99778   ** of the index is also allowed to match against the ORDER BY
99779   ** clause.
99780   */
99781   for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
99782     Expr *pExpr;       /* The expression of the ORDER BY pTerm */
99783     CollSeq *pColl;    /* The collating sequence of pExpr */
99784     int termSortOrder; /* Sort order for this term */
99785     int iColumn;       /* The i-th column of the index.  -1 for rowid */
99786     int iSortOrder;    /* 1 for DESC, 0 for ASC on the i-th index term */
99787     const char *zColl; /* Name of the collating sequence for i-th index term */
99788
99789     pExpr = pTerm->pExpr;
99790     if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
99791       /* Can not use an index sort on anything that is not a column in the
99792       ** left-most table of the FROM clause */
99793       break;
99794     }
99795     pColl = sqlite3ExprCollSeq(pParse, pExpr);
99796     if( !pColl ){
99797       pColl = db->pDfltColl;
99798     }
99799     if( pIdx->zName && i<pIdx->nColumn ){
99800       iColumn = pIdx->aiColumn[i];
99801       if( iColumn==pIdx->pTable->iPKey ){
99802         iColumn = -1;
99803       }
99804       iSortOrder = pIdx->aSortOrder[i];
99805       zColl = pIdx->azColl[i];
99806     }else{
99807       iColumn = -1;
99808       iSortOrder = 0;
99809       zColl = pColl->zName;
99810     }
99811     if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){
99812       /* Term j of the ORDER BY clause does not match column i of the index */
99813       if( i<nEqCol ){
99814         /* If an index column that is constrained by == fails to match an
99815         ** ORDER BY term, that is OK.  Just ignore that column of the index
99816         */
99817         continue;
99818       }else if( i==pIdx->nColumn ){
99819         /* Index column i is the rowid.  All other terms match. */
99820         break;
99821       }else{
99822         /* If an index column fails to match and is not constrained by ==
99823         ** then the index cannot satisfy the ORDER BY constraint.
99824         */
99825         return 0;
99826       }
99827     }
99828     assert( pIdx->aSortOrder!=0 || iColumn==-1 );
99829     assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
99830     assert( iSortOrder==0 || iSortOrder==1 );
99831     termSortOrder = iSortOrder ^ pTerm->sortOrder;
99832     if( i>nEqCol ){
99833       if( termSortOrder!=sortOrder ){
99834         /* Indices can only be used if all ORDER BY terms past the
99835         ** equality constraints are all either DESC or ASC. */
99836         return 0;
99837       }
99838     }else{
99839       sortOrder = termSortOrder;
99840     }
99841     j++;
99842     pTerm++;
99843     if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
99844       /* If the indexed column is the primary key and everything matches
99845       ** so far and none of the ORDER BY terms to the right reference other
99846       ** tables in the join, then we are assured that the index can be used 
99847       ** to sort because the primary key is unique and so none of the other
99848       ** columns will make any difference
99849       */
99850       j = nTerm;
99851     }
99852   }
99853
99854   *pbRev = sortOrder!=0;
99855   if( j>=nTerm ){
99856     /* All terms of the ORDER BY clause are covered by this index so
99857     ** this index can be used for sorting. */
99858     return 1;
99859   }
99860   if( pIdx->onError!=OE_None && i==pIdx->nColumn
99861       && (wsFlags & WHERE_COLUMN_NULL)==0
99862       && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
99863     /* All terms of this index match some prefix of the ORDER BY clause
99864     ** and the index is UNIQUE and no terms on the tail of the ORDER BY
99865     ** clause reference other tables in a join.  If this is all true then
99866     ** the order by clause is superfluous.  Not that if the matching
99867     ** condition is IS NULL then the result is not necessarily unique
99868     ** even on a UNIQUE index, so disallow those cases. */
99869     return 1;
99870   }
99871   return 0;
99872 }
99873
99874 /*
99875 ** Prepare a crude estimate of the logarithm of the input value.
99876 ** The results need not be exact.  This is only used for estimating
99877 ** the total cost of performing operations with O(logN) or O(NlogN)
99878 ** complexity.  Because N is just a guess, it is no great tragedy if
99879 ** logN is a little off.
99880 */
99881 static double estLog(double N){
99882   double logN = 1;
99883   double x = 10;
99884   while( N>x ){
99885     logN += 1;
99886     x *= 10;
99887   }
99888   return logN;
99889 }
99890
99891 /*
99892 ** Two routines for printing the content of an sqlite3_index_info
99893 ** structure.  Used for testing and debugging only.  If neither
99894 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
99895 ** are no-ops.
99896 */
99897 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
99898 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
99899   int i;
99900   if( !sqlite3WhereTrace ) return;
99901   for(i=0; i<p->nConstraint; i++){
99902     sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
99903        i,
99904        p->aConstraint[i].iColumn,
99905        p->aConstraint[i].iTermOffset,
99906        p->aConstraint[i].op,
99907        p->aConstraint[i].usable);
99908   }
99909   for(i=0; i<p->nOrderBy; i++){
99910     sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
99911        i,
99912        p->aOrderBy[i].iColumn,
99913        p->aOrderBy[i].desc);
99914   }
99915 }
99916 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
99917   int i;
99918   if( !sqlite3WhereTrace ) return;
99919   for(i=0; i<p->nConstraint; i++){
99920     sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
99921        i,
99922        p->aConstraintUsage[i].argvIndex,
99923        p->aConstraintUsage[i].omit);
99924   }
99925   sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
99926   sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
99927   sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
99928   sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
99929 }
99930 #else
99931 #define TRACE_IDX_INPUTS(A)
99932 #define TRACE_IDX_OUTPUTS(A)
99933 #endif
99934
99935 /* 
99936 ** Required because bestIndex() is called by bestOrClauseIndex() 
99937 */
99938 static void bestIndex(
99939     Parse*, WhereClause*, struct SrcList_item*,
99940     Bitmask, Bitmask, ExprList*, WhereCost*);
99941
99942 /*
99943 ** This routine attempts to find an scanning strategy that can be used 
99944 ** to optimize an 'OR' expression that is part of a WHERE clause. 
99945 **
99946 ** The table associated with FROM clause term pSrc may be either a
99947 ** regular B-Tree table or a virtual table.
99948 */
99949 static void bestOrClauseIndex(
99950   Parse *pParse,              /* The parsing context */
99951   WhereClause *pWC,           /* The WHERE clause */
99952   struct SrcList_item *pSrc,  /* The FROM clause term to search */
99953   Bitmask notReady,           /* Mask of cursors not available for indexing */
99954   Bitmask notValid,           /* Cursors not available for any purpose */
99955   ExprList *pOrderBy,         /* The ORDER BY clause */
99956   WhereCost *pCost            /* Lowest cost query plan */
99957 ){
99958 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
99959   const int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
99960   const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur);  /* Bitmask for pSrc */
99961   WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm];        /* End of pWC->a[] */
99962   WhereTerm *pTerm;                 /* A single term of the WHERE clause */
99963
99964   /* No OR-clause optimization allowed if the INDEXED BY or NOT INDEXED clauses
99965   ** are used */
99966   if( pSrc->notIndexed || pSrc->pIndex!=0 ){
99967     return;
99968   }
99969
99970   /* Search the WHERE clause terms for a usable WO_OR term. */
99971   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
99972     if( pTerm->eOperator==WO_OR 
99973      && ((pTerm->prereqAll & ~maskSrc) & notReady)==0
99974      && (pTerm->u.pOrInfo->indexable & maskSrc)!=0 
99975     ){
99976       WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
99977       WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
99978       WhereTerm *pOrTerm;
99979       int flags = WHERE_MULTI_OR;
99980       double rTotal = 0;
99981       double nRow = 0;
99982       Bitmask used = 0;
99983
99984       for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
99985         WhereCost sTermCost;
99986         WHERETRACE(("... Multi-index OR testing for term %d of %d....\n", 
99987           (pOrTerm - pOrWC->a), (pTerm - pWC->a)
99988         ));
99989         if( pOrTerm->eOperator==WO_AND ){
99990           WhereClause *pAndWC = &pOrTerm->u.pAndInfo->wc;
99991           bestIndex(pParse, pAndWC, pSrc, notReady, notValid, 0, &sTermCost);
99992         }else if( pOrTerm->leftCursor==iCur ){
99993           WhereClause tempWC;
99994           tempWC.pParse = pWC->pParse;
99995           tempWC.pMaskSet = pWC->pMaskSet;
99996           tempWC.op = TK_AND;
99997           tempWC.a = pOrTerm;
99998           tempWC.nTerm = 1;
99999           bestIndex(pParse, &tempWC, pSrc, notReady, notValid, 0, &sTermCost);
100000         }else{
100001           continue;
100002         }
100003         rTotal += sTermCost.rCost;
100004         nRow += sTermCost.plan.nRow;
100005         used |= sTermCost.used;
100006         if( rTotal>=pCost->rCost ) break;
100007       }
100008
100009       /* If there is an ORDER BY clause, increase the scan cost to account 
100010       ** for the cost of the sort. */
100011       if( pOrderBy!=0 ){
100012         WHERETRACE(("... sorting increases OR cost %.9g to %.9g\n",
100013                     rTotal, rTotal+nRow*estLog(nRow)));
100014         rTotal += nRow*estLog(nRow);
100015       }
100016
100017       /* If the cost of scanning using this OR term for optimization is
100018       ** less than the current cost stored in pCost, replace the contents
100019       ** of pCost. */
100020       WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow));
100021       if( rTotal<pCost->rCost ){
100022         pCost->rCost = rTotal;
100023         pCost->used = used;
100024         pCost->plan.nRow = nRow;
100025         pCost->plan.wsFlags = flags;
100026         pCost->plan.u.pTerm = pTerm;
100027       }
100028     }
100029   }
100030 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
100031 }
100032
100033 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
100034 /*
100035 ** Return TRUE if the WHERE clause term pTerm is of a form where it
100036 ** could be used with an index to access pSrc, assuming an appropriate
100037 ** index existed.
100038 */
100039 static int termCanDriveIndex(
100040   WhereTerm *pTerm,              /* WHERE clause term to check */
100041   struct SrcList_item *pSrc,     /* Table we are trying to access */
100042   Bitmask notReady               /* Tables in outer loops of the join */
100043 ){
100044   char aff;
100045   if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
100046   if( pTerm->eOperator!=WO_EQ ) return 0;
100047   if( (pTerm->prereqRight & notReady)!=0 ) return 0;
100048   aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
100049   if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
100050   return 1;
100051 }
100052 #endif
100053
100054 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
100055 /*
100056 ** If the query plan for pSrc specified in pCost is a full table scan
100057 ** and indexing is allows (if there is no NOT INDEXED clause) and it
100058 ** possible to construct a transient index that would perform better
100059 ** than a full table scan even when the cost of constructing the index
100060 ** is taken into account, then alter the query plan to use the
100061 ** transient index.
100062 */
100063 static void bestAutomaticIndex(
100064   Parse *pParse,              /* The parsing context */
100065   WhereClause *pWC,           /* The WHERE clause */
100066   struct SrcList_item *pSrc,  /* The FROM clause term to search */
100067   Bitmask notReady,           /* Mask of cursors that are not available */
100068   WhereCost *pCost            /* Lowest cost query plan */
100069 ){
100070   double nTableRow;           /* Rows in the input table */
100071   double logN;                /* log(nTableRow) */
100072   double costTempIdx;         /* per-query cost of the transient index */
100073   WhereTerm *pTerm;           /* A single term of the WHERE clause */
100074   WhereTerm *pWCEnd;          /* End of pWC->a[] */
100075   Table *pTable;              /* Table tht might be indexed */
100076
100077   if( (pParse->db->flags & SQLITE_AutoIndex)==0 ){
100078     /* Automatic indices are disabled at run-time */
100079     return;
100080   }
100081   if( (pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)!=0 ){
100082     /* We already have some kind of index in use for this query. */
100083     return;
100084   }
100085   if( pSrc->notIndexed ){
100086     /* The NOT INDEXED clause appears in the SQL. */
100087     return;
100088   }
100089
100090   assert( pParse->nQueryLoop >= (double)1 );
100091   pTable = pSrc->pTab;
100092   nTableRow = pTable->nRowEst;
100093   logN = estLog(nTableRow);
100094   costTempIdx = 2*logN*(nTableRow/pParse->nQueryLoop + 1);
100095   if( costTempIdx>=pCost->rCost ){
100096     /* The cost of creating the transient table would be greater than
100097     ** doing the full table scan */
100098     return;
100099   }
100100
100101   /* Search for any equality comparison term */
100102   pWCEnd = &pWC->a[pWC->nTerm];
100103   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
100104     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
100105       WHERETRACE(("auto-index reduces cost from %.1f to %.1f\n",
100106                     pCost->rCost, costTempIdx));
100107       pCost->rCost = costTempIdx;
100108       pCost->plan.nRow = logN + 1;
100109       pCost->plan.wsFlags = WHERE_TEMP_INDEX;
100110       pCost->used = pTerm->prereqRight;
100111       break;
100112     }
100113   }
100114 }
100115 #else
100116 # define bestAutomaticIndex(A,B,C,D,E)  /* no-op */
100117 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
100118
100119
100120 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
100121 /*
100122 ** Generate code to construct the Index object for an automatic index
100123 ** and to set up the WhereLevel object pLevel so that the code generator
100124 ** makes use of the automatic index.
100125 */
100126 static void constructAutomaticIndex(
100127   Parse *pParse,              /* The parsing context */
100128   WhereClause *pWC,           /* The WHERE clause */
100129   struct SrcList_item *pSrc,  /* The FROM clause term to get the next index */
100130   Bitmask notReady,           /* Mask of cursors that are not available */
100131   WhereLevel *pLevel          /* Write new index here */
100132 ){
100133   int nColumn;                /* Number of columns in the constructed index */
100134   WhereTerm *pTerm;           /* A single term of the WHERE clause */
100135   WhereTerm *pWCEnd;          /* End of pWC->a[] */
100136   int nByte;                  /* Byte of memory needed for pIdx */
100137   Index *pIdx;                /* Object describing the transient index */
100138   Vdbe *v;                    /* Prepared statement under construction */
100139   int regIsInit;              /* Register set by initialization */
100140   int addrInit;               /* Address of the initialization bypass jump */
100141   Table *pTable;              /* The table being indexed */
100142   KeyInfo *pKeyinfo;          /* Key information for the index */   
100143   int addrTop;                /* Top of the index fill loop */
100144   int regRecord;              /* Register holding an index record */
100145   int n;                      /* Column counter */
100146   int i;                      /* Loop counter */
100147   int mxBitCol;               /* Maximum column in pSrc->colUsed */
100148   CollSeq *pColl;             /* Collating sequence to on a column */
100149   Bitmask idxCols;            /* Bitmap of columns used for indexing */
100150   Bitmask extraCols;          /* Bitmap of additional columns */
100151
100152   /* Generate code to skip over the creation and initialization of the
100153   ** transient index on 2nd and subsequent iterations of the loop. */
100154   v = pParse->pVdbe;
100155   assert( v!=0 );
100156   regIsInit = ++pParse->nMem;
100157   addrInit = sqlite3VdbeAddOp1(v, OP_If, regIsInit);
100158   sqlite3VdbeAddOp2(v, OP_Integer, 1, regIsInit);
100159
100160   /* Count the number of columns that will be added to the index
100161   ** and used to match WHERE clause constraints */
100162   nColumn = 0;
100163   pTable = pSrc->pTab;
100164   pWCEnd = &pWC->a[pWC->nTerm];
100165   idxCols = 0;
100166   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
100167     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
100168       int iCol = pTerm->u.leftColumn;
100169       Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
100170       testcase( iCol==BMS );
100171       testcase( iCol==BMS-1 );
100172       if( (idxCols & cMask)==0 ){
100173         nColumn++;
100174         idxCols |= cMask;
100175       }
100176     }
100177   }
100178   assert( nColumn>0 );
100179   pLevel->plan.nEq = nColumn;
100180
100181   /* Count the number of additional columns needed to create a
100182   ** covering index.  A "covering index" is an index that contains all
100183   ** columns that are needed by the query.  With a covering index, the
100184   ** original table never needs to be accessed.  Automatic indices must
100185   ** be a covering index because the index will not be updated if the
100186   ** original table changes and the index and table cannot both be used
100187   ** if they go out of sync.
100188   */
100189   extraCols = pSrc->colUsed & (~idxCols | (((Bitmask)1)<<(BMS-1)));
100190   mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
100191   testcase( pTable->nCol==BMS-1 );
100192   testcase( pTable->nCol==BMS-2 );
100193   for(i=0; i<mxBitCol; i++){
100194     if( extraCols & (((Bitmask)1)<<i) ) nColumn++;
100195   }
100196   if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
100197     nColumn += pTable->nCol - BMS + 1;
100198   }
100199   pLevel->plan.wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WO_EQ;
100200
100201   /* Construct the Index object to describe this index */
100202   nByte = sizeof(Index);
100203   nByte += nColumn*sizeof(int);     /* Index.aiColumn */
100204   nByte += nColumn*sizeof(char*);   /* Index.azColl */
100205   nByte += nColumn;                 /* Index.aSortOrder */
100206   pIdx = sqlite3DbMallocZero(pParse->db, nByte);
100207   if( pIdx==0 ) return;
100208   pLevel->plan.u.pIdx = pIdx;
100209   pIdx->azColl = (char**)&pIdx[1];
100210   pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
100211   pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
100212   pIdx->zName = "auto-index";
100213   pIdx->nColumn = nColumn;
100214   pIdx->pTable = pTable;
100215   n = 0;
100216   idxCols = 0;
100217   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
100218     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
100219       int iCol = pTerm->u.leftColumn;
100220       Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
100221       if( (idxCols & cMask)==0 ){
100222         Expr *pX = pTerm->pExpr;
100223         idxCols |= cMask;
100224         pIdx->aiColumn[n] = pTerm->u.leftColumn;
100225         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
100226         pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
100227         n++;
100228       }
100229     }
100230   }
100231   assert( (u32)n==pLevel->plan.nEq );
100232
100233   /* Add additional columns needed to make the automatic index into
100234   ** a covering index */
100235   for(i=0; i<mxBitCol; i++){
100236     if( extraCols & (((Bitmask)1)<<i) ){
100237       pIdx->aiColumn[n] = i;
100238       pIdx->azColl[n] = "BINARY";
100239       n++;
100240     }
100241   }
100242   if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
100243     for(i=BMS-1; i<pTable->nCol; i++){
100244       pIdx->aiColumn[n] = i;
100245       pIdx->azColl[n] = "BINARY";
100246       n++;
100247     }
100248   }
100249   assert( n==nColumn );
100250
100251   /* Create the automatic index */
100252   pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
100253   assert( pLevel->iIdxCur>=0 );
100254   sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
100255                     (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
100256   VdbeComment((v, "for %s", pTable->zName));
100257
100258   /* Fill the automatic index with content */
100259   addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
100260   regRecord = sqlite3GetTempReg(pParse);
100261   sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1);
100262   sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
100263   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
100264   sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
100265   sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
100266   sqlite3VdbeJumpHere(v, addrTop);
100267   sqlite3ReleaseTempReg(pParse, regRecord);
100268   
100269   /* Jump here when skipping the initialization */
100270   sqlite3VdbeJumpHere(v, addrInit);
100271 }
100272 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
100273
100274 #ifndef SQLITE_OMIT_VIRTUALTABLE
100275 /*
100276 ** Allocate and populate an sqlite3_index_info structure. It is the 
100277 ** responsibility of the caller to eventually release the structure
100278 ** by passing the pointer returned by this function to sqlite3_free().
100279 */
100280 static sqlite3_index_info *allocateIndexInfo(
100281   Parse *pParse, 
100282   WhereClause *pWC,
100283   struct SrcList_item *pSrc,
100284   ExprList *pOrderBy
100285 ){
100286   int i, j;
100287   int nTerm;
100288   struct sqlite3_index_constraint *pIdxCons;
100289   struct sqlite3_index_orderby *pIdxOrderBy;
100290   struct sqlite3_index_constraint_usage *pUsage;
100291   WhereTerm *pTerm;
100292   int nOrderBy;
100293   sqlite3_index_info *pIdxInfo;
100294
100295   WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));
100296
100297   /* Count the number of possible WHERE clause constraints referring
100298   ** to this virtual table */
100299   for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
100300     if( pTerm->leftCursor != pSrc->iCursor ) continue;
100301     assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
100302     testcase( pTerm->eOperator==WO_IN );
100303     testcase( pTerm->eOperator==WO_ISNULL );
100304     if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
100305     nTerm++;
100306   }
100307
100308   /* If the ORDER BY clause contains only columns in the current 
100309   ** virtual table then allocate space for the aOrderBy part of
100310   ** the sqlite3_index_info structure.
100311   */
100312   nOrderBy = 0;
100313   if( pOrderBy ){
100314     for(i=0; i<pOrderBy->nExpr; i++){
100315       Expr *pExpr = pOrderBy->a[i].pExpr;
100316       if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
100317     }
100318     if( i==pOrderBy->nExpr ){
100319       nOrderBy = pOrderBy->nExpr;
100320     }
100321   }
100322
100323   /* Allocate the sqlite3_index_info structure
100324   */
100325   pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
100326                            + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
100327                            + sizeof(*pIdxOrderBy)*nOrderBy );
100328   if( pIdxInfo==0 ){
100329     sqlite3ErrorMsg(pParse, "out of memory");
100330     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
100331     return 0;
100332   }
100333
100334   /* Initialize the structure.  The sqlite3_index_info structure contains
100335   ** many fields that are declared "const" to prevent xBestIndex from
100336   ** changing them.  We have to do some funky casting in order to
100337   ** initialize those fields.
100338   */
100339   pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
100340   pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
100341   pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
100342   *(int*)&pIdxInfo->nConstraint = nTerm;
100343   *(int*)&pIdxInfo->nOrderBy = nOrderBy;
100344   *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
100345   *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
100346   *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
100347                                                                    pUsage;
100348
100349   for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
100350     if( pTerm->leftCursor != pSrc->iCursor ) continue;
100351     assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
100352     testcase( pTerm->eOperator==WO_IN );
100353     testcase( pTerm->eOperator==WO_ISNULL );
100354     if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
100355     pIdxCons[j].iColumn = pTerm->u.leftColumn;
100356     pIdxCons[j].iTermOffset = i;
100357     pIdxCons[j].op = (u8)pTerm->eOperator;
100358     /* The direct assignment in the previous line is possible only because
100359     ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
100360     ** following asserts verify this fact. */
100361     assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
100362     assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
100363     assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
100364     assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
100365     assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
100366     assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
100367     assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
100368     j++;
100369   }
100370   for(i=0; i<nOrderBy; i++){
100371     Expr *pExpr = pOrderBy->a[i].pExpr;
100372     pIdxOrderBy[i].iColumn = pExpr->iColumn;
100373     pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
100374   }
100375
100376   return pIdxInfo;
100377 }
100378
100379 /*
100380 ** The table object reference passed as the second argument to this function
100381 ** must represent a virtual table. This function invokes the xBestIndex()
100382 ** method of the virtual table with the sqlite3_index_info pointer passed
100383 ** as the argument.
100384 **
100385 ** If an error occurs, pParse is populated with an error message and a
100386 ** non-zero value is returned. Otherwise, 0 is returned and the output
100387 ** part of the sqlite3_index_info structure is left populated.
100388 **
100389 ** Whether or not an error is returned, it is the responsibility of the
100390 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
100391 ** that this is required.
100392 */
100393 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
100394   sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
100395   int i;
100396   int rc;
100397
100398   WHERETRACE(("xBestIndex for %s\n", pTab->zName));
100399   TRACE_IDX_INPUTS(p);
100400   rc = pVtab->pModule->xBestIndex(pVtab, p);
100401   TRACE_IDX_OUTPUTS(p);
100402
100403   if( rc!=SQLITE_OK ){
100404     if( rc==SQLITE_NOMEM ){
100405       pParse->db->mallocFailed = 1;
100406     }else if( !pVtab->zErrMsg ){
100407       sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
100408     }else{
100409       sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
100410     }
100411   }
100412   sqlite3_free(pVtab->zErrMsg);
100413   pVtab->zErrMsg = 0;
100414
100415   for(i=0; i<p->nConstraint; i++){
100416     if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
100417       sqlite3ErrorMsg(pParse, 
100418           "table %s: xBestIndex returned an invalid plan", pTab->zName);
100419     }
100420   }
100421
100422   return pParse->nErr;
100423 }
100424
100425
100426 /*
100427 ** Compute the best index for a virtual table.
100428 **
100429 ** The best index is computed by the xBestIndex method of the virtual
100430 ** table module.  This routine is really just a wrapper that sets up
100431 ** the sqlite3_index_info structure that is used to communicate with
100432 ** xBestIndex.
100433 **
100434 ** In a join, this routine might be called multiple times for the
100435 ** same virtual table.  The sqlite3_index_info structure is created
100436 ** and initialized on the first invocation and reused on all subsequent
100437 ** invocations.  The sqlite3_index_info structure is also used when
100438 ** code is generated to access the virtual table.  The whereInfoDelete() 
100439 ** routine takes care of freeing the sqlite3_index_info structure after
100440 ** everybody has finished with it.
100441 */
100442 static void bestVirtualIndex(
100443   Parse *pParse,                  /* The parsing context */
100444   WhereClause *pWC,               /* The WHERE clause */
100445   struct SrcList_item *pSrc,      /* The FROM clause term to search */
100446   Bitmask notReady,               /* Mask of cursors not available for index */
100447   Bitmask notValid,               /* Cursors not valid for any purpose */
100448   ExprList *pOrderBy,             /* The order by clause */
100449   WhereCost *pCost,               /* Lowest cost query plan */
100450   sqlite3_index_info **ppIdxInfo  /* Index information passed to xBestIndex */
100451 ){
100452   Table *pTab = pSrc->pTab;
100453   sqlite3_index_info *pIdxInfo;
100454   struct sqlite3_index_constraint *pIdxCons;
100455   struct sqlite3_index_constraint_usage *pUsage;
100456   WhereTerm *pTerm;
100457   int i, j;
100458   int nOrderBy;
100459   double rCost;
100460
100461   /* Make sure wsFlags is initialized to some sane value. Otherwise, if the 
100462   ** malloc in allocateIndexInfo() fails and this function returns leaving
100463   ** wsFlags in an uninitialized state, the caller may behave unpredictably.
100464   */
100465   memset(pCost, 0, sizeof(*pCost));
100466   pCost->plan.wsFlags = WHERE_VIRTUALTABLE;
100467
100468   /* If the sqlite3_index_info structure has not been previously
100469   ** allocated and initialized, then allocate and initialize it now.
100470   */
100471   pIdxInfo = *ppIdxInfo;
100472   if( pIdxInfo==0 ){
100473     *ppIdxInfo = pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pOrderBy);
100474   }
100475   if( pIdxInfo==0 ){
100476     return;
100477   }
100478
100479   /* At this point, the sqlite3_index_info structure that pIdxInfo points
100480   ** to will have been initialized, either during the current invocation or
100481   ** during some prior invocation.  Now we just have to customize the
100482   ** details of pIdxInfo for the current invocation and pass it to
100483   ** xBestIndex.
100484   */
100485
100486   /* The module name must be defined. Also, by this point there must
100487   ** be a pointer to an sqlite3_vtab structure. Otherwise
100488   ** sqlite3ViewGetColumnNames() would have picked up the error. 
100489   */
100490   assert( pTab->azModuleArg && pTab->azModuleArg[0] );
100491   assert( sqlite3GetVTable(pParse->db, pTab) );
100492
100493   /* Set the aConstraint[].usable fields and initialize all 
100494   ** output variables to zero.
100495   **
100496   ** aConstraint[].usable is true for constraints where the right-hand
100497   ** side contains only references to tables to the left of the current
100498   ** table.  In other words, if the constraint is of the form:
100499   **
100500   **           column = expr
100501   **
100502   ** and we are evaluating a join, then the constraint on column is 
100503   ** only valid if all tables referenced in expr occur to the left
100504   ** of the table containing column.
100505   **
100506   ** The aConstraints[] array contains entries for all constraints
100507   ** on the current table.  That way we only have to compute it once
100508   ** even though we might try to pick the best index multiple times.
100509   ** For each attempt at picking an index, the order of tables in the
100510   ** join might be different so we have to recompute the usable flag
100511   ** each time.
100512   */
100513   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
100514   pUsage = pIdxInfo->aConstraintUsage;
100515   for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
100516     j = pIdxCons->iTermOffset;
100517     pTerm = &pWC->a[j];
100518     pIdxCons->usable = (pTerm->prereqRight&notReady) ? 0 : 1;
100519   }
100520   memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
100521   if( pIdxInfo->needToFreeIdxStr ){
100522     sqlite3_free(pIdxInfo->idxStr);
100523   }
100524   pIdxInfo->idxStr = 0;
100525   pIdxInfo->idxNum = 0;
100526   pIdxInfo->needToFreeIdxStr = 0;
100527   pIdxInfo->orderByConsumed = 0;
100528   /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
100529   pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);
100530   nOrderBy = pIdxInfo->nOrderBy;
100531   if( !pOrderBy ){
100532     pIdxInfo->nOrderBy = 0;
100533   }
100534
100535   if( vtabBestIndex(pParse, pTab, pIdxInfo) ){
100536     return;
100537   }
100538
100539   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
100540   for(i=0; i<pIdxInfo->nConstraint; i++){
100541     if( pUsage[i].argvIndex>0 ){
100542       pCost->used |= pWC->a[pIdxCons[i].iTermOffset].prereqRight;
100543     }
100544   }
100545
100546   /* If there is an ORDER BY clause, and the selected virtual table index
100547   ** does not satisfy it, increase the cost of the scan accordingly. This
100548   ** matches the processing for non-virtual tables in bestBtreeIndex().
100549   */
100550   rCost = pIdxInfo->estimatedCost;
100551   if( pOrderBy && pIdxInfo->orderByConsumed==0 ){
100552     rCost += estLog(rCost)*rCost;
100553   }
100554
100555   /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
100556   ** inital value of lowestCost in this loop. If it is, then the
100557   ** (cost<lowestCost) test below will never be true.
100558   ** 
100559   ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT 
100560   ** is defined.
100561   */
100562   if( (SQLITE_BIG_DBL/((double)2))<rCost ){
100563     pCost->rCost = (SQLITE_BIG_DBL/((double)2));
100564   }else{
100565     pCost->rCost = rCost;
100566   }
100567   pCost->plan.u.pVtabIdx = pIdxInfo;
100568   if( pIdxInfo->orderByConsumed ){
100569     pCost->plan.wsFlags |= WHERE_ORDERBY;
100570   }
100571   pCost->plan.nEq = 0;
100572   pIdxInfo->nOrderBy = nOrderBy;
100573
100574   /* Try to find a more efficient access pattern by using multiple indexes
100575   ** to optimize an OR expression within the WHERE clause. 
100576   */
100577   bestOrClauseIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
100578 }
100579 #endif /* SQLITE_OMIT_VIRTUALTABLE */
100580
100581 /*
100582 ** Argument pIdx is a pointer to an index structure that has an array of
100583 ** SQLITE_INDEX_SAMPLES evenly spaced samples of the first indexed column
100584 ** stored in Index.aSample. These samples divide the domain of values stored
100585 ** the index into (SQLITE_INDEX_SAMPLES+1) regions.
100586 ** Region 0 contains all values less than the first sample value. Region
100587 ** 1 contains values between the first and second samples.  Region 2 contains
100588 ** values between samples 2 and 3.  And so on.  Region SQLITE_INDEX_SAMPLES
100589 ** contains values larger than the last sample.
100590 **
100591 ** If the index contains many duplicates of a single value, then it is
100592 ** possible that two or more adjacent samples can hold the same value.
100593 ** When that is the case, the smallest possible region code is returned
100594 ** when roundUp is false and the largest possible region code is returned
100595 ** when roundUp is true.
100596 **
100597 ** If successful, this function determines which of the regions value 
100598 ** pVal lies in, sets *piRegion to the region index (a value between 0
100599 ** and SQLITE_INDEX_SAMPLES+1, inclusive) and returns SQLITE_OK.
100600 ** Or, if an OOM occurs while converting text values between encodings,
100601 ** SQLITE_NOMEM is returned and *piRegion is undefined.
100602 */
100603 #ifdef SQLITE_ENABLE_STAT2
100604 static int whereRangeRegion(
100605   Parse *pParse,              /* Database connection */
100606   Index *pIdx,                /* Index to consider domain of */
100607   sqlite3_value *pVal,        /* Value to consider */
100608   int roundUp,                /* Return largest valid region if true */
100609   int *piRegion               /* OUT: Region of domain in which value lies */
100610 ){
100611   assert( roundUp==0 || roundUp==1 );
100612   if( ALWAYS(pVal) ){
100613     IndexSample *aSample = pIdx->aSample;
100614     int i = 0;
100615     int eType = sqlite3_value_type(pVal);
100616
100617     if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
100618       double r = sqlite3_value_double(pVal);
100619       for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
100620         if( aSample[i].eType==SQLITE_NULL ) continue;
100621         if( aSample[i].eType>=SQLITE_TEXT ) break;
100622         if( roundUp ){
100623           if( aSample[i].u.r>r ) break;
100624         }else{
100625           if( aSample[i].u.r>=r ) break;
100626         }
100627       }
100628     }else if( eType==SQLITE_NULL ){
100629       i = 0;
100630       if( roundUp ){
100631         while( i<SQLITE_INDEX_SAMPLES && aSample[i].eType==SQLITE_NULL ) i++;
100632       }
100633     }else{ 
100634       sqlite3 *db = pParse->db;
100635       CollSeq *pColl;
100636       const u8 *z;
100637       int n;
100638
100639       /* pVal comes from sqlite3ValueFromExpr() so the type cannot be NULL */
100640       assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
100641
100642       if( eType==SQLITE_BLOB ){
100643         z = (const u8 *)sqlite3_value_blob(pVal);
100644         pColl = db->pDfltColl;
100645         assert( pColl->enc==SQLITE_UTF8 );
100646       }else{
100647         pColl = sqlite3GetCollSeq(db, SQLITE_UTF8, 0, *pIdx->azColl);
100648         if( pColl==0 ){
100649           sqlite3ErrorMsg(pParse, "no such collation sequence: %s",
100650                           *pIdx->azColl);
100651           return SQLITE_ERROR;
100652         }
100653         z = (const u8 *)sqlite3ValueText(pVal, pColl->enc);
100654         if( !z ){
100655           return SQLITE_NOMEM;
100656         }
100657         assert( z && pColl && pColl->xCmp );
100658       }
100659       n = sqlite3ValueBytes(pVal, pColl->enc);
100660
100661       for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
100662         int c;
100663         int eSampletype = aSample[i].eType;
100664         if( eSampletype==SQLITE_NULL || eSampletype<eType ) continue;
100665         if( (eSampletype!=eType) ) break;
100666 #ifndef SQLITE_OMIT_UTF16
100667         if( pColl->enc!=SQLITE_UTF8 ){
100668           int nSample;
100669           char *zSample = sqlite3Utf8to16(
100670               db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample
100671           );
100672           if( !zSample ){
100673             assert( db->mallocFailed );
100674             return SQLITE_NOMEM;
100675           }
100676           c = pColl->xCmp(pColl->pUser, nSample, zSample, n, z);
100677           sqlite3DbFree(db, zSample);
100678         }else
100679 #endif
100680         {
100681           c = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z);
100682         }
100683         if( c-roundUp>=0 ) break;
100684       }
100685     }
100686
100687     assert( i>=0 && i<=SQLITE_INDEX_SAMPLES );
100688     *piRegion = i;
100689   }
100690   return SQLITE_OK;
100691 }
100692 #endif   /* #ifdef SQLITE_ENABLE_STAT2 */
100693
100694 /*
100695 ** If expression pExpr represents a literal value, set *pp to point to
100696 ** an sqlite3_value structure containing the same value, with affinity
100697 ** aff applied to it, before returning. It is the responsibility of the 
100698 ** caller to eventually release this structure by passing it to 
100699 ** sqlite3ValueFree().
100700 **
100701 ** If the current parse is a recompile (sqlite3Reprepare()) and pExpr
100702 ** is an SQL variable that currently has a non-NULL value bound to it,
100703 ** create an sqlite3_value structure containing this value, again with
100704 ** affinity aff applied to it, instead.
100705 **
100706 ** If neither of the above apply, set *pp to NULL.
100707 **
100708 ** If an error occurs, return an error code. Otherwise, SQLITE_OK.
100709 */
100710 #ifdef SQLITE_ENABLE_STAT2
100711 static int valueFromExpr(
100712   Parse *pParse, 
100713   Expr *pExpr, 
100714   u8 aff, 
100715   sqlite3_value **pp
100716 ){
100717   if( pExpr->op==TK_VARIABLE
100718    || (pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
100719   ){
100720     int iVar = pExpr->iColumn;
100721     sqlite3VdbeSetVarmask(pParse->pVdbe, iVar); /* IMP: R-23257-02778 */
100722     *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);
100723     return SQLITE_OK;
100724   }
100725   return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
100726 }
100727 #endif
100728
100729 /*
100730 ** This function is used to estimate the number of rows that will be visited
100731 ** by scanning an index for a range of values. The range may have an upper
100732 ** bound, a lower bound, or both. The WHERE clause terms that set the upper
100733 ** and lower bounds are represented by pLower and pUpper respectively. For
100734 ** example, assuming that index p is on t1(a):
100735 **
100736 **   ... FROM t1 WHERE a > ? AND a < ? ...
100737 **                    |_____|   |_____|
100738 **                       |         |
100739 **                     pLower    pUpper
100740 **
100741 ** If either of the upper or lower bound is not present, then NULL is passed in
100742 ** place of the corresponding WhereTerm.
100743 **
100744 ** The nEq parameter is passed the index of the index column subject to the
100745 ** range constraint. Or, equivalently, the number of equality constraints
100746 ** optimized by the proposed index scan. For example, assuming index p is
100747 ** on t1(a, b), and the SQL query is:
100748 **
100749 **   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
100750 **
100751 ** then nEq should be passed the value 1 (as the range restricted column,
100752 ** b, is the second left-most column of the index). Or, if the query is:
100753 **
100754 **   ... FROM t1 WHERE a > ? AND a < ? ...
100755 **
100756 ** then nEq should be passed 0.
100757 **
100758 ** The returned value is an integer between 1 and 100, inclusive. A return
100759 ** value of 1 indicates that the proposed range scan is expected to visit
100760 ** approximately 1/100th (1%) of the rows selected by the nEq equality
100761 ** constraints (if any). A return value of 100 indicates that it is expected
100762 ** that the range scan will visit every row (100%) selected by the equality
100763 ** constraints.
100764 **
100765 ** In the absence of sqlite_stat2 ANALYZE data, each range inequality
100766 ** reduces the search space by 3/4ths.  Hence a single constraint (x>?)
100767 ** results in a return of 25 and a range constraint (x>? AND x<?) results
100768 ** in a return of 6.
100769 */
100770 static int whereRangeScanEst(
100771   Parse *pParse,       /* Parsing & code generating context */
100772   Index *p,            /* The index containing the range-compared column; "x" */
100773   int nEq,             /* index into p->aCol[] of the range-compared column */
100774   WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
100775   WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
100776   int *piEst           /* OUT: Return value */
100777 ){
100778   int rc = SQLITE_OK;
100779
100780 #ifdef SQLITE_ENABLE_STAT2
100781
100782   if( nEq==0 && p->aSample ){
100783     sqlite3_value *pLowerVal = 0;
100784     sqlite3_value *pUpperVal = 0;
100785     int iEst;
100786     int iLower = 0;
100787     int iUpper = SQLITE_INDEX_SAMPLES;
100788     int roundUpUpper = 0;
100789     int roundUpLower = 0;
100790     u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
100791
100792     if( pLower ){
100793       Expr *pExpr = pLower->pExpr->pRight;
100794       rc = valueFromExpr(pParse, pExpr, aff, &pLowerVal);
100795       assert( pLower->eOperator==WO_GT || pLower->eOperator==WO_GE );
100796       roundUpLower = (pLower->eOperator==WO_GT) ?1:0;
100797     }
100798     if( rc==SQLITE_OK && pUpper ){
100799       Expr *pExpr = pUpper->pExpr->pRight;
100800       rc = valueFromExpr(pParse, pExpr, aff, &pUpperVal);
100801       assert( pUpper->eOperator==WO_LT || pUpper->eOperator==WO_LE );
100802       roundUpUpper = (pUpper->eOperator==WO_LE) ?1:0;
100803     }
100804
100805     if( rc!=SQLITE_OK || (pLowerVal==0 && pUpperVal==0) ){
100806       sqlite3ValueFree(pLowerVal);
100807       sqlite3ValueFree(pUpperVal);
100808       goto range_est_fallback;
100809     }else if( pLowerVal==0 ){
100810       rc = whereRangeRegion(pParse, p, pUpperVal, roundUpUpper, &iUpper);
100811       if( pLower ) iLower = iUpper/2;
100812     }else if( pUpperVal==0 ){
100813       rc = whereRangeRegion(pParse, p, pLowerVal, roundUpLower, &iLower);
100814       if( pUpper ) iUpper = (iLower + SQLITE_INDEX_SAMPLES + 1)/2;
100815     }else{
100816       rc = whereRangeRegion(pParse, p, pUpperVal, roundUpUpper, &iUpper);
100817       if( rc==SQLITE_OK ){
100818         rc = whereRangeRegion(pParse, p, pLowerVal, roundUpLower, &iLower);
100819       }
100820     }
100821     WHERETRACE(("range scan regions: %d..%d\n", iLower, iUpper));
100822
100823     iEst = iUpper - iLower;
100824     testcase( iEst==SQLITE_INDEX_SAMPLES );
100825     assert( iEst<=SQLITE_INDEX_SAMPLES );
100826     if( iEst<1 ){
100827       *piEst = 50/SQLITE_INDEX_SAMPLES;
100828     }else{
100829       *piEst = (iEst*100)/SQLITE_INDEX_SAMPLES;
100830     }
100831     sqlite3ValueFree(pLowerVal);
100832     sqlite3ValueFree(pUpperVal);
100833     return rc;
100834   }
100835 range_est_fallback:
100836 #else
100837   UNUSED_PARAMETER(pParse);
100838   UNUSED_PARAMETER(p);
100839   UNUSED_PARAMETER(nEq);
100840 #endif
100841   assert( pLower || pUpper );
100842   *piEst = 100;
100843   if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ) *piEst /= 4;
100844   if( pUpper ) *piEst /= 4;
100845   return rc;
100846 }
100847
100848 #ifdef SQLITE_ENABLE_STAT2
100849 /*
100850 ** Estimate the number of rows that will be returned based on
100851 ** an equality constraint x=VALUE and where that VALUE occurs in
100852 ** the histogram data.  This only works when x is the left-most
100853 ** column of an index and sqlite_stat2 histogram data is available
100854 ** for that index.  When pExpr==NULL that means the constraint is
100855 ** "x IS NULL" instead of "x=VALUE".
100856 **
100857 ** Write the estimated row count into *pnRow and return SQLITE_OK. 
100858 ** If unable to make an estimate, leave *pnRow unchanged and return
100859 ** non-zero.
100860 **
100861 ** This routine can fail if it is unable to load a collating sequence
100862 ** required for string comparison, or if unable to allocate memory
100863 ** for a UTF conversion required for comparison.  The error is stored
100864 ** in the pParse structure.
100865 */
100866 static int whereEqualScanEst(
100867   Parse *pParse,       /* Parsing & code generating context */
100868   Index *p,            /* The index whose left-most column is pTerm */
100869   Expr *pExpr,         /* Expression for VALUE in the x=VALUE constraint */
100870   double *pnRow        /* Write the revised row estimate here */
100871 ){
100872   sqlite3_value *pRhs = 0;  /* VALUE on right-hand side of pTerm */
100873   int iLower, iUpper;       /* Range of histogram regions containing pRhs */
100874   u8 aff;                   /* Column affinity */
100875   int rc;                   /* Subfunction return code */
100876   double nRowEst;           /* New estimate of the number of rows */
100877
100878   assert( p->aSample!=0 );
100879   aff = p->pTable->aCol[p->aiColumn[0]].affinity;
100880   if( pExpr ){
100881     rc = valueFromExpr(pParse, pExpr, aff, &pRhs);
100882     if( rc ) goto whereEqualScanEst_cancel;
100883   }else{
100884     pRhs = sqlite3ValueNew(pParse->db);
100885   }
100886   if( pRhs==0 ) return SQLITE_NOTFOUND;
100887   rc = whereRangeRegion(pParse, p, pRhs, 0, &iLower);
100888   if( rc ) goto whereEqualScanEst_cancel;
100889   rc = whereRangeRegion(pParse, p, pRhs, 1, &iUpper);
100890   if( rc ) goto whereEqualScanEst_cancel;
100891   WHERETRACE(("equality scan regions: %d..%d\n", iLower, iUpper));
100892   if( iLower>=iUpper ){
100893     nRowEst = p->aiRowEst[0]/(SQLITE_INDEX_SAMPLES*2);
100894     if( nRowEst<*pnRow ) *pnRow = nRowEst;
100895   }else{
100896     nRowEst = (iUpper-iLower)*p->aiRowEst[0]/SQLITE_INDEX_SAMPLES;
100897     *pnRow = nRowEst;
100898   }
100899
100900 whereEqualScanEst_cancel:
100901   sqlite3ValueFree(pRhs);
100902   return rc;
100903 }
100904 #endif /* defined(SQLITE_ENABLE_STAT2) */
100905
100906 #ifdef SQLITE_ENABLE_STAT2
100907 /*
100908 ** Estimate the number of rows that will be returned based on
100909 ** an IN constraint where the right-hand side of the IN operator
100910 ** is a list of values.  Example:
100911 **
100912 **        WHERE x IN (1,2,3,4)
100913 **
100914 ** Write the estimated row count into *pnRow and return SQLITE_OK. 
100915 ** If unable to make an estimate, leave *pnRow unchanged and return
100916 ** non-zero.
100917 **
100918 ** This routine can fail if it is unable to load a collating sequence
100919 ** required for string comparison, or if unable to allocate memory
100920 ** for a UTF conversion required for comparison.  The error is stored
100921 ** in the pParse structure.
100922 */
100923 static int whereInScanEst(
100924   Parse *pParse,       /* Parsing & code generating context */
100925   Index *p,            /* The index whose left-most column is pTerm */
100926   ExprList *pList,     /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
100927   double *pnRow        /* Write the revised row estimate here */
100928 ){
100929   sqlite3_value *pVal = 0;  /* One value from list */
100930   int iLower, iUpper;       /* Range of histogram regions containing pRhs */
100931   u8 aff;                   /* Column affinity */
100932   int rc = SQLITE_OK;       /* Subfunction return code */
100933   double nRowEst;           /* New estimate of the number of rows */
100934   int nSpan = 0;            /* Number of histogram regions spanned */
100935   int nSingle = 0;          /* Histogram regions hit by a single value */
100936   int nNotFound = 0;        /* Count of values that are not constants */
100937   int i;                               /* Loop counter */
100938   u8 aSpan[SQLITE_INDEX_SAMPLES+1];    /* Histogram regions that are spanned */
100939   u8 aSingle[SQLITE_INDEX_SAMPLES+1];  /* Histogram regions hit once */
100940
100941   assert( p->aSample!=0 );
100942   aff = p->pTable->aCol[p->aiColumn[0]].affinity;
100943   memset(aSpan, 0, sizeof(aSpan));
100944   memset(aSingle, 0, sizeof(aSingle));
100945   for(i=0; i<pList->nExpr; i++){
100946     sqlite3ValueFree(pVal);
100947     rc = valueFromExpr(pParse, pList->a[i].pExpr, aff, &pVal);
100948     if( rc ) break;
100949     if( pVal==0 || sqlite3_value_type(pVal)==SQLITE_NULL ){
100950       nNotFound++;
100951       continue;
100952     }
100953     rc = whereRangeRegion(pParse, p, pVal, 0, &iLower);
100954     if( rc ) break;
100955     rc = whereRangeRegion(pParse, p, pVal, 1, &iUpper);
100956     if( rc ) break;
100957     if( iLower>=iUpper ){
100958       aSingle[iLower] = 1;
100959     }else{
100960       assert( iLower>=0 && iUpper<=SQLITE_INDEX_SAMPLES );
100961       while( iLower<iUpper ) aSpan[iLower++] = 1;
100962     }
100963   }
100964   if( rc==SQLITE_OK ){
100965     for(i=nSpan=0; i<=SQLITE_INDEX_SAMPLES; i++){
100966       if( aSpan[i] ){
100967         nSpan++;
100968       }else if( aSingle[i] ){
100969         nSingle++;
100970       }
100971     }
100972     nRowEst = (nSpan*2+nSingle)*p->aiRowEst[0]/(2*SQLITE_INDEX_SAMPLES)
100973                + nNotFound*p->aiRowEst[1];
100974     if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0];
100975     *pnRow = nRowEst;
100976     WHERETRACE(("IN row estimate: nSpan=%d, nSingle=%d, nNotFound=%d, est=%g\n",
100977                  nSpan, nSingle, nNotFound, nRowEst));
100978   }
100979   sqlite3ValueFree(pVal);
100980   return rc;
100981 }
100982 #endif /* defined(SQLITE_ENABLE_STAT2) */
100983
100984
100985 /*
100986 ** Find the best query plan for accessing a particular table.  Write the
100987 ** best query plan and its cost into the WhereCost object supplied as the
100988 ** last parameter.
100989 **
100990 ** The lowest cost plan wins.  The cost is an estimate of the amount of
100991 ** CPU and disk I/O needed to process the requested result.
100992 ** Factors that influence cost include:
100993 **
100994 **    *  The estimated number of rows that will be retrieved.  (The
100995 **       fewer the better.)
100996 **
100997 **    *  Whether or not sorting must occur.
100998 **
100999 **    *  Whether or not there must be separate lookups in the
101000 **       index and in the main table.
101001 **
101002 ** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in
101003 ** the SQL statement, then this function only considers plans using the 
101004 ** named index. If no such plan is found, then the returned cost is
101005 ** SQLITE_BIG_DBL. If a plan is found that uses the named index, 
101006 ** then the cost is calculated in the usual way.
101007 **
101008 ** If a NOT INDEXED clause (pSrc->notIndexed!=0) was attached to the table 
101009 ** in the SELECT statement, then no indexes are considered. However, the 
101010 ** selected plan may still take advantage of the built-in rowid primary key
101011 ** index.
101012 */
101013 static void bestBtreeIndex(
101014   Parse *pParse,              /* The parsing context */
101015   WhereClause *pWC,           /* The WHERE clause */
101016   struct SrcList_item *pSrc,  /* The FROM clause term to search */
101017   Bitmask notReady,           /* Mask of cursors not available for indexing */
101018   Bitmask notValid,           /* Cursors not available for any purpose */
101019   ExprList *pOrderBy,         /* The ORDER BY clause */
101020   WhereCost *pCost            /* Lowest cost query plan */
101021 ){
101022   int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
101023   Index *pProbe;              /* An index we are evaluating */
101024   Index *pIdx;                /* Copy of pProbe, or zero for IPK index */
101025   int eqTermMask;             /* Current mask of valid equality operators */
101026   int idxEqTermMask;          /* Index mask of valid equality operators */
101027   Index sPk;                  /* A fake index object for the primary key */
101028   unsigned int aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
101029   int aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
101030   int wsFlagMask;             /* Allowed flags in pCost->plan.wsFlag */
101031
101032   /* Initialize the cost to a worst-case value */
101033   memset(pCost, 0, sizeof(*pCost));
101034   pCost->rCost = SQLITE_BIG_DBL;
101035
101036   /* If the pSrc table is the right table of a LEFT JOIN then we may not
101037   ** use an index to satisfy IS NULL constraints on that table.  This is
101038   ** because columns might end up being NULL if the table does not match -
101039   ** a circumstance which the index cannot help us discover.  Ticket #2177.
101040   */
101041   if( pSrc->jointype & JT_LEFT ){
101042     idxEqTermMask = WO_EQ|WO_IN;
101043   }else{
101044     idxEqTermMask = WO_EQ|WO_IN|WO_ISNULL;
101045   }
101046
101047   if( pSrc->pIndex ){
101048     /* An INDEXED BY clause specifies a particular index to use */
101049     pIdx = pProbe = pSrc->pIndex;
101050     wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
101051     eqTermMask = idxEqTermMask;
101052   }else{
101053     /* There is no INDEXED BY clause.  Create a fake Index object in local
101054     ** variable sPk to represent the rowid primary key index.  Make this
101055     ** fake index the first in a chain of Index objects with all of the real
101056     ** indices to follow */
101057     Index *pFirst;                  /* First of real indices on the table */
101058     memset(&sPk, 0, sizeof(Index));
101059     sPk.nColumn = 1;
101060     sPk.aiColumn = &aiColumnPk;
101061     sPk.aiRowEst = aiRowEstPk;
101062     sPk.onError = OE_Replace;
101063     sPk.pTable = pSrc->pTab;
101064     aiRowEstPk[0] = pSrc->pTab->nRowEst;
101065     aiRowEstPk[1] = 1;
101066     pFirst = pSrc->pTab->pIndex;
101067     if( pSrc->notIndexed==0 ){
101068       /* The real indices of the table are only considered if the
101069       ** NOT INDEXED qualifier is omitted from the FROM clause */
101070       sPk.pNext = pFirst;
101071     }
101072     pProbe = &sPk;
101073     wsFlagMask = ~(
101074         WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE
101075     );
101076     eqTermMask = WO_EQ|WO_IN;
101077     pIdx = 0;
101078   }
101079
101080   /* Loop over all indices looking for the best one to use
101081   */
101082   for(; pProbe; pIdx=pProbe=pProbe->pNext){
101083     const unsigned int * const aiRowEst = pProbe->aiRowEst;
101084     double cost;                /* Cost of using pProbe */
101085     double nRow;                /* Estimated number of rows in result set */
101086     double log10N;              /* base-10 logarithm of nRow (inexact) */
101087     int rev;                    /* True to scan in reverse order */
101088     int wsFlags = 0;
101089     Bitmask used = 0;
101090
101091     /* The following variables are populated based on the properties of
101092     ** index being evaluated. They are then used to determine the expected
101093     ** cost and number of rows returned.
101094     **
101095     **  nEq: 
101096     **    Number of equality terms that can be implemented using the index.
101097     **    In other words, the number of initial fields in the index that
101098     **    are used in == or IN or NOT NULL constraints of the WHERE clause.
101099     **
101100     **  nInMul:  
101101     **    The "in-multiplier". This is an estimate of how many seek operations 
101102     **    SQLite must perform on the index in question. For example, if the 
101103     **    WHERE clause is:
101104     **
101105     **      WHERE a IN (1, 2, 3) AND b IN (4, 5, 6)
101106     **
101107     **    SQLite must perform 9 lookups on an index on (a, b), so nInMul is 
101108     **    set to 9. Given the same schema and either of the following WHERE 
101109     **    clauses:
101110     **
101111     **      WHERE a =  1
101112     **      WHERE a >= 2
101113     **
101114     **    nInMul is set to 1.
101115     **
101116     **    If there exists a WHERE term of the form "x IN (SELECT ...)", then 
101117     **    the sub-select is assumed to return 25 rows for the purposes of 
101118     **    determining nInMul.
101119     **
101120     **  bInEst:  
101121     **    Set to true if there was at least one "x IN (SELECT ...)" term used 
101122     **    in determining the value of nInMul.  Note that the RHS of the
101123     **    IN operator must be a SELECT, not a value list, for this variable
101124     **    to be true.
101125     **
101126     **  estBound:
101127     **    An estimate on the amount of the table that must be searched.  A
101128     **    value of 100 means the entire table is searched.  Range constraints
101129     **    might reduce this to a value less than 100 to indicate that only
101130     **    a fraction of the table needs searching.  In the absence of
101131     **    sqlite_stat2 ANALYZE data, a single inequality reduces the search
101132     **    space to 1/4rd its original size.  So an x>? constraint reduces
101133     **    estBound to 25.  Two constraints (x>? AND x<?) reduce estBound to 6.
101134     **
101135     **  bSort:   
101136     **    Boolean. True if there is an ORDER BY clause that will require an 
101137     **    external sort (i.e. scanning the index being evaluated will not 
101138     **    correctly order records).
101139     **
101140     **  bLookup: 
101141     **    Boolean. True if a table lookup is required for each index entry
101142     **    visited.  In other words, true if this is not a covering index.
101143     **    This is always false for the rowid primary key index of a table.
101144     **    For other indexes, it is true unless all the columns of the table
101145     **    used by the SELECT statement are present in the index (such an
101146     **    index is sometimes described as a covering index).
101147     **    For example, given the index on (a, b), the second of the following 
101148     **    two queries requires table b-tree lookups in order to find the value
101149     **    of column c, but the first does not because columns a and b are
101150     **    both available in the index.
101151     **
101152     **             SELECT a, b    FROM tbl WHERE a = 1;
101153     **             SELECT a, b, c FROM tbl WHERE a = 1;
101154     */
101155     int nEq;                      /* Number of == or IN terms matching index */
101156     int bInEst = 0;               /* True if "x IN (SELECT...)" seen */
101157     int nInMul = 1;               /* Number of distinct equalities to lookup */
101158     int estBound = 100;           /* Estimated reduction in search space */
101159     int nBound = 0;               /* Number of range constraints seen */
101160     int bSort = 0;                /* True if external sort required */
101161     int bLookup = 0;              /* True if not a covering index */
101162     WhereTerm *pTerm;             /* A single term of the WHERE clause */
101163 #ifdef SQLITE_ENABLE_STAT2
101164     WhereTerm *pFirstTerm = 0;    /* First term matching the index */
101165 #endif
101166
101167     /* Determine the values of nEq and nInMul */
101168     for(nEq=0; nEq<pProbe->nColumn; nEq++){
101169       int j = pProbe->aiColumn[nEq];
101170       pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pIdx);
101171       if( pTerm==0 ) break;
101172       wsFlags |= (WHERE_COLUMN_EQ|WHERE_ROWID_EQ);
101173       if( pTerm->eOperator & WO_IN ){
101174         Expr *pExpr = pTerm->pExpr;
101175         wsFlags |= WHERE_COLUMN_IN;
101176         if( ExprHasProperty(pExpr, EP_xIsSelect) ){
101177           /* "x IN (SELECT ...)":  Assume the SELECT returns 25 rows */
101178           nInMul *= 25;
101179           bInEst = 1;
101180         }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
101181           /* "x IN (value, value, ...)" */
101182           nInMul *= pExpr->x.pList->nExpr;
101183         }
101184       }else if( pTerm->eOperator & WO_ISNULL ){
101185         wsFlags |= WHERE_COLUMN_NULL;
101186       }
101187 #ifdef SQLITE_ENABLE_STAT2
101188       if( nEq==0 && pProbe->aSample ) pFirstTerm = pTerm;
101189 #endif
101190       used |= pTerm->prereqRight;
101191     }
101192
101193     /* Determine the value of estBound. */
101194     if( nEq<pProbe->nColumn && pProbe->bUnordered==0 ){
101195       int j = pProbe->aiColumn[nEq];
101196       if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){
101197         WhereTerm *pTop = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pIdx);
101198         WhereTerm *pBtm = findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pIdx);
101199         whereRangeScanEst(pParse, pProbe, nEq, pBtm, pTop, &estBound);
101200         if( pTop ){
101201           nBound = 1;
101202           wsFlags |= WHERE_TOP_LIMIT;
101203           used |= pTop->prereqRight;
101204         }
101205         if( pBtm ){
101206           nBound++;
101207           wsFlags |= WHERE_BTM_LIMIT;
101208           used |= pBtm->prereqRight;
101209         }
101210         wsFlags |= (WHERE_COLUMN_RANGE|WHERE_ROWID_RANGE);
101211       }
101212     }else if( pProbe->onError!=OE_None ){
101213       testcase( wsFlags & WHERE_COLUMN_IN );
101214       testcase( wsFlags & WHERE_COLUMN_NULL );
101215       if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){
101216         wsFlags |= WHERE_UNIQUE;
101217       }
101218     }
101219
101220     /* If there is an ORDER BY clause and the index being considered will
101221     ** naturally scan rows in the required order, set the appropriate flags
101222     ** in wsFlags. Otherwise, if there is an ORDER BY clause but the index
101223     ** will scan rows in a different order, set the bSort variable.  */
101224     if( pOrderBy ){
101225       if( (wsFlags & WHERE_COLUMN_IN)==0
101226         && pProbe->bUnordered==0
101227         && isSortingIndex(pParse, pWC->pMaskSet, pProbe, iCur, pOrderBy,
101228                           nEq, wsFlags, &rev)
101229       ){
101230         wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_ORDERBY;
101231         wsFlags |= (rev ? WHERE_REVERSE : 0);
101232       }else{
101233         bSort = 1;
101234       }
101235     }
101236
101237     /* If currently calculating the cost of using an index (not the IPK
101238     ** index), determine if all required column data may be obtained without 
101239     ** using the main table (i.e. if the index is a covering
101240     ** index for this query). If it is, set the WHERE_IDX_ONLY flag in
101241     ** wsFlags. Otherwise, set the bLookup variable to true.  */
101242     if( pIdx && wsFlags ){
101243       Bitmask m = pSrc->colUsed;
101244       int j;
101245       for(j=0; j<pIdx->nColumn; j++){
101246         int x = pIdx->aiColumn[j];
101247         if( x<BMS-1 ){
101248           m &= ~(((Bitmask)1)<<x);
101249         }
101250       }
101251       if( m==0 ){
101252         wsFlags |= WHERE_IDX_ONLY;
101253       }else{
101254         bLookup = 1;
101255       }
101256     }
101257
101258     /*
101259     ** Estimate the number of rows of output.  For an "x IN (SELECT...)"
101260     ** constraint, do not let the estimate exceed half the rows in the table.
101261     */
101262     nRow = (double)(aiRowEst[nEq] * nInMul);
101263     if( bInEst && nRow*2>aiRowEst[0] ){
101264       nRow = aiRowEst[0]/2;
101265       nInMul = (int)(nRow / aiRowEst[nEq]);
101266     }
101267
101268 #ifdef SQLITE_ENABLE_STAT2
101269     /* If the constraint is of the form x=VALUE and histogram
101270     ** data is available for column x, then it might be possible
101271     ** to get a better estimate on the number of rows based on
101272     ** VALUE and how common that value is according to the histogram.
101273     */
101274     if( nRow>(double)1 && nEq==1 && pFirstTerm!=0 ){
101275       if( pFirstTerm->eOperator & (WO_EQ|WO_ISNULL) ){
101276         testcase( pFirstTerm->eOperator==WO_EQ );
101277         testcase( pFirstTerm->eOperator==WO_ISNULL );
101278         whereEqualScanEst(pParse, pProbe, pFirstTerm->pExpr->pRight, &nRow);
101279       }else if( pFirstTerm->eOperator==WO_IN && bInEst==0 ){
101280         whereInScanEst(pParse, pProbe, pFirstTerm->pExpr->x.pList, &nRow);
101281       }
101282     }
101283 #endif /* SQLITE_ENABLE_STAT2 */
101284
101285     /* Adjust the number of output rows and downward to reflect rows
101286     ** that are excluded by range constraints.
101287     */
101288     nRow = (nRow * (double)estBound) / (double)100;
101289     if( nRow<1 ) nRow = 1;
101290
101291     /* Experiments run on real SQLite databases show that the time needed
101292     ** to do a binary search to locate a row in a table or index is roughly
101293     ** log10(N) times the time to move from one row to the next row within
101294     ** a table or index.  The actual times can vary, with the size of
101295     ** records being an important factor.  Both moves and searches are
101296     ** slower with larger records, presumably because fewer records fit
101297     ** on one page and hence more pages have to be fetched.
101298     **
101299     ** The ANALYZE command and the sqlite_stat1 and sqlite_stat2 tables do
101300     ** not give us data on the relative sizes of table and index records.
101301     ** So this computation assumes table records are about twice as big
101302     ** as index records
101303     */
101304     if( (wsFlags & WHERE_NOT_FULLSCAN)==0 ){
101305       /* The cost of a full table scan is a number of move operations equal
101306       ** to the number of rows in the table.
101307       **
101308       ** We add an additional 4x penalty to full table scans.  This causes
101309       ** the cost function to err on the side of choosing an index over
101310       ** choosing a full scan.  This 4x full-scan penalty is an arguable
101311       ** decision and one which we expect to revisit in the future.  But
101312       ** it seems to be working well enough at the moment.
101313       */
101314       cost = aiRowEst[0]*4;
101315     }else{
101316       log10N = estLog(aiRowEst[0]);
101317       cost = nRow;
101318       if( pIdx ){
101319         if( bLookup ){
101320           /* For an index lookup followed by a table lookup:
101321           **    nInMul index searches to find the start of each index range
101322           **  + nRow steps through the index
101323           **  + nRow table searches to lookup the table entry using the rowid
101324           */
101325           cost += (nInMul + nRow)*log10N;
101326         }else{
101327           /* For a covering index:
101328           **     nInMul index searches to find the initial entry 
101329           **   + nRow steps through the index
101330           */
101331           cost += nInMul*log10N;
101332         }
101333       }else{
101334         /* For a rowid primary key lookup:
101335         **    nInMult table searches to find the initial entry for each range
101336         **  + nRow steps through the table
101337         */
101338         cost += nInMul*log10N;
101339       }
101340     }
101341
101342     /* Add in the estimated cost of sorting the result.  Actual experimental
101343     ** measurements of sorting performance in SQLite show that sorting time
101344     ** adds C*N*log10(N) to the cost, where N is the number of rows to be 
101345     ** sorted and C is a factor between 1.95 and 4.3.  We will split the
101346     ** difference and select C of 3.0.
101347     */
101348     if( bSort ){
101349       cost += nRow*estLog(nRow)*3;
101350     }
101351
101352     /**** Cost of using this index has now been computed ****/
101353
101354     /* If there are additional constraints on this table that cannot
101355     ** be used with the current index, but which might lower the number
101356     ** of output rows, adjust the nRow value accordingly.  This only 
101357     ** matters if the current index is the least costly, so do not bother
101358     ** with this step if we already know this index will not be chosen.
101359     ** Also, never reduce the output row count below 2 using this step.
101360     **
101361     ** It is critical that the notValid mask be used here instead of
101362     ** the notReady mask.  When computing an "optimal" index, the notReady
101363     ** mask will only have one bit set - the bit for the current table.
101364     ** The notValid mask, on the other hand, always has all bits set for
101365     ** tables that are not in outer loops.  If notReady is used here instead
101366     ** of notValid, then a optimal index that depends on inner joins loops
101367     ** might be selected even when there exists an optimal index that has
101368     ** no such dependency.
101369     */
101370     if( nRow>2 && cost<=pCost->rCost ){
101371       int k;                       /* Loop counter */
101372       int nSkipEq = nEq;           /* Number of == constraints to skip */
101373       int nSkipRange = nBound;     /* Number of < constraints to skip */
101374       Bitmask thisTab;             /* Bitmap for pSrc */
101375
101376       thisTab = getMask(pWC->pMaskSet, iCur);
101377       for(pTerm=pWC->a, k=pWC->nTerm; nRow>2 && k; k--, pTerm++){
101378         if( pTerm->wtFlags & TERM_VIRTUAL ) continue;
101379         if( (pTerm->prereqAll & notValid)!=thisTab ) continue;
101380         if( pTerm->eOperator & (WO_EQ|WO_IN|WO_ISNULL) ){
101381           if( nSkipEq ){
101382             /* Ignore the first nEq equality matches since the index
101383             ** has already accounted for these */
101384             nSkipEq--;
101385           }else{
101386             /* Assume each additional equality match reduces the result
101387             ** set size by a factor of 10 */
101388             nRow /= 10;
101389           }
101390         }else if( pTerm->eOperator & (WO_LT|WO_LE|WO_GT|WO_GE) ){
101391           if( nSkipRange ){
101392             /* Ignore the first nSkipRange range constraints since the index
101393             ** has already accounted for these */
101394             nSkipRange--;
101395           }else{
101396             /* Assume each additional range constraint reduces the result
101397             ** set size by a factor of 3.  Indexed range constraints reduce
101398             ** the search space by a larger factor: 4.  We make indexed range
101399             ** more selective intentionally because of the subjective 
101400             ** observation that indexed range constraints really are more
101401             ** selective in practice, on average. */
101402             nRow /= 3;
101403           }
101404         }else if( pTerm->eOperator!=WO_NOOP ){
101405           /* Any other expression lowers the output row count by half */
101406           nRow /= 2;
101407         }
101408       }
101409       if( nRow<2 ) nRow = 2;
101410     }
101411
101412
101413     WHERETRACE((
101414       "%s(%s): nEq=%d nInMul=%d estBound=%d bSort=%d bLookup=%d wsFlags=0x%x\n"
101415       "         notReady=0x%llx log10N=%.1f nRow=%.1f cost=%.1f used=0x%llx\n",
101416       pSrc->pTab->zName, (pIdx ? pIdx->zName : "ipk"), 
101417       nEq, nInMul, estBound, bSort, bLookup, wsFlags,
101418       notReady, log10N, nRow, cost, used
101419     ));
101420
101421     /* If this index is the best we have seen so far, then record this
101422     ** index and its cost in the pCost structure.
101423     */
101424     if( (!pIdx || wsFlags)
101425      && (cost<pCost->rCost || (cost<=pCost->rCost && nRow<pCost->plan.nRow))
101426     ){
101427       pCost->rCost = cost;
101428       pCost->used = used;
101429       pCost->plan.nRow = nRow;
101430       pCost->plan.wsFlags = (wsFlags&wsFlagMask);
101431       pCost->plan.nEq = nEq;
101432       pCost->plan.u.pIdx = pIdx;
101433     }
101434
101435     /* If there was an INDEXED BY clause, then only that one index is
101436     ** considered. */
101437     if( pSrc->pIndex ) break;
101438
101439     /* Reset masks for the next index in the loop */
101440     wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
101441     eqTermMask = idxEqTermMask;
101442   }
101443
101444   /* If there is no ORDER BY clause and the SQLITE_ReverseOrder flag
101445   ** is set, then reverse the order that the index will be scanned
101446   ** in. This is used for application testing, to help find cases
101447   ** where application behaviour depends on the (undefined) order that
101448   ** SQLite outputs rows in in the absence of an ORDER BY clause.  */
101449   if( !pOrderBy && pParse->db->flags & SQLITE_ReverseOrder ){
101450     pCost->plan.wsFlags |= WHERE_REVERSE;
101451   }
101452
101453   assert( pOrderBy || (pCost->plan.wsFlags&WHERE_ORDERBY)==0 );
101454   assert( pCost->plan.u.pIdx==0 || (pCost->plan.wsFlags&WHERE_ROWID_EQ)==0 );
101455   assert( pSrc->pIndex==0 
101456        || pCost->plan.u.pIdx==0 
101457        || pCost->plan.u.pIdx==pSrc->pIndex 
101458   );
101459
101460   WHERETRACE(("best index is: %s\n", 
101461     ((pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ? "none" : 
101462          pCost->plan.u.pIdx ? pCost->plan.u.pIdx->zName : "ipk")
101463   ));
101464   
101465   bestOrClauseIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
101466   bestAutomaticIndex(pParse, pWC, pSrc, notReady, pCost);
101467   pCost->plan.wsFlags |= eqTermMask;
101468 }
101469
101470 /*
101471 ** Find the query plan for accessing table pSrc->pTab. Write the
101472 ** best query plan and its cost into the WhereCost object supplied 
101473 ** as the last parameter. This function may calculate the cost of
101474 ** both real and virtual table scans.
101475 */
101476 static void bestIndex(
101477   Parse *pParse,              /* The parsing context */
101478   WhereClause *pWC,           /* The WHERE clause */
101479   struct SrcList_item *pSrc,  /* The FROM clause term to search */
101480   Bitmask notReady,           /* Mask of cursors not available for indexing */
101481   Bitmask notValid,           /* Cursors not available for any purpose */
101482   ExprList *pOrderBy,         /* The ORDER BY clause */
101483   WhereCost *pCost            /* Lowest cost query plan */
101484 ){
101485 #ifndef SQLITE_OMIT_VIRTUALTABLE
101486   if( IsVirtual(pSrc->pTab) ){
101487     sqlite3_index_info *p = 0;
101488     bestVirtualIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost,&p);
101489     if( p->needToFreeIdxStr ){
101490       sqlite3_free(p->idxStr);
101491     }
101492     sqlite3DbFree(pParse->db, p);
101493   }else
101494 #endif
101495   {
101496     bestBtreeIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
101497   }
101498 }
101499
101500 /*
101501 ** Disable a term in the WHERE clause.  Except, do not disable the term
101502 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
101503 ** or USING clause of that join.
101504 **
101505 ** Consider the term t2.z='ok' in the following queries:
101506 **
101507 **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
101508 **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
101509 **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
101510 **
101511 ** The t2.z='ok' is disabled in the in (2) because it originates
101512 ** in the ON clause.  The term is disabled in (3) because it is not part
101513 ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
101514 **
101515 ** IMPLEMENTATION-OF: R-24597-58655 No tests are done for terms that are
101516 ** completely satisfied by indices.
101517 **
101518 ** Disabling a term causes that term to not be tested in the inner loop
101519 ** of the join.  Disabling is an optimization.  When terms are satisfied
101520 ** by indices, we disable them to prevent redundant tests in the inner
101521 ** loop.  We would get the correct results if nothing were ever disabled,
101522 ** but joins might run a little slower.  The trick is to disable as much
101523 ** as we can without disabling too much.  If we disabled in (1), we'd get
101524 ** the wrong answer.  See ticket #813.
101525 */
101526 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
101527   if( pTerm
101528       && (pTerm->wtFlags & TERM_CODED)==0
101529       && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
101530   ){
101531     pTerm->wtFlags |= TERM_CODED;
101532     if( pTerm->iParent>=0 ){
101533       WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
101534       if( (--pOther->nChild)==0 ){
101535         disableTerm(pLevel, pOther);
101536       }
101537     }
101538   }
101539 }
101540
101541 /*
101542 ** Code an OP_Affinity opcode to apply the column affinity string zAff
101543 ** to the n registers starting at base. 
101544 **
101545 ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
101546 ** beginning and end of zAff are ignored.  If all entries in zAff are
101547 ** SQLITE_AFF_NONE, then no code gets generated.
101548 **
101549 ** This routine makes its own copy of zAff so that the caller is free
101550 ** to modify zAff after this routine returns.
101551 */
101552 static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
101553   Vdbe *v = pParse->pVdbe;
101554   if( zAff==0 ){
101555     assert( pParse->db->mallocFailed );
101556     return;
101557   }
101558   assert( v!=0 );
101559
101560   /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
101561   ** and end of the affinity string.
101562   */
101563   while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
101564     n--;
101565     base++;
101566     zAff++;
101567   }
101568   while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
101569     n--;
101570   }
101571
101572   /* Code the OP_Affinity opcode if there is anything left to do. */
101573   if( n>0 ){
101574     sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
101575     sqlite3VdbeChangeP4(v, -1, zAff, n);
101576     sqlite3ExprCacheAffinityChange(pParse, base, n);
101577   }
101578 }
101579
101580
101581 /*
101582 ** Generate code for a single equality term of the WHERE clause.  An equality
101583 ** term can be either X=expr or X IN (...).   pTerm is the term to be 
101584 ** coded.
101585 **
101586 ** The current value for the constraint is left in register iReg.
101587 **
101588 ** For a constraint of the form X=expr, the expression is evaluated and its
101589 ** result is left on the stack.  For constraints of the form X IN (...)
101590 ** this routine sets up a loop that will iterate over all values of X.
101591 */
101592 static int codeEqualityTerm(
101593   Parse *pParse,      /* The parsing context */
101594   WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
101595   WhereLevel *pLevel, /* When level of the FROM clause we are working on */
101596   int iTarget         /* Attempt to leave results in this register */
101597 ){
101598   Expr *pX = pTerm->pExpr;
101599   Vdbe *v = pParse->pVdbe;
101600   int iReg;                  /* Register holding results */
101601
101602   assert( iTarget>0 );
101603   if( pX->op==TK_EQ ){
101604     iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
101605   }else if( pX->op==TK_ISNULL ){
101606     iReg = iTarget;
101607     sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
101608 #ifndef SQLITE_OMIT_SUBQUERY
101609   }else{
101610     int eType;
101611     int iTab;
101612     struct InLoop *pIn;
101613
101614     assert( pX->op==TK_IN );
101615     iReg = iTarget;
101616     eType = sqlite3FindInIndex(pParse, pX, 0);
101617     iTab = pX->iTable;
101618     sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
101619     assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
101620     if( pLevel->u.in.nIn==0 ){
101621       pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
101622     }
101623     pLevel->u.in.nIn++;
101624     pLevel->u.in.aInLoop =
101625        sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
101626                               sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
101627     pIn = pLevel->u.in.aInLoop;
101628     if( pIn ){
101629       pIn += pLevel->u.in.nIn - 1;
101630       pIn->iCur = iTab;
101631       if( eType==IN_INDEX_ROWID ){
101632         pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
101633       }else{
101634         pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
101635       }
101636       sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
101637     }else{
101638       pLevel->u.in.nIn = 0;
101639     }
101640 #endif
101641   }
101642   disableTerm(pLevel, pTerm);
101643   return iReg;
101644 }
101645
101646 /*
101647 ** Generate code that will evaluate all == and IN constraints for an
101648 ** index.
101649 **
101650 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
101651 ** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
101652 ** The index has as many as three equality constraints, but in this
101653 ** example, the third "c" value is an inequality.  So only two 
101654 ** constraints are coded.  This routine will generate code to evaluate
101655 ** a==5 and b IN (1,2,3).  The current values for a and b will be stored
101656 ** in consecutive registers and the index of the first register is returned.
101657 **
101658 ** In the example above nEq==2.  But this subroutine works for any value
101659 ** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
101660 ** The only thing it does is allocate the pLevel->iMem memory cell and
101661 ** compute the affinity string.
101662 **
101663 ** This routine always allocates at least one memory cell and returns
101664 ** the index of that memory cell. The code that
101665 ** calls this routine will use that memory cell to store the termination
101666 ** key value of the loop.  If one or more IN operators appear, then
101667 ** this routine allocates an additional nEq memory cells for internal
101668 ** use.
101669 **
101670 ** Before returning, *pzAff is set to point to a buffer containing a
101671 ** copy of the column affinity string of the index allocated using
101672 ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
101673 ** with equality constraints that use NONE affinity are set to
101674 ** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
101675 **
101676 **   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
101677 **   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
101678 **
101679 ** In the example above, the index on t1(a) has TEXT affinity. But since
101680 ** the right hand side of the equality constraint (t2.b) has NONE affinity,
101681 ** no conversion should be attempted before using a t2.b value as part of
101682 ** a key to search the index. Hence the first byte in the returned affinity
101683 ** string in this example would be set to SQLITE_AFF_NONE.
101684 */
101685 static int codeAllEqualityTerms(
101686   Parse *pParse,        /* Parsing context */
101687   WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
101688   WhereClause *pWC,     /* The WHERE clause */
101689   Bitmask notReady,     /* Which parts of FROM have not yet been coded */
101690   int nExtraReg,        /* Number of extra registers to allocate */
101691   char **pzAff          /* OUT: Set to point to affinity string */
101692 ){
101693   int nEq = pLevel->plan.nEq;   /* The number of == or IN constraints to code */
101694   Vdbe *v = pParse->pVdbe;      /* The vm under construction */
101695   Index *pIdx;                  /* The index being used for this loop */
101696   int iCur = pLevel->iTabCur;   /* The cursor of the table */
101697   WhereTerm *pTerm;             /* A single constraint term */
101698   int j;                        /* Loop counter */
101699   int regBase;                  /* Base register */
101700   int nReg;                     /* Number of registers to allocate */
101701   char *zAff;                   /* Affinity string to return */
101702
101703   /* This module is only called on query plans that use an index. */
101704   assert( pLevel->plan.wsFlags & WHERE_INDEXED );
101705   pIdx = pLevel->plan.u.pIdx;
101706
101707   /* Figure out how many memory cells we will need then allocate them.
101708   */
101709   regBase = pParse->nMem + 1;
101710   nReg = pLevel->plan.nEq + nExtraReg;
101711   pParse->nMem += nReg;
101712
101713   zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
101714   if( !zAff ){
101715     pParse->db->mallocFailed = 1;
101716   }
101717
101718   /* Evaluate the equality constraints
101719   */
101720   assert( pIdx->nColumn>=nEq );
101721   for(j=0; j<nEq; j++){
101722     int r1;
101723     int k = pIdx->aiColumn[j];
101724     pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
101725     if( NEVER(pTerm==0) ) break;
101726     /* The following true for indices with redundant columns. 
101727     ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
101728     testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
101729     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
101730     r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
101731     if( r1!=regBase+j ){
101732       if( nReg==1 ){
101733         sqlite3ReleaseTempReg(pParse, regBase);
101734         regBase = r1;
101735       }else{
101736         sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
101737       }
101738     }
101739     testcase( pTerm->eOperator & WO_ISNULL );
101740     testcase( pTerm->eOperator & WO_IN );
101741     if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
101742       Expr *pRight = pTerm->pExpr->pRight;
101743       sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
101744       if( zAff ){
101745         if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
101746           zAff[j] = SQLITE_AFF_NONE;
101747         }
101748         if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
101749           zAff[j] = SQLITE_AFF_NONE;
101750         }
101751       }
101752     }
101753   }
101754   *pzAff = zAff;
101755   return regBase;
101756 }
101757
101758 #ifndef SQLITE_OMIT_EXPLAIN
101759 /*
101760 ** This routine is a helper for explainIndexRange() below
101761 **
101762 ** pStr holds the text of an expression that we are building up one term
101763 ** at a time.  This routine adds a new term to the end of the expression.
101764 ** Terms are separated by AND so add the "AND" text for second and subsequent
101765 ** terms only.
101766 */
101767 static void explainAppendTerm(
101768   StrAccum *pStr,             /* The text expression being built */
101769   int iTerm,                  /* Index of this term.  First is zero */
101770   const char *zColumn,        /* Name of the column */
101771   const char *zOp             /* Name of the operator */
101772 ){
101773   if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
101774   sqlite3StrAccumAppend(pStr, zColumn, -1);
101775   sqlite3StrAccumAppend(pStr, zOp, 1);
101776   sqlite3StrAccumAppend(pStr, "?", 1);
101777 }
101778
101779 /*
101780 ** Argument pLevel describes a strategy for scanning table pTab. This 
101781 ** function returns a pointer to a string buffer containing a description
101782 ** of the subset of table rows scanned by the strategy in the form of an
101783 ** SQL expression. Or, if all rows are scanned, NULL is returned.
101784 **
101785 ** For example, if the query:
101786 **
101787 **   SELECT * FROM t1 WHERE a=1 AND b>2;
101788 **
101789 ** is run and there is an index on (a, b), then this function returns a
101790 ** string similar to:
101791 **
101792 **   "a=? AND b>?"
101793 **
101794 ** The returned pointer points to memory obtained from sqlite3DbMalloc().
101795 ** It is the responsibility of the caller to free the buffer when it is
101796 ** no longer required.
101797 */
101798 static char *explainIndexRange(sqlite3 *db, WhereLevel *pLevel, Table *pTab){
101799   WherePlan *pPlan = &pLevel->plan;
101800   Index *pIndex = pPlan->u.pIdx;
101801   int nEq = pPlan->nEq;
101802   int i, j;
101803   Column *aCol = pTab->aCol;
101804   int *aiColumn = pIndex->aiColumn;
101805   StrAccum txt;
101806
101807   if( nEq==0 && (pPlan->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
101808     return 0;
101809   }
101810   sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
101811   txt.db = db;
101812   sqlite3StrAccumAppend(&txt, " (", 2);
101813   for(i=0; i<nEq; i++){
101814     explainAppendTerm(&txt, i, aCol[aiColumn[i]].zName, "=");
101815   }
101816
101817   j = i;
101818   if( pPlan->wsFlags&WHERE_BTM_LIMIT ){
101819     explainAppendTerm(&txt, i++, aCol[aiColumn[j]].zName, ">");
101820   }
101821   if( pPlan->wsFlags&WHERE_TOP_LIMIT ){
101822     explainAppendTerm(&txt, i, aCol[aiColumn[j]].zName, "<");
101823   }
101824   sqlite3StrAccumAppend(&txt, ")", 1);
101825   return sqlite3StrAccumFinish(&txt);
101826 }
101827
101828 /*
101829 ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
101830 ** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
101831 ** record is added to the output to describe the table scan strategy in 
101832 ** pLevel.
101833 */
101834 static void explainOneScan(
101835   Parse *pParse,                  /* Parse context */
101836   SrcList *pTabList,              /* Table list this loop refers to */
101837   WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
101838   int iLevel,                     /* Value for "level" column of output */
101839   int iFrom,                      /* Value for "from" column of output */
101840   u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
101841 ){
101842   if( pParse->explain==2 ){
101843     u32 flags = pLevel->plan.wsFlags;
101844     struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
101845     Vdbe *v = pParse->pVdbe;      /* VM being constructed */
101846     sqlite3 *db = pParse->db;     /* Database handle */
101847     char *zMsg;                   /* Text to add to EQP output */
101848     sqlite3_int64 nRow;           /* Expected number of rows visited by scan */
101849     int iId = pParse->iSelectId;  /* Select id (left-most output column) */
101850     int isSearch;                 /* True for a SEARCH. False for SCAN. */
101851
101852     if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
101853
101854     isSearch = (pLevel->plan.nEq>0)
101855              || (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
101856              || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
101857
101858     zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
101859     if( pItem->pSelect ){
101860       zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
101861     }else{
101862       zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName);
101863     }
101864
101865     if( pItem->zAlias ){
101866       zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
101867     }
101868     if( (flags & WHERE_INDEXED)!=0 ){
101869       char *zWhere = explainIndexRange(db, pLevel, pItem->pTab);
101870       zMsg = sqlite3MAppendf(db, zMsg, "%s USING %s%sINDEX%s%s%s", zMsg, 
101871           ((flags & WHERE_TEMP_INDEX)?"AUTOMATIC ":""),
101872           ((flags & WHERE_IDX_ONLY)?"COVERING ":""),
101873           ((flags & WHERE_TEMP_INDEX)?"":" "),
101874           ((flags & WHERE_TEMP_INDEX)?"": pLevel->plan.u.pIdx->zName),
101875           zWhere
101876       );
101877       sqlite3DbFree(db, zWhere);
101878     }else if( flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
101879       zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
101880
101881       if( flags&WHERE_ROWID_EQ ){
101882         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
101883       }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
101884         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
101885       }else if( flags&WHERE_BTM_LIMIT ){
101886         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
101887       }else if( flags&WHERE_TOP_LIMIT ){
101888         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
101889       }
101890     }
101891 #ifndef SQLITE_OMIT_VIRTUALTABLE
101892     else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
101893       sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
101894       zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
101895                   pVtabIdx->idxNum, pVtabIdx->idxStr);
101896     }
101897 #endif
101898     if( wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX) ){
101899       testcase( wctrlFlags & WHERE_ORDERBY_MIN );
101900       nRow = 1;
101901     }else{
101902       nRow = (sqlite3_int64)pLevel->plan.nRow;
101903     }
101904     zMsg = sqlite3MAppendf(db, zMsg, "%s (~%lld rows)", zMsg, nRow);
101905     sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
101906   }
101907 }
101908 #else
101909 # define explainOneScan(u,v,w,x,y,z)
101910 #endif /* SQLITE_OMIT_EXPLAIN */
101911
101912
101913 /*
101914 ** Generate code for the start of the iLevel-th loop in the WHERE clause
101915 ** implementation described by pWInfo.
101916 */
101917 static Bitmask codeOneLoopStart(
101918   WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
101919   int iLevel,          /* Which level of pWInfo->a[] should be coded */
101920   u16 wctrlFlags,      /* One of the WHERE_* flags defined in sqliteInt.h */
101921   Bitmask notReady     /* Which tables are currently available */
101922 ){
101923   int j, k;            /* Loop counters */
101924   int iCur;            /* The VDBE cursor for the table */
101925   int addrNxt;         /* Where to jump to continue with the next IN case */
101926   int omitTable;       /* True if we use the index only */
101927   int bRev;            /* True if we need to scan in reverse order */
101928   WhereLevel *pLevel;  /* The where level to be coded */
101929   WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
101930   WhereTerm *pTerm;               /* A WHERE clause term */
101931   Parse *pParse;                  /* Parsing context */
101932   Vdbe *v;                        /* The prepared stmt under constructions */
101933   struct SrcList_item *pTabItem;  /* FROM clause term being coded */
101934   int addrBrk;                    /* Jump here to break out of the loop */
101935   int addrCont;                   /* Jump here to continue with next cycle */
101936   int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
101937   int iReleaseReg = 0;      /* Temp register to free before returning */
101938
101939   pParse = pWInfo->pParse;
101940   v = pParse->pVdbe;
101941   pWC = pWInfo->pWC;
101942   pLevel = &pWInfo->a[iLevel];
101943   pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
101944   iCur = pTabItem->iCursor;
101945   bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
101946   omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0 
101947            && (wctrlFlags & WHERE_FORCE_TABLE)==0;
101948
101949   /* Create labels for the "break" and "continue" instructions
101950   ** for the current loop.  Jump to addrBrk to break out of a loop.
101951   ** Jump to cont to go immediately to the next iteration of the
101952   ** loop.
101953   **
101954   ** When there is an IN operator, we also have a "addrNxt" label that
101955   ** means to continue with the next IN value combination.  When
101956   ** there are no IN operators in the constraints, the "addrNxt" label
101957   ** is the same as "addrBrk".
101958   */
101959   addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
101960   addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
101961
101962   /* If this is the right table of a LEFT OUTER JOIN, allocate and
101963   ** initialize a memory cell that records if this table matches any
101964   ** row of the left table of the join.
101965   */
101966   if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
101967     pLevel->iLeftJoin = ++pParse->nMem;
101968     sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
101969     VdbeComment((v, "init LEFT JOIN no-match flag"));
101970   }
101971
101972 #ifndef SQLITE_OMIT_VIRTUALTABLE
101973   if(  (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
101974     /* Case 0:  The table is a virtual-table.  Use the VFilter and VNext
101975     **          to access the data.
101976     */
101977     int iReg;   /* P3 Value for OP_VFilter */
101978     sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
101979     int nConstraint = pVtabIdx->nConstraint;
101980     struct sqlite3_index_constraint_usage *aUsage =
101981                                                 pVtabIdx->aConstraintUsage;
101982     const struct sqlite3_index_constraint *aConstraint =
101983                                                 pVtabIdx->aConstraint;
101984
101985     sqlite3ExprCachePush(pParse);
101986     iReg = sqlite3GetTempRange(pParse, nConstraint+2);
101987     for(j=1; j<=nConstraint; j++){
101988       for(k=0; k<nConstraint; k++){
101989         if( aUsage[k].argvIndex==j ){
101990           int iTerm = aConstraint[k].iTermOffset;
101991           sqlite3ExprCode(pParse, pWC->a[iTerm].pExpr->pRight, iReg+j+1);
101992           break;
101993         }
101994       }
101995       if( k==nConstraint ) break;
101996     }
101997     sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
101998     sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
101999     sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrBrk, iReg, pVtabIdx->idxStr,
102000                       pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
102001     pVtabIdx->needToFreeIdxStr = 0;
102002     for(j=0; j<nConstraint; j++){
102003       if( aUsage[j].omit ){
102004         int iTerm = aConstraint[j].iTermOffset;
102005         disableTerm(pLevel, &pWC->a[iTerm]);
102006       }
102007     }
102008     pLevel->op = OP_VNext;
102009     pLevel->p1 = iCur;
102010     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
102011     sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
102012     sqlite3ExprCachePop(pParse, 1);
102013   }else
102014 #endif /* SQLITE_OMIT_VIRTUALTABLE */
102015
102016   if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
102017     /* Case 1:  We can directly reference a single row using an
102018     **          equality comparison against the ROWID field.  Or
102019     **          we reference multiple rows using a "rowid IN (...)"
102020     **          construct.
102021     */
102022     iReleaseReg = sqlite3GetTempReg(pParse);
102023     pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
102024     assert( pTerm!=0 );
102025     assert( pTerm->pExpr!=0 );
102026     assert( pTerm->leftCursor==iCur );
102027     assert( omitTable==0 );
102028     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
102029     iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, iReleaseReg);
102030     addrNxt = pLevel->addrNxt;
102031     sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
102032     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
102033     sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
102034     VdbeComment((v, "pk"));
102035     pLevel->op = OP_Noop;
102036   }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
102037     /* Case 2:  We have an inequality comparison against the ROWID field.
102038     */
102039     int testOp = OP_Noop;
102040     int start;
102041     int memEndValue = 0;
102042     WhereTerm *pStart, *pEnd;
102043
102044     assert( omitTable==0 );
102045     pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);
102046     pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);
102047     if( bRev ){
102048       pTerm = pStart;
102049       pStart = pEnd;
102050       pEnd = pTerm;
102051     }
102052     if( pStart ){
102053       Expr *pX;             /* The expression that defines the start bound */
102054       int r1, rTemp;        /* Registers for holding the start boundary */
102055
102056       /* The following constant maps TK_xx codes into corresponding 
102057       ** seek opcodes.  It depends on a particular ordering of TK_xx
102058       */
102059       const u8 aMoveOp[] = {
102060            /* TK_GT */  OP_SeekGt,
102061            /* TK_LE */  OP_SeekLe,
102062            /* TK_LT */  OP_SeekLt,
102063            /* TK_GE */  OP_SeekGe
102064       };
102065       assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
102066       assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
102067       assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
102068
102069       testcase( pStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
102070       pX = pStart->pExpr;
102071       assert( pX!=0 );
102072       assert( pStart->leftCursor==iCur );
102073       r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
102074       sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
102075       VdbeComment((v, "pk"));
102076       sqlite3ExprCacheAffinityChange(pParse, r1, 1);
102077       sqlite3ReleaseTempReg(pParse, rTemp);
102078       disableTerm(pLevel, pStart);
102079     }else{
102080       sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
102081     }
102082     if( pEnd ){
102083       Expr *pX;
102084       pX = pEnd->pExpr;
102085       assert( pX!=0 );
102086       assert( pEnd->leftCursor==iCur );
102087       testcase( pEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
102088       memEndValue = ++pParse->nMem;
102089       sqlite3ExprCode(pParse, pX->pRight, memEndValue);
102090       if( pX->op==TK_LT || pX->op==TK_GT ){
102091         testOp = bRev ? OP_Le : OP_Ge;
102092       }else{
102093         testOp = bRev ? OP_Lt : OP_Gt;
102094       }
102095       disableTerm(pLevel, pEnd);
102096     }
102097     start = sqlite3VdbeCurrentAddr(v);
102098     pLevel->op = bRev ? OP_Prev : OP_Next;
102099     pLevel->p1 = iCur;
102100     pLevel->p2 = start;
102101     if( pStart==0 && pEnd==0 ){
102102       pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
102103     }else{
102104       assert( pLevel->p5==0 );
102105     }
102106     if( testOp!=OP_Noop ){
102107       iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
102108       sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
102109       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
102110       sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
102111       sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
102112     }
102113   }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
102114     /* Case 3: A scan using an index.
102115     **
102116     **         The WHERE clause may contain zero or more equality 
102117     **         terms ("==" or "IN" operators) that refer to the N
102118     **         left-most columns of the index. It may also contain
102119     **         inequality constraints (>, <, >= or <=) on the indexed
102120     **         column that immediately follows the N equalities. Only 
102121     **         the right-most column can be an inequality - the rest must
102122     **         use the "==" and "IN" operators. For example, if the 
102123     **         index is on (x,y,z), then the following clauses are all 
102124     **         optimized:
102125     **
102126     **            x=5
102127     **            x=5 AND y=10
102128     **            x=5 AND y<10
102129     **            x=5 AND y>5 AND y<10
102130     **            x=5 AND y=5 AND z<=10
102131     **
102132     **         The z<10 term of the following cannot be used, only
102133     **         the x=5 term:
102134     **
102135     **            x=5 AND z<10
102136     **
102137     **         N may be zero if there are inequality constraints.
102138     **         If there are no inequality constraints, then N is at
102139     **         least one.
102140     **
102141     **         This case is also used when there are no WHERE clause
102142     **         constraints but an index is selected anyway, in order
102143     **         to force the output order to conform to an ORDER BY.
102144     */  
102145     static const u8 aStartOp[] = {
102146       0,
102147       0,
102148       OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
102149       OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
102150       OP_SeekGt,           /* 4: (start_constraints  && !startEq && !bRev) */
102151       OP_SeekLt,           /* 5: (start_constraints  && !startEq &&  bRev) */
102152       OP_SeekGe,           /* 6: (start_constraints  &&  startEq && !bRev) */
102153       OP_SeekLe            /* 7: (start_constraints  &&  startEq &&  bRev) */
102154     };
102155     static const u8 aEndOp[] = {
102156       OP_Noop,             /* 0: (!end_constraints) */
102157       OP_IdxGE,            /* 1: (end_constraints && !bRev) */
102158       OP_IdxLT             /* 2: (end_constraints && bRev) */
102159     };
102160     int nEq = pLevel->plan.nEq;  /* Number of == or IN terms */
102161     int isMinQuery = 0;          /* If this is an optimized SELECT min(x).. */
102162     int regBase;                 /* Base register holding constraint values */
102163     int r1;                      /* Temp register */
102164     WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
102165     WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
102166     int startEq;                 /* True if range start uses ==, >= or <= */
102167     int endEq;                   /* True if range end uses ==, >= or <= */
102168     int start_constraints;       /* Start of range is constrained */
102169     int nConstraint;             /* Number of constraint terms */
102170     Index *pIdx;                 /* The index we will be using */
102171     int iIdxCur;                 /* The VDBE cursor for the index */
102172     int nExtraReg = 0;           /* Number of extra registers needed */
102173     int op;                      /* Instruction opcode */
102174     char *zStartAff;             /* Affinity for start of range constraint */
102175     char *zEndAff;               /* Affinity for end of range constraint */
102176
102177     pIdx = pLevel->plan.u.pIdx;
102178     iIdxCur = pLevel->iIdxCur;
102179     k = pIdx->aiColumn[nEq];     /* Column for inequality constraints */
102180
102181     /* If this loop satisfies a sort order (pOrderBy) request that 
102182     ** was passed to this function to implement a "SELECT min(x) ..." 
102183     ** query, then the caller will only allow the loop to run for
102184     ** a single iteration. This means that the first row returned
102185     ** should not have a NULL value stored in 'x'. If column 'x' is
102186     ** the first one after the nEq equality constraints in the index,
102187     ** this requires some special handling.
102188     */
102189     if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
102190      && (pLevel->plan.wsFlags&WHERE_ORDERBY)
102191      && (pIdx->nColumn>nEq)
102192     ){
102193       /* assert( pOrderBy->nExpr==1 ); */
102194       /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
102195       isMinQuery = 1;
102196       nExtraReg = 1;
102197     }
102198
102199     /* Find any inequality constraint terms for the start and end 
102200     ** of the range. 
102201     */
102202     if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
102203       pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
102204       nExtraReg = 1;
102205     }
102206     if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
102207       pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
102208       nExtraReg = 1;
102209     }
102210
102211     /* Generate code to evaluate all constraint terms using == or IN
102212     ** and store the values of those terms in an array of registers
102213     ** starting at regBase.
102214     */
102215     regBase = codeAllEqualityTerms(
102216         pParse, pLevel, pWC, notReady, nExtraReg, &zStartAff
102217     );
102218     zEndAff = sqlite3DbStrDup(pParse->db, zStartAff);
102219     addrNxt = pLevel->addrNxt;
102220
102221     /* If we are doing a reverse order scan on an ascending index, or
102222     ** a forward order scan on a descending index, interchange the 
102223     ** start and end terms (pRangeStart and pRangeEnd).
102224     */
102225     if( nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC) ){
102226       SWAP(WhereTerm *, pRangeEnd, pRangeStart);
102227     }
102228
102229     testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
102230     testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
102231     testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
102232     testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
102233     startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
102234     endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
102235     start_constraints = pRangeStart || nEq>0;
102236
102237     /* Seek the index cursor to the start of the range. */
102238     nConstraint = nEq;
102239     if( pRangeStart ){
102240       Expr *pRight = pRangeStart->pExpr->pRight;
102241       sqlite3ExprCode(pParse, pRight, regBase+nEq);
102242       if( (pRangeStart->wtFlags & TERM_VNULL)==0 ){
102243         sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
102244       }
102245       if( zStartAff ){
102246         if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
102247           /* Since the comparison is to be performed with no conversions
102248           ** applied to the operands, set the affinity to apply to pRight to 
102249           ** SQLITE_AFF_NONE.  */
102250           zStartAff[nEq] = SQLITE_AFF_NONE;
102251         }
102252         if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
102253           zStartAff[nEq] = SQLITE_AFF_NONE;
102254         }
102255       }  
102256       nConstraint++;
102257       testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
102258     }else if( isMinQuery ){
102259       sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
102260       nConstraint++;
102261       startEq = 0;
102262       start_constraints = 1;
102263     }
102264     codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
102265     op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
102266     assert( op!=0 );
102267     testcase( op==OP_Rewind );
102268     testcase( op==OP_Last );
102269     testcase( op==OP_SeekGt );
102270     testcase( op==OP_SeekGe );
102271     testcase( op==OP_SeekLe );
102272     testcase( op==OP_SeekLt );
102273     sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
102274
102275     /* Load the value for the inequality constraint at the end of the
102276     ** range (if any).
102277     */
102278     nConstraint = nEq;
102279     if( pRangeEnd ){
102280       Expr *pRight = pRangeEnd->pExpr->pRight;
102281       sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
102282       sqlite3ExprCode(pParse, pRight, regBase+nEq);
102283       if( (pRangeEnd->wtFlags & TERM_VNULL)==0 ){
102284         sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
102285       }
102286       if( zEndAff ){
102287         if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){
102288           /* Since the comparison is to be performed with no conversions
102289           ** applied to the operands, set the affinity to apply to pRight to 
102290           ** SQLITE_AFF_NONE.  */
102291           zEndAff[nEq] = SQLITE_AFF_NONE;
102292         }
102293         if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
102294           zEndAff[nEq] = SQLITE_AFF_NONE;
102295         }
102296       }  
102297       codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
102298       nConstraint++;
102299       testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
102300     }
102301     sqlite3DbFree(pParse->db, zStartAff);
102302     sqlite3DbFree(pParse->db, zEndAff);
102303
102304     /* Top of the loop body */
102305     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
102306
102307     /* Check if the index cursor is past the end of the range. */
102308     op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
102309     testcase( op==OP_Noop );
102310     testcase( op==OP_IdxGE );
102311     testcase( op==OP_IdxLT );
102312     if( op!=OP_Noop ){
102313       sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
102314       sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
102315     }
102316
102317     /* If there are inequality constraints, check that the value
102318     ** of the table column that the inequality contrains is not NULL.
102319     ** If it is, jump to the next iteration of the loop.
102320     */
102321     r1 = sqlite3GetTempReg(pParse);
102322     testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
102323     testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
102324     if( (pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){
102325       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
102326       sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
102327     }
102328     sqlite3ReleaseTempReg(pParse, r1);
102329
102330     /* Seek the table cursor, if required */
102331     disableTerm(pLevel, pRangeStart);
102332     disableTerm(pLevel, pRangeEnd);
102333     if( !omitTable ){
102334       iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
102335       sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
102336       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
102337       sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */
102338     }
102339
102340     /* Record the instruction used to terminate the loop. Disable 
102341     ** WHERE clause terms made redundant by the index range scan.
102342     */
102343     if( pLevel->plan.wsFlags & WHERE_UNIQUE ){
102344       pLevel->op = OP_Noop;
102345     }else if( bRev ){
102346       pLevel->op = OP_Prev;
102347     }else{
102348       pLevel->op = OP_Next;
102349     }
102350     pLevel->p1 = iIdxCur;
102351   }else
102352
102353 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
102354   if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
102355     /* Case 4:  Two or more separately indexed terms connected by OR
102356     **
102357     ** Example:
102358     **
102359     **   CREATE TABLE t1(a,b,c,d);
102360     **   CREATE INDEX i1 ON t1(a);
102361     **   CREATE INDEX i2 ON t1(b);
102362     **   CREATE INDEX i3 ON t1(c);
102363     **
102364     **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
102365     **
102366     ** In the example, there are three indexed terms connected by OR.
102367     ** The top of the loop looks like this:
102368     **
102369     **          Null       1                # Zero the rowset in reg 1
102370     **
102371     ** Then, for each indexed term, the following. The arguments to
102372     ** RowSetTest are such that the rowid of the current row is inserted
102373     ** into the RowSet. If it is already present, control skips the
102374     ** Gosub opcode and jumps straight to the code generated by WhereEnd().
102375     **
102376     **        sqlite3WhereBegin(<term>)
102377     **          RowSetTest                  # Insert rowid into rowset
102378     **          Gosub      2 A
102379     **        sqlite3WhereEnd()
102380     **
102381     ** Following the above, code to terminate the loop. Label A, the target
102382     ** of the Gosub above, jumps to the instruction right after the Goto.
102383     **
102384     **          Null       1                # Zero the rowset in reg 1
102385     **          Goto       B                # The loop is finished.
102386     **
102387     **       A: <loop body>                 # Return data, whatever.
102388     **
102389     **          Return     2                # Jump back to the Gosub
102390     **
102391     **       B: <after the loop>
102392     **
102393     */
102394     WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
102395     SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
102396
102397     int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
102398     int regRowset = 0;                        /* Register for RowSet object */
102399     int regRowid = 0;                         /* Register holding rowid */
102400     int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
102401     int iRetInit;                             /* Address of regReturn init */
102402     int untestedTerms = 0;             /* Some terms not completely tested */
102403     int ii;
102404    
102405     pTerm = pLevel->plan.u.pTerm;
102406     assert( pTerm!=0 );
102407     assert( pTerm->eOperator==WO_OR );
102408     assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
102409     pOrWc = &pTerm->u.pOrInfo->wc;
102410     pLevel->op = OP_Return;
102411     pLevel->p1 = regReturn;
102412
102413     /* Set up a new SrcList ni pOrTab containing the table being scanned
102414     ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
102415     ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
102416     */
102417     if( pWInfo->nLevel>1 ){
102418       int nNotReady;                 /* The number of notReady tables */
102419       struct SrcList_item *origSrc;     /* Original list of tables */
102420       nNotReady = pWInfo->nLevel - iLevel - 1;
102421       pOrTab = sqlite3StackAllocRaw(pParse->db,
102422                             sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
102423       if( pOrTab==0 ) return notReady;
102424       pOrTab->nAlloc = (i16)(nNotReady + 1);
102425       pOrTab->nSrc = pOrTab->nAlloc;
102426       memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
102427       origSrc = pWInfo->pTabList->a;
102428       for(k=1; k<=nNotReady; k++){
102429         memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
102430       }
102431     }else{
102432       pOrTab = pWInfo->pTabList;
102433     }
102434
102435     /* Initialize the rowset register to contain NULL. An SQL NULL is 
102436     ** equivalent to an empty rowset.
102437     **
102438     ** Also initialize regReturn to contain the address of the instruction 
102439     ** immediately following the OP_Return at the bottom of the loop. This
102440     ** is required in a few obscure LEFT JOIN cases where control jumps
102441     ** over the top of the loop into the body of it. In this case the 
102442     ** correct response for the end-of-loop code (the OP_Return) is to 
102443     ** fall through to the next instruction, just as an OP_Next does if
102444     ** called on an uninitialized cursor.
102445     */
102446     if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
102447       regRowset = ++pParse->nMem;
102448       regRowid = ++pParse->nMem;
102449       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
102450     }
102451     iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
102452
102453     for(ii=0; ii<pOrWc->nTerm; ii++){
102454       WhereTerm *pOrTerm = &pOrWc->a[ii];
102455       if( pOrTerm->leftCursor==iCur || pOrTerm->eOperator==WO_AND ){
102456         WhereInfo *pSubWInfo;          /* Info for single OR-term scan */
102457         /* Loop through table entries that match term pOrTerm. */
102458         pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrTerm->pExpr, 0,
102459                         WHERE_OMIT_OPEN | WHERE_OMIT_CLOSE |
102460                         WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY);
102461         if( pSubWInfo ){
102462           explainOneScan(
102463               pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
102464           );
102465           if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
102466             int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
102467             int r;
102468             r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur, 
102469                                          regRowid);
102470             sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
102471                                  sqlite3VdbeCurrentAddr(v)+2, r, iSet);
102472           }
102473           sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
102474
102475           /* The pSubWInfo->untestedTerms flag means that this OR term
102476           ** contained one or more AND term from a notReady table.  The
102477           ** terms from the notReady table could not be tested and will
102478           ** need to be tested later.
102479           */
102480           if( pSubWInfo->untestedTerms ) untestedTerms = 1;
102481
102482           /* Finish the loop through table entries that match term pOrTerm. */
102483           sqlite3WhereEnd(pSubWInfo);
102484         }
102485       }
102486     }
102487     sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
102488     sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
102489     sqlite3VdbeResolveLabel(v, iLoopBody);
102490
102491     if( pWInfo->nLevel>1 ) sqlite3StackFree(pParse->db, pOrTab);
102492     if( !untestedTerms ) disableTerm(pLevel, pTerm);
102493   }else
102494 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
102495
102496   {
102497     /* Case 5:  There is no usable index.  We must do a complete
102498     **          scan of the entire table.
102499     */
102500     static const u8 aStep[] = { OP_Next, OP_Prev };
102501     static const u8 aStart[] = { OP_Rewind, OP_Last };
102502     assert( bRev==0 || bRev==1 );
102503     assert( omitTable==0 );
102504     pLevel->op = aStep[bRev];
102505     pLevel->p1 = iCur;
102506     pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
102507     pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
102508   }
102509   notReady &= ~getMask(pWC->pMaskSet, iCur);
102510
102511   /* Insert code to test every subexpression that can be completely
102512   ** computed using the current set of tables.
102513   **
102514   ** IMPLEMENTATION-OF: R-49525-50935 Terms that cannot be satisfied through
102515   ** the use of indices become tests that are evaluated against each row of
102516   ** the relevant input tables.
102517   */
102518   for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
102519     Expr *pE;
102520     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
102521     testcase( pTerm->wtFlags & TERM_CODED );
102522     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
102523     if( (pTerm->prereqAll & notReady)!=0 ){
102524       testcase( pWInfo->untestedTerms==0
102525                && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
102526       pWInfo->untestedTerms = 1;
102527       continue;
102528     }
102529     pE = pTerm->pExpr;
102530     assert( pE!=0 );
102531     if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
102532       continue;
102533     }
102534     sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
102535     pTerm->wtFlags |= TERM_CODED;
102536   }
102537
102538   /* For a LEFT OUTER JOIN, generate code that will record the fact that
102539   ** at least one row of the right table has matched the left table.  
102540   */
102541   if( pLevel->iLeftJoin ){
102542     pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
102543     sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
102544     VdbeComment((v, "record LEFT JOIN hit"));
102545     sqlite3ExprCacheClear(pParse);
102546     for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
102547       testcase( pTerm->wtFlags & TERM_VIRTUAL );  /* IMP: R-30575-11662 */
102548       testcase( pTerm->wtFlags & TERM_CODED );
102549       if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
102550       if( (pTerm->prereqAll & notReady)!=0 ){
102551         assert( pWInfo->untestedTerms );
102552         continue;
102553       }
102554       assert( pTerm->pExpr );
102555       sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
102556       pTerm->wtFlags |= TERM_CODED;
102557     }
102558   }
102559   sqlite3ReleaseTempReg(pParse, iReleaseReg);
102560
102561   return notReady;
102562 }
102563
102564 #if defined(SQLITE_TEST)
102565 /*
102566 ** The following variable holds a text description of query plan generated
102567 ** by the most recent call to sqlite3WhereBegin().  Each call to WhereBegin
102568 ** overwrites the previous.  This information is used for testing and
102569 ** analysis only.
102570 */
102571 SQLITE_API char sqlite3_query_plan[BMS*2*40];  /* Text of the join */
102572 static int nQPlan = 0;              /* Next free slow in _query_plan[] */
102573
102574 #endif /* SQLITE_TEST */
102575
102576
102577 /*
102578 ** Free a WhereInfo structure
102579 */
102580 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
102581   if( ALWAYS(pWInfo) ){
102582     int i;
102583     for(i=0; i<pWInfo->nLevel; i++){
102584       sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
102585       if( pInfo ){
102586         /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
102587         if( pInfo->needToFreeIdxStr ){
102588           sqlite3_free(pInfo->idxStr);
102589         }
102590         sqlite3DbFree(db, pInfo);
102591       }
102592       if( pWInfo->a[i].plan.wsFlags & WHERE_TEMP_INDEX ){
102593         Index *pIdx = pWInfo->a[i].plan.u.pIdx;
102594         if( pIdx ){
102595           sqlite3DbFree(db, pIdx->zColAff);
102596           sqlite3DbFree(db, pIdx);
102597         }
102598       }
102599     }
102600     whereClauseClear(pWInfo->pWC);
102601     sqlite3DbFree(db, pWInfo);
102602   }
102603 }
102604
102605
102606 /*
102607 ** Generate the beginning of the loop used for WHERE clause processing.
102608 ** The return value is a pointer to an opaque structure that contains
102609 ** information needed to terminate the loop.  Later, the calling routine
102610 ** should invoke sqlite3WhereEnd() with the return value of this function
102611 ** in order to complete the WHERE clause processing.
102612 **
102613 ** If an error occurs, this routine returns NULL.
102614 **
102615 ** The basic idea is to do a nested loop, one loop for each table in
102616 ** the FROM clause of a select.  (INSERT and UPDATE statements are the
102617 ** same as a SELECT with only a single table in the FROM clause.)  For
102618 ** example, if the SQL is this:
102619 **
102620 **       SELECT * FROM t1, t2, t3 WHERE ...;
102621 **
102622 ** Then the code generated is conceptually like the following:
102623 **
102624 **      foreach row1 in t1 do       \    Code generated
102625 **        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
102626 **          foreach row3 in t3 do   /
102627 **            ...
102628 **          end                     \    Code generated
102629 **        end                        |-- by sqlite3WhereEnd()
102630 **      end                         /
102631 **
102632 ** Note that the loops might not be nested in the order in which they
102633 ** appear in the FROM clause if a different order is better able to make
102634 ** use of indices.  Note also that when the IN operator appears in
102635 ** the WHERE clause, it might result in additional nested loops for
102636 ** scanning through all values on the right-hand side of the IN.
102637 **
102638 ** There are Btree cursors associated with each table.  t1 uses cursor
102639 ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
102640 ** And so forth.  This routine generates code to open those VDBE cursors
102641 ** and sqlite3WhereEnd() generates the code to close them.
102642 **
102643 ** The code that sqlite3WhereBegin() generates leaves the cursors named
102644 ** in pTabList pointing at their appropriate entries.  The [...] code
102645 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
102646 ** data from the various tables of the loop.
102647 **
102648 ** If the WHERE clause is empty, the foreach loops must each scan their
102649 ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
102650 ** the tables have indices and there are terms in the WHERE clause that
102651 ** refer to those indices, a complete table scan can be avoided and the
102652 ** code will run much faster.  Most of the work of this routine is checking
102653 ** to see if there are indices that can be used to speed up the loop.
102654 **
102655 ** Terms of the WHERE clause are also used to limit which rows actually
102656 ** make it to the "..." in the middle of the loop.  After each "foreach",
102657 ** terms of the WHERE clause that use only terms in that loop and outer
102658 ** loops are evaluated and if false a jump is made around all subsequent
102659 ** inner loops (or around the "..." if the test occurs within the inner-
102660 ** most loop)
102661 **
102662 ** OUTER JOINS
102663 **
102664 ** An outer join of tables t1 and t2 is conceptally coded as follows:
102665 **
102666 **    foreach row1 in t1 do
102667 **      flag = 0
102668 **      foreach row2 in t2 do
102669 **        start:
102670 **          ...
102671 **          flag = 1
102672 **      end
102673 **      if flag==0 then
102674 **        move the row2 cursor to a null row
102675 **        goto start
102676 **      fi
102677 **    end
102678 **
102679 ** ORDER BY CLAUSE PROCESSING
102680 **
102681 ** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
102682 ** if there is one.  If there is no ORDER BY clause or if this routine
102683 ** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
102684 **
102685 ** If an index can be used so that the natural output order of the table
102686 ** scan is correct for the ORDER BY clause, then that index is used and
102687 ** *ppOrderBy is set to NULL.  This is an optimization that prevents an
102688 ** unnecessary sort of the result set if an index appropriate for the
102689 ** ORDER BY clause already exists.
102690 **
102691 ** If the where clause loops cannot be arranged to provide the correct
102692 ** output order, then the *ppOrderBy is unchanged.
102693 */
102694 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
102695   Parse *pParse,        /* The parser context */
102696   SrcList *pTabList,    /* A list of all tables to be scanned */
102697   Expr *pWhere,         /* The WHERE clause */
102698   ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
102699   u16 wctrlFlags        /* One of the WHERE_* flags defined in sqliteInt.h */
102700 ){
102701   int i;                     /* Loop counter */
102702   int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
102703   int nTabList;              /* Number of elements in pTabList */
102704   WhereInfo *pWInfo;         /* Will become the return value of this function */
102705   Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
102706   Bitmask notReady;          /* Cursors that are not yet positioned */
102707   WhereMaskSet *pMaskSet;    /* The expression mask set */
102708   WhereClause *pWC;               /* Decomposition of the WHERE clause */
102709   struct SrcList_item *pTabItem;  /* A single entry from pTabList */
102710   WhereLevel *pLevel;             /* A single level in the pWInfo list */
102711   int iFrom;                      /* First unused FROM clause element */
102712   int andFlags;              /* AND-ed combination of all pWC->a[].wtFlags */
102713   sqlite3 *db;               /* Database connection */
102714
102715   /* The number of tables in the FROM clause is limited by the number of
102716   ** bits in a Bitmask 
102717   */
102718   testcase( pTabList->nSrc==BMS );
102719   if( pTabList->nSrc>BMS ){
102720     sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
102721     return 0;
102722   }
102723
102724   /* This function normally generates a nested loop for all tables in 
102725   ** pTabList.  But if the WHERE_ONETABLE_ONLY flag is set, then we should
102726   ** only generate code for the first table in pTabList and assume that
102727   ** any cursors associated with subsequent tables are uninitialized.
102728   */
102729   nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
102730
102731   /* Allocate and initialize the WhereInfo structure that will become the
102732   ** return value. A single allocation is used to store the WhereInfo
102733   ** struct, the contents of WhereInfo.a[], the WhereClause structure
102734   ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
102735   ** field (type Bitmask) it must be aligned on an 8-byte boundary on
102736   ** some architectures. Hence the ROUND8() below.
102737   */
102738   db = pParse->db;
102739   nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
102740   pWInfo = sqlite3DbMallocZero(db, 
102741       nByteWInfo + 
102742       sizeof(WhereClause) +
102743       sizeof(WhereMaskSet)
102744   );
102745   if( db->mallocFailed ){
102746     sqlite3DbFree(db, pWInfo);
102747     pWInfo = 0;
102748     goto whereBeginError;
102749   }
102750   pWInfo->nLevel = nTabList;
102751   pWInfo->pParse = pParse;
102752   pWInfo->pTabList = pTabList;
102753   pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
102754   pWInfo->pWC = pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
102755   pWInfo->wctrlFlags = wctrlFlags;
102756   pWInfo->savedNQueryLoop = pParse->nQueryLoop;
102757   pMaskSet = (WhereMaskSet*)&pWC[1];
102758
102759   /* Split the WHERE clause into separate subexpressions where each
102760   ** subexpression is separated by an AND operator.
102761   */
102762   initMaskSet(pMaskSet);
102763   whereClauseInit(pWC, pParse, pMaskSet);
102764   sqlite3ExprCodeConstants(pParse, pWhere);
102765   whereSplit(pWC, pWhere, TK_AND);   /* IMP: R-15842-53296 */
102766     
102767   /* Special case: a WHERE clause that is constant.  Evaluate the
102768   ** expression and either jump over all of the code or fall thru.
102769   */
102770   if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
102771     sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
102772     pWhere = 0;
102773   }
102774
102775   /* Assign a bit from the bitmask to every term in the FROM clause.
102776   **
102777   ** When assigning bitmask values to FROM clause cursors, it must be
102778   ** the case that if X is the bitmask for the N-th FROM clause term then
102779   ** the bitmask for all FROM clause terms to the left of the N-th term
102780   ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
102781   ** its Expr.iRightJoinTable value to find the bitmask of the right table
102782   ** of the join.  Subtracting one from the right table bitmask gives a
102783   ** bitmask for all tables to the left of the join.  Knowing the bitmask
102784   ** for all tables to the left of a left join is important.  Ticket #3015.
102785   **
102786   ** Configure the WhereClause.vmask variable so that bits that correspond
102787   ** to virtual table cursors are set. This is used to selectively disable 
102788   ** the OR-to-IN transformation in exprAnalyzeOrTerm(). It is not helpful 
102789   ** with virtual tables.
102790   **
102791   ** Note that bitmasks are created for all pTabList->nSrc tables in
102792   ** pTabList, not just the first nTabList tables.  nTabList is normally
102793   ** equal to pTabList->nSrc but might be shortened to 1 if the
102794   ** WHERE_ONETABLE_ONLY flag is set.
102795   */
102796   assert( pWC->vmask==0 && pMaskSet->n==0 );
102797   for(i=0; i<pTabList->nSrc; i++){
102798     createMask(pMaskSet, pTabList->a[i].iCursor);
102799 #ifndef SQLITE_OMIT_VIRTUALTABLE
102800     if( ALWAYS(pTabList->a[i].pTab) && IsVirtual(pTabList->a[i].pTab) ){
102801       pWC->vmask |= ((Bitmask)1 << i);
102802     }
102803 #endif
102804   }
102805 #ifndef NDEBUG
102806   {
102807     Bitmask toTheLeft = 0;
102808     for(i=0; i<pTabList->nSrc; i++){
102809       Bitmask m = getMask(pMaskSet, pTabList->a[i].iCursor);
102810       assert( (m-1)==toTheLeft );
102811       toTheLeft |= m;
102812     }
102813   }
102814 #endif
102815
102816   /* Analyze all of the subexpressions.  Note that exprAnalyze() might
102817   ** add new virtual terms onto the end of the WHERE clause.  We do not
102818   ** want to analyze these virtual terms, so start analyzing at the end
102819   ** and work forward so that the added virtual terms are never processed.
102820   */
102821   exprAnalyzeAll(pTabList, pWC);
102822   if( db->mallocFailed ){
102823     goto whereBeginError;
102824   }
102825
102826   /* Chose the best index to use for each table in the FROM clause.
102827   **
102828   ** This loop fills in the following fields:
102829   **
102830   **   pWInfo->a[].pIdx      The index to use for this level of the loop.
102831   **   pWInfo->a[].wsFlags   WHERE_xxx flags associated with pIdx
102832   **   pWInfo->a[].nEq       The number of == and IN constraints
102833   **   pWInfo->a[].iFrom     Which term of the FROM clause is being coded
102834   **   pWInfo->a[].iTabCur   The VDBE cursor for the database table
102835   **   pWInfo->a[].iIdxCur   The VDBE cursor for the index
102836   **   pWInfo->a[].pTerm     When wsFlags==WO_OR, the OR-clause term
102837   **
102838   ** This loop also figures out the nesting order of tables in the FROM
102839   ** clause.
102840   */
102841   notReady = ~(Bitmask)0;
102842   andFlags = ~0;
102843   WHERETRACE(("*** Optimizer Start ***\n"));
102844   for(i=iFrom=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
102845     WhereCost bestPlan;         /* Most efficient plan seen so far */
102846     Index *pIdx;                /* Index for FROM table at pTabItem */
102847     int j;                      /* For looping over FROM tables */
102848     int bestJ = -1;             /* The value of j */
102849     Bitmask m;                  /* Bitmask value for j or bestJ */
102850     int isOptimal;              /* Iterator for optimal/non-optimal search */
102851     int nUnconstrained;         /* Number tables without INDEXED BY */
102852     Bitmask notIndexed;         /* Mask of tables that cannot use an index */
102853
102854     memset(&bestPlan, 0, sizeof(bestPlan));
102855     bestPlan.rCost = SQLITE_BIG_DBL;
102856     WHERETRACE(("*** Begin search for loop %d ***\n", i));
102857
102858     /* Loop through the remaining entries in the FROM clause to find the
102859     ** next nested loop. The loop tests all FROM clause entries
102860     ** either once or twice. 
102861     **
102862     ** The first test is always performed if there are two or more entries
102863     ** remaining and never performed if there is only one FROM clause entry
102864     ** to choose from.  The first test looks for an "optimal" scan.  In
102865     ** this context an optimal scan is one that uses the same strategy
102866     ** for the given FROM clause entry as would be selected if the entry
102867     ** were used as the innermost nested loop.  In other words, a table
102868     ** is chosen such that the cost of running that table cannot be reduced
102869     ** by waiting for other tables to run first.  This "optimal" test works
102870     ** by first assuming that the FROM clause is on the inner loop and finding
102871     ** its query plan, then checking to see if that query plan uses any
102872     ** other FROM clause terms that are notReady.  If no notReady terms are
102873     ** used then the "optimal" query plan works.
102874     **
102875     ** Note that the WhereCost.nRow parameter for an optimal scan might
102876     ** not be as small as it would be if the table really were the innermost
102877     ** join.  The nRow value can be reduced by WHERE clause constraints
102878     ** that do not use indices.  But this nRow reduction only happens if the
102879     ** table really is the innermost join.  
102880     **
102881     ** The second loop iteration is only performed if no optimal scan
102882     ** strategies were found by the first iteration. This second iteration
102883     ** is used to search for the lowest cost scan overall.
102884     **
102885     ** Previous versions of SQLite performed only the second iteration -
102886     ** the next outermost loop was always that with the lowest overall
102887     ** cost. However, this meant that SQLite could select the wrong plan
102888     ** for scripts such as the following:
102889     **   
102890     **   CREATE TABLE t1(a, b); 
102891     **   CREATE TABLE t2(c, d);
102892     **   SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
102893     **
102894     ** The best strategy is to iterate through table t1 first. However it
102895     ** is not possible to determine this with a simple greedy algorithm.
102896     ** Since the cost of a linear scan through table t2 is the same 
102897     ** as the cost of a linear scan through table t1, a simple greedy 
102898     ** algorithm may choose to use t2 for the outer loop, which is a much
102899     ** costlier approach.
102900     */
102901     nUnconstrained = 0;
102902     notIndexed = 0;
102903     for(isOptimal=(iFrom<nTabList-1); isOptimal>=0 && bestJ<0; isOptimal--){
102904       Bitmask mask;             /* Mask of tables not yet ready */
102905       for(j=iFrom, pTabItem=&pTabList->a[j]; j<nTabList; j++, pTabItem++){
102906         int doNotReorder;    /* True if this table should not be reordered */
102907         WhereCost sCost;     /* Cost information from best[Virtual]Index() */
102908         ExprList *pOrderBy;  /* ORDER BY clause for index to optimize */
102909   
102910         doNotReorder =  (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
102911         if( j!=iFrom && doNotReorder ) break;
102912         m = getMask(pMaskSet, pTabItem->iCursor);
102913         if( (m & notReady)==0 ){
102914           if( j==iFrom ) iFrom++;
102915           continue;
102916         }
102917         mask = (isOptimal ? m : notReady);
102918         pOrderBy = ((i==0 && ppOrderBy )?*ppOrderBy:0);
102919         if( pTabItem->pIndex==0 ) nUnconstrained++;
102920   
102921         WHERETRACE(("=== trying table %d with isOptimal=%d ===\n",
102922                     j, isOptimal));
102923         assert( pTabItem->pTab );
102924 #ifndef SQLITE_OMIT_VIRTUALTABLE
102925         if( IsVirtual(pTabItem->pTab) ){
102926           sqlite3_index_info **pp = &pWInfo->a[j].pIdxInfo;
102927           bestVirtualIndex(pParse, pWC, pTabItem, mask, notReady, pOrderBy,
102928                            &sCost, pp);
102929         }else 
102930 #endif
102931         {
102932           bestBtreeIndex(pParse, pWC, pTabItem, mask, notReady, pOrderBy,
102933                          &sCost);
102934         }
102935         assert( isOptimal || (sCost.used&notReady)==0 );
102936
102937         /* If an INDEXED BY clause is present, then the plan must use that
102938         ** index if it uses any index at all */
102939         assert( pTabItem->pIndex==0 
102940                   || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
102941                   || sCost.plan.u.pIdx==pTabItem->pIndex );
102942
102943         if( isOptimal && (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ){
102944           notIndexed |= m;
102945         }
102946
102947         /* Conditions under which this table becomes the best so far:
102948         **
102949         **   (1) The table must not depend on other tables that have not
102950         **       yet run.
102951         **
102952         **   (2) A full-table-scan plan cannot supercede indexed plan unless
102953         **       the full-table-scan is an "optimal" plan as defined above.
102954         **
102955         **   (3) All tables have an INDEXED BY clause or this table lacks an
102956         **       INDEXED BY clause or this table uses the specific
102957         **       index specified by its INDEXED BY clause.  This rule ensures
102958         **       that a best-so-far is always selected even if an impossible
102959         **       combination of INDEXED BY clauses are given.  The error
102960         **       will be detected and relayed back to the application later.
102961         **       The NEVER() comes about because rule (2) above prevents
102962         **       An indexable full-table-scan from reaching rule (3).
102963         **
102964         **   (4) The plan cost must be lower than prior plans or else the
102965         **       cost must be the same and the number of rows must be lower.
102966         */
102967         if( (sCost.used&notReady)==0                       /* (1) */
102968             && (bestJ<0 || (notIndexed&m)!=0               /* (2) */
102969                 || (bestPlan.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
102970                 || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0)
102971             && (nUnconstrained==0 || pTabItem->pIndex==0   /* (3) */
102972                 || NEVER((sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0))
102973             && (bestJ<0 || sCost.rCost<bestPlan.rCost      /* (4) */
102974                 || (sCost.rCost<=bestPlan.rCost 
102975                  && sCost.plan.nRow<bestPlan.plan.nRow))
102976         ){
102977           WHERETRACE(("=== table %d is best so far"
102978                       " with cost=%g and nRow=%g\n",
102979                       j, sCost.rCost, sCost.plan.nRow));
102980           bestPlan = sCost;
102981           bestJ = j;
102982         }
102983         if( doNotReorder ) break;
102984       }
102985     }
102986     assert( bestJ>=0 );
102987     assert( notReady & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
102988     WHERETRACE(("*** Optimizer selects table %d for loop %d"
102989                 " with cost=%g and nRow=%g\n",
102990                 bestJ, pLevel-pWInfo->a, bestPlan.rCost, bestPlan.plan.nRow));
102991     if( (bestPlan.plan.wsFlags & WHERE_ORDERBY)!=0 ){
102992       *ppOrderBy = 0;
102993     }
102994     andFlags &= bestPlan.plan.wsFlags;
102995     pLevel->plan = bestPlan.plan;
102996     testcase( bestPlan.plan.wsFlags & WHERE_INDEXED );
102997     testcase( bestPlan.plan.wsFlags & WHERE_TEMP_INDEX );
102998     if( bestPlan.plan.wsFlags & (WHERE_INDEXED|WHERE_TEMP_INDEX) ){
102999       pLevel->iIdxCur = pParse->nTab++;
103000     }else{
103001       pLevel->iIdxCur = -1;
103002     }
103003     notReady &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
103004     pLevel->iFrom = (u8)bestJ;
103005     if( bestPlan.plan.nRow>=(double)1 ){
103006       pParse->nQueryLoop *= bestPlan.plan.nRow;
103007     }
103008
103009     /* Check that if the table scanned by this loop iteration had an
103010     ** INDEXED BY clause attached to it, that the named index is being
103011     ** used for the scan. If not, then query compilation has failed.
103012     ** Return an error.
103013     */
103014     pIdx = pTabList->a[bestJ].pIndex;
103015     if( pIdx ){
103016       if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){
103017         sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
103018         goto whereBeginError;
103019       }else{
103020         /* If an INDEXED BY clause is used, the bestIndex() function is
103021         ** guaranteed to find the index specified in the INDEXED BY clause
103022         ** if it find an index at all. */
103023         assert( bestPlan.plan.u.pIdx==pIdx );
103024       }
103025     }
103026   }
103027   WHERETRACE(("*** Optimizer Finished ***\n"));
103028   if( pParse->nErr || db->mallocFailed ){
103029     goto whereBeginError;
103030   }
103031
103032   /* If the total query only selects a single row, then the ORDER BY
103033   ** clause is irrelevant.
103034   */
103035   if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
103036     *ppOrderBy = 0;
103037   }
103038
103039   /* If the caller is an UPDATE or DELETE statement that is requesting
103040   ** to use a one-pass algorithm, determine if this is appropriate.
103041   ** The one-pass algorithm only works if the WHERE clause constraints
103042   ** the statement to update a single row.
103043   */
103044   assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
103045   if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
103046     pWInfo->okOnePass = 1;
103047     pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
103048   }
103049
103050   /* Open all tables in the pTabList and any indices selected for
103051   ** searching those tables.
103052   */
103053   sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
103054   notReady = ~(Bitmask)0;
103055   pWInfo->nRowOut = (double)1;
103056   for(i=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
103057     Table *pTab;     /* Table to open */
103058     int iDb;         /* Index of database containing table/index */
103059
103060     pTabItem = &pTabList->a[pLevel->iFrom];
103061     pTab = pTabItem->pTab;
103062     pLevel->iTabCur = pTabItem->iCursor;
103063     pWInfo->nRowOut *= pLevel->plan.nRow;
103064     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
103065     if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
103066       /* Do nothing */
103067     }else
103068 #ifndef SQLITE_OMIT_VIRTUALTABLE
103069     if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
103070       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
103071       int iCur = pTabItem->iCursor;
103072       sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
103073     }else
103074 #endif
103075     if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
103076          && (wctrlFlags & WHERE_OMIT_OPEN)==0 ){
103077       int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
103078       sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
103079       testcase( pTab->nCol==BMS-1 );
103080       testcase( pTab->nCol==BMS );
103081       if( !pWInfo->okOnePass && pTab->nCol<BMS ){
103082         Bitmask b = pTabItem->colUsed;
103083         int n = 0;
103084         for(; b; b=b>>1, n++){}
103085         sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1, 
103086                             SQLITE_INT_TO_PTR(n), P4_INT32);
103087         assert( n<=pTab->nCol );
103088       }
103089     }else{
103090       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
103091     }
103092 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
103093     if( (pLevel->plan.wsFlags & WHERE_TEMP_INDEX)!=0 ){
103094       constructAutomaticIndex(pParse, pWC, pTabItem, notReady, pLevel);
103095     }else
103096 #endif
103097     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
103098       Index *pIx = pLevel->plan.u.pIdx;
103099       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
103100       int iIdxCur = pLevel->iIdxCur;
103101       assert( pIx->pSchema==pTab->pSchema );
103102       assert( iIdxCur>=0 );
103103       sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIx->tnum, iDb,
103104                         (char*)pKey, P4_KEYINFO_HANDOFF);
103105       VdbeComment((v, "%s", pIx->zName));
103106     }
103107     sqlite3CodeVerifySchema(pParse, iDb);
103108     notReady &= ~getMask(pWC->pMaskSet, pTabItem->iCursor);
103109   }
103110   pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
103111   if( db->mallocFailed ) goto whereBeginError;
103112
103113   /* Generate the code to do the search.  Each iteration of the for
103114   ** loop below generates code for a single nested loop of the VM
103115   ** program.
103116   */
103117   notReady = ~(Bitmask)0;
103118   for(i=0; i<nTabList; i++){
103119     pLevel = &pWInfo->a[i];
103120     explainOneScan(pParse, pTabList, pLevel, i, pLevel->iFrom, wctrlFlags);
103121     notReady = codeOneLoopStart(pWInfo, i, wctrlFlags, notReady);
103122     pWInfo->iContinue = pLevel->addrCont;
103123   }
103124
103125 #ifdef SQLITE_TEST  /* For testing and debugging use only */
103126   /* Record in the query plan information about the current table
103127   ** and the index used to access it (if any).  If the table itself
103128   ** is not used, its name is just '{}'.  If no index is used
103129   ** the index is listed as "{}".  If the primary key is used the
103130   ** index name is '*'.
103131   */
103132   for(i=0; i<nTabList; i++){
103133     char *z;
103134     int n;
103135     pLevel = &pWInfo->a[i];
103136     pTabItem = &pTabList->a[pLevel->iFrom];
103137     z = pTabItem->zAlias;
103138     if( z==0 ) z = pTabItem->pTab->zName;
103139     n = sqlite3Strlen30(z);
103140     if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
103141       if( pLevel->plan.wsFlags & WHERE_IDX_ONLY ){
103142         memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
103143         nQPlan += 2;
103144       }else{
103145         memcpy(&sqlite3_query_plan[nQPlan], z, n);
103146         nQPlan += n;
103147       }
103148       sqlite3_query_plan[nQPlan++] = ' ';
103149     }
103150     testcase( pLevel->plan.wsFlags & WHERE_ROWID_EQ );
103151     testcase( pLevel->plan.wsFlags & WHERE_ROWID_RANGE );
103152     if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
103153       memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
103154       nQPlan += 2;
103155     }else if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
103156       n = sqlite3Strlen30(pLevel->plan.u.pIdx->zName);
103157       if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
103158         memcpy(&sqlite3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);
103159         nQPlan += n;
103160         sqlite3_query_plan[nQPlan++] = ' ';
103161       }
103162     }else{
103163       memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
103164       nQPlan += 3;
103165     }
103166   }
103167   while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
103168     sqlite3_query_plan[--nQPlan] = 0;
103169   }
103170   sqlite3_query_plan[nQPlan] = 0;
103171   nQPlan = 0;
103172 #endif /* SQLITE_TEST // Testing and debugging use only */
103173
103174   /* Record the continuation address in the WhereInfo structure.  Then
103175   ** clean up and return.
103176   */
103177   return pWInfo;
103178
103179   /* Jump here if malloc fails */
103180 whereBeginError:
103181   if( pWInfo ){
103182     pParse->nQueryLoop = pWInfo->savedNQueryLoop;
103183     whereInfoFree(db, pWInfo);
103184   }
103185   return 0;
103186 }
103187
103188 /*
103189 ** Generate the end of the WHERE loop.  See comments on 
103190 ** sqlite3WhereBegin() for additional information.
103191 */
103192 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
103193   Parse *pParse = pWInfo->pParse;
103194   Vdbe *v = pParse->pVdbe;
103195   int i;
103196   WhereLevel *pLevel;
103197   SrcList *pTabList = pWInfo->pTabList;
103198   sqlite3 *db = pParse->db;
103199
103200   /* Generate loop termination code.
103201   */
103202   sqlite3ExprCacheClear(pParse);
103203   for(i=pWInfo->nLevel-1; i>=0; i--){
103204     pLevel = &pWInfo->a[i];
103205     sqlite3VdbeResolveLabel(v, pLevel->addrCont);
103206     if( pLevel->op!=OP_Noop ){
103207       sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
103208       sqlite3VdbeChangeP5(v, pLevel->p5);
103209     }
103210     if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
103211       struct InLoop *pIn;
103212       int j;
103213       sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
103214       for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
103215         sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
103216         sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->addrInTop);
103217         sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
103218       }
103219       sqlite3DbFree(db, pLevel->u.in.aInLoop);
103220     }
103221     sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
103222     if( pLevel->iLeftJoin ){
103223       int addr;
103224       addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
103225       assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
103226            || (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 );
103227       if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
103228         sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
103229       }
103230       if( pLevel->iIdxCur>=0 ){
103231         sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
103232       }
103233       if( pLevel->op==OP_Return ){
103234         sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
103235       }else{
103236         sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
103237       }
103238       sqlite3VdbeJumpHere(v, addr);
103239     }
103240   }
103241
103242   /* The "break" point is here, just past the end of the outer loop.
103243   ** Set it.
103244   */
103245   sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
103246
103247   /* Close all of the cursors that were opened by sqlite3WhereBegin.
103248   */
103249   assert( pWInfo->nLevel==1 || pWInfo->nLevel==pTabList->nSrc );
103250   for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
103251     struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
103252     Table *pTab = pTabItem->pTab;
103253     assert( pTab!=0 );
103254     if( (pTab->tabFlags & TF_Ephemeral)==0
103255      && pTab->pSelect==0
103256      && (pWInfo->wctrlFlags & WHERE_OMIT_CLOSE)==0
103257     ){
103258       int ws = pLevel->plan.wsFlags;
103259       if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
103260         sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
103261       }
103262       if( (ws & WHERE_INDEXED)!=0 && (ws & WHERE_TEMP_INDEX)==0 ){
103263         sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
103264       }
103265     }
103266
103267     /* If this scan uses an index, make code substitutions to read data
103268     ** from the index in preference to the table. Sometimes, this means
103269     ** the table need never be read from. This is a performance boost,
103270     ** as the vdbe level waits until the table is read before actually
103271     ** seeking the table cursor to the record corresponding to the current
103272     ** position in the index.
103273     ** 
103274     ** Calls to the code generator in between sqlite3WhereBegin and
103275     ** sqlite3WhereEnd will have created code that references the table
103276     ** directly.  This loop scans all that code looking for opcodes
103277     ** that reference the table and converts them into opcodes that
103278     ** reference the index.
103279     */
103280     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 && !db->mallocFailed){
103281       int k, j, last;
103282       VdbeOp *pOp;
103283       Index *pIdx = pLevel->plan.u.pIdx;
103284
103285       assert( pIdx!=0 );
103286       pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
103287       last = sqlite3VdbeCurrentAddr(v);
103288       for(k=pWInfo->iTop; k<last; k++, pOp++){
103289         if( pOp->p1!=pLevel->iTabCur ) continue;
103290         if( pOp->opcode==OP_Column ){
103291           for(j=0; j<pIdx->nColumn; j++){
103292             if( pOp->p2==pIdx->aiColumn[j] ){
103293               pOp->p2 = j;
103294               pOp->p1 = pLevel->iIdxCur;
103295               break;
103296             }
103297           }
103298           assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
103299                || j<pIdx->nColumn );
103300         }else if( pOp->opcode==OP_Rowid ){
103301           pOp->p1 = pLevel->iIdxCur;
103302           pOp->opcode = OP_IdxRowid;
103303         }
103304       }
103305     }
103306   }
103307
103308   /* Final cleanup
103309   */
103310   pParse->nQueryLoop = pWInfo->savedNQueryLoop;
103311   whereInfoFree(db, pWInfo);
103312   return;
103313 }
103314
103315 /************** End of where.c ***********************************************/
103316 /************** Begin file parse.c *******************************************/
103317 /* Driver template for the LEMON parser generator.
103318 ** The author disclaims copyright to this source code.
103319 **
103320 ** This version of "lempar.c" is modified, slightly, for use by SQLite.
103321 ** The only modifications are the addition of a couple of NEVER()
103322 ** macros to disable tests that are needed in the case of a general
103323 ** LALR(1) grammar but which are always false in the
103324 ** specific grammar used by SQLite.
103325 */
103326 /* First off, code is included that follows the "include" declaration
103327 ** in the input grammar file. */
103328
103329
103330 /*
103331 ** Disable all error recovery processing in the parser push-down
103332 ** automaton.
103333 */
103334 #define YYNOERRORRECOVERY 1
103335
103336 /*
103337 ** Make yytestcase() the same as testcase()
103338 */
103339 #define yytestcase(X) testcase(X)
103340
103341 /*
103342 ** An instance of this structure holds information about the
103343 ** LIMIT clause of a SELECT statement.
103344 */
103345 struct LimitVal {
103346   Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
103347   Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
103348 };
103349
103350 /*
103351 ** An instance of this structure is used to store the LIKE,
103352 ** GLOB, NOT LIKE, and NOT GLOB operators.
103353 */
103354 struct LikeOp {
103355   Token eOperator;  /* "like" or "glob" or "regexp" */
103356   int not;         /* True if the NOT keyword is present */
103357 };
103358
103359 /*
103360 ** An instance of the following structure describes the event of a
103361 ** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
103362 ** TK_DELETE, or TK_INSTEAD.  If the event is of the form
103363 **
103364 **      UPDATE ON (a,b,c)
103365 **
103366 ** Then the "b" IdList records the list "a,b,c".
103367 */
103368 struct TrigEvent { int a; IdList * b; };
103369
103370 /*
103371 ** An instance of this structure holds the ATTACH key and the key type.
103372 */
103373 struct AttachKey { int type;  Token key; };
103374
103375
103376   /* This is a utility routine used to set the ExprSpan.zStart and
103377   ** ExprSpan.zEnd values of pOut so that the span covers the complete
103378   ** range of text beginning with pStart and going to the end of pEnd.
103379   */
103380   static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
103381     pOut->zStart = pStart->z;
103382     pOut->zEnd = &pEnd->z[pEnd->n];
103383   }
103384
103385   /* Construct a new Expr object from a single identifier.  Use the
103386   ** new Expr to populate pOut.  Set the span of pOut to be the identifier
103387   ** that created the expression.
103388   */
103389   static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
103390     pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
103391     pOut->zStart = pValue->z;
103392     pOut->zEnd = &pValue->z[pValue->n];
103393   }
103394
103395   /* This routine constructs a binary expression node out of two ExprSpan
103396   ** objects and uses the result to populate a new ExprSpan object.
103397   */
103398   static void spanBinaryExpr(
103399     ExprSpan *pOut,     /* Write the result here */
103400     Parse *pParse,      /* The parsing context.  Errors accumulate here */
103401     int op,             /* The binary operation */
103402     ExprSpan *pLeft,    /* The left operand */
103403     ExprSpan *pRight    /* The right operand */
103404   ){
103405     pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
103406     pOut->zStart = pLeft->zStart;
103407     pOut->zEnd = pRight->zEnd;
103408   }
103409
103410   /* Construct an expression node for a unary postfix operator
103411   */
103412   static void spanUnaryPostfix(
103413     ExprSpan *pOut,        /* Write the new expression node here */
103414     Parse *pParse,         /* Parsing context to record errors */
103415     int op,                /* The operator */
103416     ExprSpan *pOperand,    /* The operand */
103417     Token *pPostOp         /* The operand token for setting the span */
103418   ){
103419     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
103420     pOut->zStart = pOperand->zStart;
103421     pOut->zEnd = &pPostOp->z[pPostOp->n];
103422   }                           
103423
103424   /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
103425   ** unary TK_ISNULL or TK_NOTNULL expression. */
103426   static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
103427     sqlite3 *db = pParse->db;
103428     if( db->mallocFailed==0 && pY->op==TK_NULL ){
103429       pA->op = (u8)op;
103430       sqlite3ExprDelete(db, pA->pRight);
103431       pA->pRight = 0;
103432     }
103433   }
103434
103435   /* Construct an expression node for a unary prefix operator
103436   */
103437   static void spanUnaryPrefix(
103438     ExprSpan *pOut,        /* Write the new expression node here */
103439     Parse *pParse,         /* Parsing context to record errors */
103440     int op,                /* The operator */
103441     ExprSpan *pOperand,    /* The operand */
103442     Token *pPreOp         /* The operand token for setting the span */
103443   ){
103444     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
103445     pOut->zStart = pPreOp->z;
103446     pOut->zEnd = pOperand->zEnd;
103447   }
103448 /* Next is all token values, in a form suitable for use by makeheaders.
103449 ** This section will be null unless lemon is run with the -m switch.
103450 */
103451 /* 
103452 ** These constants (all generated automatically by the parser generator)
103453 ** specify the various kinds of tokens (terminals) that the parser
103454 ** understands. 
103455 **
103456 ** Each symbol here is a terminal symbol in the grammar.
103457 */
103458 /* Make sure the INTERFACE macro is defined.
103459 */
103460 #ifndef INTERFACE
103461 # define INTERFACE 1
103462 #endif
103463 /* The next thing included is series of defines which control
103464 ** various aspects of the generated parser.
103465 **    YYCODETYPE         is the data type used for storing terminal
103466 **                       and nonterminal numbers.  "unsigned char" is
103467 **                       used if there are fewer than 250 terminals
103468 **                       and nonterminals.  "int" is used otherwise.
103469 **    YYNOCODE           is a number of type YYCODETYPE which corresponds
103470 **                       to no legal terminal or nonterminal number.  This
103471 **                       number is used to fill in empty slots of the hash 
103472 **                       table.
103473 **    YYFALLBACK         If defined, this indicates that one or more tokens
103474 **                       have fall-back values which should be used if the
103475 **                       original value of the token will not parse.
103476 **    YYACTIONTYPE       is the data type used for storing terminal
103477 **                       and nonterminal numbers.  "unsigned char" is
103478 **                       used if there are fewer than 250 rules and
103479 **                       states combined.  "int" is used otherwise.
103480 **    sqlite3ParserTOKENTYPE     is the data type used for minor tokens given 
103481 **                       directly to the parser from the tokenizer.
103482 **    YYMINORTYPE        is the data type used for all minor tokens.
103483 **                       This is typically a union of many types, one of
103484 **                       which is sqlite3ParserTOKENTYPE.  The entry in the union
103485 **                       for base tokens is called "yy0".
103486 **    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
103487 **                       zero the stack is dynamically sized using realloc()
103488 **    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
103489 **    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
103490 **    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
103491 **    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
103492 **    YYNSTATE           the combined number of states.
103493 **    YYNRULE            the number of rules in the grammar
103494 **    YYERRORSYMBOL      is the code number of the error symbol.  If not
103495 **                       defined, then do no error processing.
103496 */
103497 #define YYCODETYPE unsigned char
103498 #define YYNOCODE 253
103499 #define YYACTIONTYPE unsigned short int
103500 #define YYWILDCARD 67
103501 #define sqlite3ParserTOKENTYPE Token
103502 typedef union {
103503   int yyinit;
103504   sqlite3ParserTOKENTYPE yy0;
103505   int yy4;
103506   struct TrigEvent yy90;
103507   ExprSpan yy118;
103508   TriggerStep* yy203;
103509   u8 yy210;
103510   struct {int value; int mask;} yy215;
103511   SrcList* yy259;
103512   struct LimitVal yy292;
103513   Expr* yy314;
103514   ExprList* yy322;
103515   struct LikeOp yy342;
103516   IdList* yy384;
103517   Select* yy387;
103518 } YYMINORTYPE;
103519 #ifndef YYSTACKDEPTH
103520 #define YYSTACKDEPTH 100
103521 #endif
103522 #define sqlite3ParserARG_SDECL Parse *pParse;
103523 #define sqlite3ParserARG_PDECL ,Parse *pParse
103524 #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
103525 #define sqlite3ParserARG_STORE yypParser->pParse = pParse
103526 #define YYNSTATE 630
103527 #define YYNRULE 329
103528 #define YYFALLBACK 1
103529 #define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
103530 #define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
103531 #define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)
103532
103533 /* The yyzerominor constant is used to initialize instances of
103534 ** YYMINORTYPE objects to zero. */
103535 static const YYMINORTYPE yyzerominor = { 0 };
103536
103537 /* Define the yytestcase() macro to be a no-op if is not already defined
103538 ** otherwise.
103539 **
103540 ** Applications can choose to define yytestcase() in the %include section
103541 ** to a macro that can assist in verifying code coverage.  For production
103542 ** code the yytestcase() macro should be turned off.  But it is useful
103543 ** for testing.
103544 */
103545 #ifndef yytestcase
103546 # define yytestcase(X)
103547 #endif
103548
103549
103550 /* Next are the tables used to determine what action to take based on the
103551 ** current state and lookahead token.  These tables are used to implement
103552 ** functions that take a state number and lookahead value and return an
103553 ** action integer.  
103554 **
103555 ** Suppose the action integer is N.  Then the action is determined as
103556 ** follows
103557 **
103558 **   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
103559 **                                      token onto the stack and goto state N.
103560 **
103561 **   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
103562 **
103563 **   N == YYNSTATE+YYNRULE              A syntax error has occurred.
103564 **
103565 **   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
103566 **
103567 **   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
103568 **                                      slots in the yy_action[] table.
103569 **
103570 ** The action table is constructed as a single large table named yy_action[].
103571 ** Given state S and lookahead X, the action is computed as
103572 **
103573 **      yy_action[ yy_shift_ofst[S] + X ]
103574 **
103575 ** If the index value yy_shift_ofst[S]+X is out of range or if the value
103576 ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
103577 ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
103578 ** and that yy_default[S] should be used instead.  
103579 **
103580 ** The formula above is for computing the action when the lookahead is
103581 ** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
103582 ** a reduce action) then the yy_reduce_ofst[] array is used in place of
103583 ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
103584 ** YY_SHIFT_USE_DFLT.
103585 **
103586 ** The following are the tables generated in this section:
103587 **
103588 **  yy_action[]        A single table containing all actions.
103589 **  yy_lookahead[]     A table containing the lookahead for each entry in
103590 **                     yy_action.  Used to detect hash collisions.
103591 **  yy_shift_ofst[]    For each state, the offset into yy_action for
103592 **                     shifting terminals.
103593 **  yy_reduce_ofst[]   For each state, the offset into yy_action for
103594 **                     shifting non-terminals after a reduce.
103595 **  yy_default[]       Default action for each state.
103596 */
103597 #define YY_ACTTAB_COUNT (1557)
103598 static const YYACTIONTYPE yy_action[] = {
103599  /*     0 */   313,  960,  186,  419,    2,  172,  627,  597,   55,   55,
103600  /*    10 */    55,   55,   48,   53,   53,   53,   53,   52,   52,   51,
103601  /*    20 */    51,   51,   50,  238,  302,  283,  623,  622,  516,  515,
103602  /*    30 */   590,  584,   55,   55,   55,   55,  282,   53,   53,   53,
103603  /*    40 */    53,   52,   52,   51,   51,   51,   50,  238,    6,   56,
103604  /*    50 */    57,   47,  582,  581,  583,  583,   54,   54,   55,   55,
103605  /*    60 */    55,   55,  608,   53,   53,   53,   53,   52,   52,   51,
103606  /*    70 */    51,   51,   50,  238,  313,  597,  409,  330,  579,  579,
103607  /*    80 */    32,   53,   53,   53,   53,   52,   52,   51,   51,   51,
103608  /*    90 */    50,  238,  330,  217,  620,  619,  166,  411,  624,  382,
103609  /*   100 */   379,  378,    7,  491,  590,  584,  200,  199,  198,   58,
103610  /*   110 */   377,  300,  414,  621,  481,   66,  623,  622,  621,  580,
103611  /*   120 */   254,  601,   94,   56,   57,   47,  582,  581,  583,  583,
103612  /*   130 */    54,   54,   55,   55,   55,   55,  671,   53,   53,   53,
103613  /*   140 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  532,
103614  /*   150 */   226,  506,  507,  133,  177,  139,  284,  385,  279,  384,
103615  /*   160 */   169,  197,  342,  398,  251,  226,  253,  275,  388,  167,
103616  /*   170 */   139,  284,  385,  279,  384,  169,  570,  236,  590,  584,
103617  /*   180 */   672,  240,  275,  157,  620,  619,  554,  437,   51,   51,
103618  /*   190 */    51,   50,  238,  343,  439,  553,  438,   56,   57,   47,
103619  /*   200 */   582,  581,  583,  583,   54,   54,   55,   55,   55,   55,
103620  /*   210 */   465,   53,   53,   53,   53,   52,   52,   51,   51,   51,
103621  /*   220 */    50,  238,  313,  390,   52,   52,   51,   51,   51,   50,
103622  /*   230 */   238,  391,  166,  491,  566,  382,  379,  378,  409,  440,
103623  /*   240 */   579,  579,  252,  440,  607,   66,  377,  513,  621,   49,
103624  /*   250 */    46,  147,  590,  584,  621,   16,  466,  189,  621,  441,
103625  /*   260 */   442,  673,  526,  441,  340,  577,  595,   64,  194,  482,
103626  /*   270 */   434,   56,   57,   47,  582,  581,  583,  583,   54,   54,
103627  /*   280 */    55,   55,   55,   55,   30,   53,   53,   53,   53,   52,
103628  /*   290 */    52,   51,   51,   51,   50,  238,  313,  593,  593,  593,
103629  /*   300 */   387,  578,  606,  493,  259,  351,  258,  411,    1,  623,
103630  /*   310 */   622,  496,  623,  622,   65,  240,  623,  622,  597,  443,
103631  /*   320 */   237,  239,  414,  341,  237,  602,  590,  584,   18,  603,
103632  /*   330 */   166,  601,   87,  382,  379,  378,   67,  623,  622,   38,
103633  /*   340 */   623,  622,  176,  270,  377,   56,   57,   47,  582,  581,
103634  /*   350 */   583,  583,   54,   54,   55,   55,   55,   55,  175,   53,
103635  /*   360 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
103636  /*   370 */   313,  396,  233,  411,  531,  565,  317,  620,  619,   44,
103637  /*   380 */   620,  619,  240,  206,  620,  619,  597,  266,  414,  268,
103638  /*   390 */   409,  597,  579,  579,  352,  184,  505,  601,   73,  533,
103639  /*   400 */   590,  584,  466,  548,  190,  620,  619,  576,  620,  619,
103640  /*   410 */   547,  383,  551,   35,  332,  575,  574,  600,  504,   56,
103641  /*   420 */    57,   47,  582,  581,  583,  583,   54,   54,   55,   55,
103642  /*   430 */    55,   55,  567,   53,   53,   53,   53,   52,   52,   51,
103643  /*   440 */    51,   51,   50,  238,  313,  411,  561,  561,  528,  364,
103644  /*   450 */   259,  351,  258,  183,  361,  549,  524,  374,  411,  597,
103645  /*   460 */   414,  240,  560,  560,  409,  604,  579,  579,  328,  601,
103646  /*   470 */    93,  623,  622,  414,  590,  584,  237,  564,  559,  559,
103647  /*   480 */   520,  402,  601,   87,  409,  210,  579,  579,  168,  421,
103648  /*   490 */   950,  519,  950,   56,   57,   47,  582,  581,  583,  583,
103649  /*   500 */    54,   54,   55,   55,   55,   55,  192,   53,   53,   53,
103650  /*   510 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  600,
103651  /*   520 */   293,  563,  511,  234,  357,  146,  475,  475,  367,  411,
103652  /*   530 */   562,  411,  358,  542,  425,  171,  411,  215,  144,  620,
103653  /*   540 */   619,  544,  318,  353,  414,  203,  414,  275,  590,  584,
103654  /*   550 */   549,  414,  174,  601,   94,  601,   79,  558,  471,   61,
103655  /*   560 */   601,   79,  421,  949,  350,  949,   34,   56,   57,   47,
103656  /*   570 */   582,  581,  583,  583,   54,   54,   55,   55,   55,   55,
103657  /*   580 */   535,   53,   53,   53,   53,   52,   52,   51,   51,   51,
103658  /*   590 */    50,  238,  313,  307,  424,  394,  272,   49,   46,  147,
103659  /*   600 */   349,  322,    4,  411,  491,  312,  321,  425,  568,  492,
103660  /*   610 */   216,  264,  407,  575,  574,  429,   66,  549,  414,  621,
103661  /*   620 */   540,  602,  590,  584,   13,  603,  621,  601,   72,   12,
103662  /*   630 */   618,  617,  616,  202,  210,  621,  546,  469,  422,  319,
103663  /*   640 */   148,   56,   57,   47,  582,  581,  583,  583,   54,   54,
103664  /*   650 */    55,   55,   55,   55,  338,   53,   53,   53,   53,   52,
103665  /*   660 */    52,   51,   51,   51,   50,  238,  313,  600,  600,  411,
103666  /*   670 */    39,   21,   37,  170,  237,  875,  411,  572,  572,  201,
103667  /*   680 */   144,  473,  538,  331,  414,  474,  143,  146,  630,  628,
103668  /*   690 */   334,  414,  353,  601,   68,  168,  590,  584,  132,  365,
103669  /*   700 */   601,   96,  307,  423,  530,  336,   49,   46,  147,  568,
103670  /*   710 */   406,  216,  549,  360,  529,   56,   57,   47,  582,  581,
103671  /*   720 */   583,  583,   54,   54,   55,   55,   55,   55,  411,   53,
103672  /*   730 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
103673  /*   740 */   313,  411,  605,  414,  484,  510,  172,  422,  597,  318,
103674  /*   750 */   496,  485,  601,   99,  411,  142,  414,  411,  231,  411,
103675  /*   760 */   540,  411,  359,  629,    2,  601,   97,  426,  308,  414,
103676  /*   770 */   590,  584,  414,   20,  414,  621,  414,  621,  601,  106,
103677  /*   780 */   503,  601,  105,  601,  108,  601,  109,  204,   28,   56,
103678  /*   790 */    57,   47,  582,  581,  583,  583,   54,   54,   55,   55,
103679  /*   800 */    55,   55,  411,   53,   53,   53,   53,   52,   52,   51,
103680  /*   810 */    51,   51,   50,  238,  313,  411,  597,  414,  411,  276,
103681  /*   820 */   214,  600,  411,  366,  213,  381,  601,  134,  274,  500,
103682  /*   830 */   414,  167,  130,  414,  621,  411,  354,  414,  376,  601,
103683  /*   840 */   135,  129,  601,  100,  590,  584,  601,  104,  522,  521,
103684  /*   850 */   414,  621,  224,  273,  600,  167,  327,  282,  600,  601,
103685  /*   860 */   103,  468,  521,   56,   57,   47,  582,  581,  583,  583,
103686  /*   870 */    54,   54,   55,   55,   55,   55,  411,   53,   53,   53,
103687  /*   880 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  411,
103688  /*   890 */    27,  414,  411,  375,  276,  167,  359,  544,   50,  238,
103689  /*   900 */   601,   95,  128,  223,  414,  411,  165,  414,  411,  621,
103690  /*   910 */   411,  621,  612,  601,  102,  372,  601,   76,  590,  584,
103691  /*   920 */   414,  570,  236,  414,  470,  414,  167,  621,  188,  601,
103692  /*   930 */    98,  225,  601,  138,  601,  137,  232,   56,   45,   47,
103693  /*   940 */   582,  581,  583,  583,   54,   54,   55,   55,   55,   55,
103694  /*   950 */   411,   53,   53,   53,   53,   52,   52,   51,   51,   51,
103695  /*   960 */    50,  238,  313,  276,  276,  414,  411,  276,  544,  459,
103696  /*   970 */   359,  171,  209,  479,  601,  136,  628,  334,  621,  621,
103697  /*   980 */   125,  414,  621,  368,  411,  621,  257,  540,  589,  588,
103698  /*   990 */   601,   75,  590,  584,  458,  446,   23,   23,  124,  414,
103699  /*  1000 */   326,  325,  621,  427,  324,  309,  600,  288,  601,   92,
103700  /*  1010 */   586,  585,   57,   47,  582,  581,  583,  583,   54,   54,
103701  /*  1020 */    55,   55,   55,   55,  411,   53,   53,   53,   53,   52,
103702  /*  1030 */    52,   51,   51,   51,   50,  238,  313,  587,  411,  414,
103703  /*  1040 */   411,  207,  611,  476,  171,  472,  160,  123,  601,   91,
103704  /*  1050 */   323,  261,   15,  414,  464,  414,  411,  621,  411,  354,
103705  /*  1060 */   222,  411,  601,   74,  601,   90,  590,  584,  159,  264,
103706  /*  1070 */   158,  414,  461,  414,  621,  600,  414,  121,  120,   25,
103707  /*  1080 */   601,   89,  601,  101,  621,  601,   88,   47,  582,  581,
103708  /*  1090 */   583,  583,   54,   54,   55,   55,   55,   55,  544,   53,
103709  /*  1100 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
103710  /*  1110 */    43,  405,  263,    3,  610,  264,  140,  415,  622,   24,
103711  /*  1120 */   410,   11,  456,  594,  118,  155,  219,  452,  408,  621,
103712  /*  1130 */   621,  621,  156,   43,  405,  621,    3,  286,  621,  113,
103713  /*  1140 */   415,  622,  111,  445,  411,  400,  557,  403,  545,   10,
103714  /*  1150 */   411,  408,  264,  110,  205,  436,  541,  566,  453,  414,
103715  /*  1160 */   621,  621,   63,  621,  435,  414,  411,  621,  601,   94,
103716  /*  1170 */   403,  621,  411,  337,  601,   86,  150,   40,   41,  534,
103717  /*  1180 */   566,  414,  242,  264,   42,  413,  412,  414,  600,  595,
103718  /*  1190 */   601,   85,  191,  333,  107,  451,  601,   84,  621,  539,
103719  /*  1200 */    40,   41,  420,  230,  411,  149,  316,   42,  413,  412,
103720  /*  1210 */   398,  127,  595,  315,  621,  399,  278,  625,  181,  414,
103721  /*  1220 */   593,  593,  593,  592,  591,   14,  450,  411,  601,   71,
103722  /*  1230 */   240,  621,   43,  405,  264,    3,  615,  180,  264,  415,
103723  /*  1240 */   622,  614,  414,  593,  593,  593,  592,  591,   14,  621,
103724  /*  1250 */   408,  601,   70,  621,  417,   33,  405,  613,    3,  411,
103725  /*  1260 */   264,  411,  415,  622,  418,  626,  178,  509,    8,  403,
103726  /*  1270 */   241,  416,  126,  408,  414,  621,  414,  449,  208,  566,
103727  /*  1280 */   240,  221,  621,  601,   83,  601,   82,  599,  297,  277,
103728  /*  1290 */   296,   30,  403,   31,  395,  264,  295,  397,  489,   40,
103729  /*  1300 */    41,  411,  566,  220,  621,  294,   42,  413,  412,  271,
103730  /*  1310 */   621,  595,  600,  621,   59,   60,  414,  269,  267,  623,
103731  /*  1320 */   622,   36,   40,   41,  621,  601,   81,  598,  235,   42,
103732  /*  1330 */   413,  412,  621,  621,  595,  265,  344,  411,  248,  556,
103733  /*  1340 */   173,  185,  593,  593,  593,  592,  591,   14,  218,   29,
103734  /*  1350 */   621,  543,  414,  305,  304,  303,  179,  301,  411,  566,
103735  /*  1360 */   454,  601,   80,  289,  335,  593,  593,  593,  592,  591,
103736  /*  1370 */    14,  411,  287,  414,  151,  392,  246,  260,  411,  196,
103737  /*  1380 */   195,  523,  601,   69,  411,  245,  414,  526,  537,  285,
103738  /*  1390 */   389,  595,  621,  414,  536,  601,   17,  362,  153,  414,
103739  /*  1400 */   466,  463,  601,   78,  154,  414,  462,  152,  601,   77,
103740  /*  1410 */   355,  255,  621,  455,  601,    9,  621,  386,  444,  517,
103741  /*  1420 */   247,  621,  593,  593,  593,  621,  621,  244,  621,  243,
103742  /*  1430 */   430,  518,  292,  621,  329,  621,  145,  393,  280,  513,
103743  /*  1440 */   291,  131,  621,  514,  621,  621,  311,  621,  259,  346,
103744  /*  1450 */   249,  621,  621,  229,  314,  621,  228,  512,  227,  240,
103745  /*  1460 */   494,  488,  310,  164,  487,  486,  373,  480,  163,  262,
103746  /*  1470 */   369,  371,  162,   26,  212,  478,  477,  161,  141,  363,
103747  /*  1480 */   467,  122,  339,  187,  119,  348,  347,  117,  116,  115,
103748  /*  1490 */   114,  112,  182,  457,  320,   22,  433,  432,  448,   19,
103749  /*  1500 */   609,  431,  428,   62,  193,  596,  573,  298,  555,  552,
103750  /*  1510 */   571,  404,  290,  380,  498,  510,  495,  306,  281,  499,
103751  /*  1520 */   250,    5,  497,  460,  345,  447,  569,  550,  238,  299,
103752  /*  1530 */   527,  525,  508,  961,  502,  501,  961,  401,  961,  211,
103753  /*  1540 */   490,  356,  256,  961,  483,  961,  961,  961,  961,  961,
103754  /*  1550 */   961,  961,  961,  961,  961,  961,  370,
103755 };
103756 static const YYCODETYPE yy_lookahead[] = {
103757  /*     0 */    19,  142,  143,  144,  145,   24,    1,   26,   77,   78,
103758  /*    10 */    79,   80,   81,   82,   83,   84,   85,   86,   87,   88,
103759  /*    20 */    89,   90,   91,   92,   15,   98,   26,   27,    7,    8,
103760  /*    30 */    49,   50,   77,   78,   79,   80,  109,   82,   83,   84,
103761  /*    40 */    85,   86,   87,   88,   89,   90,   91,   92,   22,   68,
103762  /*    50 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
103763  /*    60 */    79,   80,   23,   82,   83,   84,   85,   86,   87,   88,
103764  /*    70 */    89,   90,   91,   92,   19,   94,  112,   19,  114,  115,
103765  /*    80 */    25,   82,   83,   84,   85,   86,   87,   88,   89,   90,
103766  /*    90 */    91,   92,   19,   22,   94,   95,   96,  150,  150,   99,
103767  /*   100 */   100,  101,   76,  150,   49,   50,  105,  106,  107,   54,
103768  /*   110 */   110,  158,  165,  165,  161,  162,   26,   27,  165,  113,
103769  /*   120 */    16,  174,  175,   68,   69,   70,   71,   72,   73,   74,
103770  /*   130 */    75,   76,   77,   78,   79,   80,  118,   82,   83,   84,
103771  /*   140 */    85,   86,   87,   88,   89,   90,   91,   92,   19,   23,
103772  /*   150 */    92,   97,   98,   24,   96,   97,   98,   99,  100,  101,
103773  /*   160 */   102,   25,   97,  216,   60,   92,   62,  109,  221,   25,
103774  /*   170 */    97,   98,   99,  100,  101,  102,   86,   87,   49,   50,
103775  /*   180 */   118,  116,  109,   25,   94,   95,   32,   97,   88,   89,
103776  /*   190 */    90,   91,   92,  128,  104,   41,  106,   68,   69,   70,
103777  /*   200 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
103778  /*   210 */    11,   82,   83,   84,   85,   86,   87,   88,   89,   90,
103779  /*   220 */    91,   92,   19,   19,   86,   87,   88,   89,   90,   91,
103780  /*   230 */    92,   27,   96,  150,   66,   99,  100,  101,  112,  150,
103781  /*   240 */   114,  115,  138,  150,  161,  162,  110,  103,  165,  222,
103782  /*   250 */   223,  224,   49,   50,  165,   22,   57,   24,  165,  170,
103783  /*   260 */   171,  118,   94,  170,  171,   23,   98,   25,  185,  186,
103784  /*   270 */   243,   68,   69,   70,   71,   72,   73,   74,   75,   76,
103785  /*   280 */    77,   78,   79,   80,  126,   82,   83,   84,   85,   86,
103786  /*   290 */    87,   88,   89,   90,   91,   92,   19,  129,  130,  131,
103787  /*   300 */    88,   23,  172,  173,  105,  106,  107,  150,   22,   26,
103788  /*   310 */    27,  181,   26,   27,   22,  116,   26,   27,   26,  230,
103789  /*   320 */   231,  197,  165,  230,  231,  113,   49,   50,  204,  117,
103790  /*   330 */    96,  174,  175,   99,  100,  101,   22,   26,   27,  136,
103791  /*   340 */    26,   27,  118,   16,  110,   68,   69,   70,   71,   72,
103792  /*   350 */    73,   74,   75,   76,   77,   78,   79,   80,  118,   82,
103793  /*   360 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
103794  /*   370 */    19,  214,  215,  150,   23,   23,  155,   94,   95,   22,
103795  /*   380 */    94,   95,  116,  160,   94,   95,   94,   60,  165,   62,
103796  /*   390 */   112,   26,  114,  115,  128,   23,   36,  174,  175,   88,
103797  /*   400 */    49,   50,   57,  120,   22,   94,   95,   23,   94,   95,
103798  /*   410 */   120,   51,   25,  136,  169,  170,  171,  194,   58,   68,
103799  /*   420 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
103800  /*   430 */    79,   80,   23,   82,   83,   84,   85,   86,   87,   88,
103801  /*   440 */    89,   90,   91,   92,   19,  150,   12,   12,   23,  228,
103802  /*   450 */   105,  106,  107,   23,  233,   25,  165,   19,  150,   94,
103803  /*   460 */   165,  116,   28,   28,  112,  174,  114,  115,  108,  174,
103804  /*   470 */   175,   26,   27,  165,   49,   50,  231,   11,   44,   44,
103805  /*   480 */    46,   46,  174,  175,  112,  160,  114,  115,   50,   22,
103806  /*   490 */    23,   57,   25,   68,   69,   70,   71,   72,   73,   74,
103807  /*   500 */    75,   76,   77,   78,   79,   80,  119,   82,   83,   84,
103808  /*   510 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  194,
103809  /*   520 */   225,   23,   23,  215,   19,   95,  105,  106,  107,  150,
103810  /*   530 */    23,  150,   27,   23,   67,   25,  150,  206,  207,   94,
103811  /*   540 */    95,  166,  104,  218,  165,   22,  165,  109,   49,   50,
103812  /*   550 */   120,  165,   25,  174,  175,  174,  175,   23,   21,  234,
103813  /*   560 */   174,  175,   22,   23,  239,   25,   25,   68,   69,   70,
103814  /*   570 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
103815  /*   580 */   205,   82,   83,   84,   85,   86,   87,   88,   89,   90,
103816  /*   590 */    91,   92,   19,   22,   23,  216,   23,  222,  223,  224,
103817  /*   600 */    63,  220,   35,  150,  150,  163,  220,   67,  166,  167,
103818  /*   610 */   168,  150,  169,  170,  171,  161,  162,   25,  165,  165,
103819  /*   620 */   150,  113,   49,   50,   25,  117,  165,  174,  175,   35,
103820  /*   630 */     7,    8,    9,  160,  160,  165,  120,  100,   67,  247,
103821  /*   640 */   248,   68,   69,   70,   71,   72,   73,   74,   75,   76,
103822  /*   650 */    77,   78,   79,   80,  193,   82,   83,   84,   85,   86,
103823  /*   660 */    87,   88,   89,   90,   91,   92,   19,  194,  194,  150,
103824  /*   670 */   135,   24,  137,   35,  231,  138,  150,  129,  130,  206,
103825  /*   680 */   207,   30,   27,  213,  165,   34,  118,   95,    0,    1,
103826  /*   690 */     2,  165,  218,  174,  175,   50,   49,   50,   22,   48,
103827  /*   700 */   174,  175,   22,   23,   23,  244,  222,  223,  224,  166,
103828  /*   710 */   167,  168,  120,  239,   23,   68,   69,   70,   71,   72,
103829  /*   720 */    73,   74,   75,   76,   77,   78,   79,   80,  150,   82,
103830  /*   730 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
103831  /*   740 */    19,  150,  173,  165,  181,  182,   24,   67,   26,  104,
103832  /*   750 */   181,  188,  174,  175,  150,   39,  165,  150,   52,  150,
103833  /*   760 */   150,  150,  150,  144,  145,  174,  175,  249,  250,  165,
103834  /*   770 */    49,   50,  165,   52,  165,  165,  165,  165,  174,  175,
103835  /*   780 */    29,  174,  175,  174,  175,  174,  175,  160,   22,   68,
103836  /*   790 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
103837  /*   800 */    79,   80,  150,   82,   83,   84,   85,   86,   87,   88,
103838  /*   810 */    89,   90,   91,   92,   19,  150,   94,  165,  150,  150,
103839  /*   820 */   160,  194,  150,  213,  160,   52,  174,  175,   23,   23,
103840  /*   830 */   165,   25,   22,  165,  165,  150,  150,  165,   52,  174,
103841  /*   840 */   175,   22,  174,  175,   49,   50,  174,  175,  190,  191,
103842  /*   850 */   165,  165,  240,   23,  194,   25,  187,  109,  194,  174,
103843  /*   860 */   175,  190,  191,   68,   69,   70,   71,   72,   73,   74,
103844  /*   870 */    75,   76,   77,   78,   79,   80,  150,   82,   83,   84,
103845  /*   880 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  150,
103846  /*   890 */    22,  165,  150,   23,  150,   25,  150,  166,   91,   92,
103847  /*   900 */   174,  175,   22,  217,  165,  150,  102,  165,  150,  165,
103848  /*   910 */   150,  165,  150,  174,  175,   19,  174,  175,   49,   50,
103849  /*   920 */   165,   86,   87,  165,   23,  165,   25,  165,   24,  174,
103850  /*   930 */   175,  187,  174,  175,  174,  175,  205,   68,   69,   70,
103851  /*   940 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
103852  /*   950 */   150,   82,   83,   84,   85,   86,   87,   88,   89,   90,
103853  /*   960 */    91,   92,   19,  150,  150,  165,  150,  150,  166,   23,
103854  /*   970 */   150,   25,  160,   20,  174,  175,    1,    2,  165,  165,
103855  /*   980 */   104,  165,  165,   43,  150,  165,  240,  150,   49,   50,
103856  /*   990 */   174,  175,   49,   50,   23,   23,   25,   25,   53,  165,
103857  /*  1000 */   187,  187,  165,   23,  187,   25,  194,  205,  174,  175,
103858  /*  1010 */    71,   72,   69,   70,   71,   72,   73,   74,   75,   76,
103859  /*  1020 */    77,   78,   79,   80,  150,   82,   83,   84,   85,   86,
103860  /*  1030 */    87,   88,   89,   90,   91,   92,   19,   98,  150,  165,
103861  /*  1040 */   150,  160,  150,   59,   25,   53,  104,   22,  174,  175,
103862  /*  1050 */   213,  138,    5,  165,    1,  165,  150,  165,  150,  150,
103863  /*  1060 */   240,  150,  174,  175,  174,  175,   49,   50,  118,  150,
103864  /*  1070 */    35,  165,   27,  165,  165,  194,  165,  108,  127,   76,
103865  /*  1080 */   174,  175,  174,  175,  165,  174,  175,   70,   71,   72,
103866  /*  1090 */    73,   74,   75,   76,   77,   78,   79,   80,  166,   82,
103867  /*  1100 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
103868  /*  1110 */    19,   20,  193,   22,  150,  150,  150,   26,   27,   76,
103869  /*  1120 */   150,   22,    1,  150,  119,  121,  217,   20,   37,  165,
103870  /*  1130 */   165,  165,   16,   19,   20,  165,   22,  205,  165,  119,
103871  /*  1140 */    26,   27,  108,  128,  150,  150,  150,   56,  150,   22,
103872  /*  1150 */   150,   37,  150,  127,  160,   23,  150,   66,  193,  165,
103873  /*  1160 */   165,  165,   16,  165,   23,  165,  150,  165,  174,  175,
103874  /*  1170 */    56,  165,  150,   65,  174,  175,   15,   86,   87,   88,
103875  /*  1180 */    66,  165,  140,  150,   93,   94,   95,  165,  194,   98,
103876  /*  1190 */   174,  175,   22,    3,  164,  193,  174,  175,  165,  150,
103877  /*  1200 */    86,   87,    4,  180,  150,  248,  251,   93,   94,   95,
103878  /*  1210 */   216,  180,   98,  251,  165,  221,  150,  149,    6,  165,
103879  /*  1220 */   129,  130,  131,  132,  133,  134,  193,  150,  174,  175,
103880  /*  1230 */   116,  165,   19,   20,  150,   22,  149,  151,  150,   26,
103881  /*  1240 */    27,  149,  165,  129,  130,  131,  132,  133,  134,  165,
103882  /*  1250 */    37,  174,  175,  165,  149,   19,   20,   13,   22,  150,
103883  /*  1260 */   150,  150,   26,   27,  146,  147,  151,  150,   25,   56,
103884  /*  1270 */   152,  159,  154,   37,  165,  165,  165,  193,  160,   66,
103885  /*  1280 */   116,  193,  165,  174,  175,  174,  175,  194,  199,  150,
103886  /*  1290 */   200,  126,   56,  124,  123,  150,  201,  122,  150,   86,
103887  /*  1300 */    87,  150,   66,  193,  165,  202,   93,   94,   95,  150,
103888  /*  1310 */   165,   98,  194,  165,  125,   22,  165,  150,  150,   26,
103889  /*  1320 */    27,  135,   86,   87,  165,  174,  175,  203,  226,   93,
103890  /*  1330 */    94,   95,  165,  165,   98,  150,  218,  150,  193,  157,
103891  /*  1340 */   118,  157,  129,  130,  131,  132,  133,  134,    5,  104,
103892  /*  1350 */   165,  211,  165,   10,   11,   12,   13,   14,  150,   66,
103893  /*  1360 */    17,  174,  175,  210,  246,  129,  130,  131,  132,  133,
103894  /*  1370 */   134,  150,  210,  165,   31,  121,   33,  150,  150,   86,
103895  /*  1380 */    87,  176,  174,  175,  150,   42,  165,   94,  211,  210,
103896  /*  1390 */   150,   98,  165,  165,  211,  174,  175,  150,   55,  165,
103897  /*  1400 */    57,  150,  174,  175,   61,  165,  150,   64,  174,  175,
103898  /*  1410 */   150,  150,  165,  150,  174,  175,  165,  104,  150,  184,
103899  /*  1420 */   150,  165,  129,  130,  131,  165,  165,  150,  165,  150,
103900  /*  1430 */   150,  176,  150,  165,   47,  165,  150,  150,  176,  103,
103901  /*  1440 */   150,   22,  165,  178,  165,  165,  179,  165,  105,  106,
103902  /*  1450 */   107,  165,  165,  229,  111,  165,   92,  176,  229,  116,
103903  /*  1460 */   184,  176,  179,  156,  176,  176,   18,  157,  156,  237,
103904  /*  1470 */    45,  157,  156,  135,  157,  157,  238,  156,   68,  157,
103905  /*  1480 */   189,  189,  139,  219,   22,  157,   18,  192,  192,  192,
103906  /*  1490 */   192,  189,  219,  199,  157,  242,   40,  157,  199,  242,
103907  /*  1500 */   153,  157,   38,  245,  196,  166,  232,  198,  177,  177,
103908  /*  1510 */   232,  227,  209,  178,  166,  182,  166,  148,  177,  177,
103909  /*  1520 */   209,  196,  177,  199,  209,  199,  166,  208,   92,  195,
103910  /*  1530 */   174,  174,  183,  252,  183,  183,  252,  191,  252,  235,
103911  /*  1540 */   186,  241,  241,  252,  186,  252,  252,  252,  252,  252,
103912  /*  1550 */   252,  252,  252,  252,  252,  252,  236,
103913 };
103914 #define YY_SHIFT_USE_DFLT (-74)
103915 #define YY_SHIFT_COUNT (418)
103916 #define YY_SHIFT_MIN   (-73)
103917 #define YY_SHIFT_MAX   (1468)
103918 static const short yy_shift_ofst[] = {
103919  /*     0 */   975, 1114, 1343, 1114, 1213, 1213,   90,   90,    0,  -19,
103920  /*    10 */  1213, 1213, 1213, 1213, 1213,  345,  445,  721, 1091, 1213,
103921  /*    20 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
103922  /*    30 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
103923  /*    40 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1236, 1213, 1213,
103924  /*    50 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
103925  /*    60 */  1213,  199,  445,  445,  835,  835,  365, 1164,   55,  647,
103926  /*    70 */   573,  499,  425,  351,  277,  203,  129,  795,  795,  795,
103927  /*    80 */   795,  795,  795,  795,  795,  795,  795,  795,  795,  795,
103928  /*    90 */   795,  795,  795,  795,  795,  869,  795,  943, 1017, 1017,
103929  /*   100 */   -69,  -45,  -45,  -45,  -45,  -45,   -1,   58,  138,  100,
103930  /*   110 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
103931  /*   120 */   445,  445,  445,  445,  445,  445,  537,  438,  445,  445,
103932  /*   130 */   445,  445,  445,  365,  807, 1436,  -74,  -74,  -74, 1293,
103933  /*   140 */    73,  434,  434,  311,  314,  290,  283,  286,  540,  467,
103934  /*   150 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
103935  /*   160 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
103936  /*   170 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
103937  /*   180 */   445,  445,   65,  722,  722,  722,  688,  266, 1164, 1164,
103938  /*   190 */  1164,  -74,  -74,  -74,  136,  168,  168,  234,  360,  360,
103939  /*   200 */   360,  430,  372,  435,  352,  278,  126,  -36,  -36,  -36,
103940  /*   210 */   -36,  421,  651,  -36,  -36,  592,  292,  212,  623,  158,
103941  /*   220 */   204,  204,  505,  158,  505,  144,  365,  154,  365,  154,
103942  /*   230 */   645,  154,  204,  154,  154,  535,  548,  548,  365,  387,
103943  /*   240 */   508,  233, 1464, 1222, 1222, 1456, 1456, 1222, 1462, 1410,
103944  /*   250 */  1165, 1468, 1468, 1468, 1468, 1222, 1165, 1462, 1410, 1410,
103945  /*   260 */  1222, 1448, 1338, 1425, 1222, 1222, 1448, 1222, 1448, 1222,
103946  /*   270 */  1448, 1419, 1313, 1313, 1313, 1387, 1364, 1364, 1419, 1313,
103947  /*   280 */  1336, 1313, 1387, 1313, 1313, 1254, 1245, 1254, 1245, 1254,
103948  /*   290 */  1245, 1222, 1222, 1186, 1189, 1175, 1169, 1171, 1165, 1164,
103949  /*   300 */  1243, 1244, 1244, 1212, 1212, 1212, 1212,  -74,  -74,  -74,
103950  /*   310 */   -74,  -74,  -74,  939,  104,  680,  571,  327,    1,  980,
103951  /*   320 */    26,  972,  971,  946,  901,  870,  830,  806,   54,   21,
103952  /*   330 */   -73,  510,  242, 1198, 1190, 1170, 1042, 1161, 1108, 1146,
103953  /*   340 */  1141, 1132, 1015, 1127, 1026, 1034, 1020, 1107, 1004, 1116,
103954  /*   350 */  1121, 1005, 1099,  951, 1043, 1003,  969, 1045, 1035,  950,
103955  /*   360 */  1053, 1047, 1025,  942,  913,  992, 1019,  945,  984,  940,
103956  /*   370 */   876,  904,  953,  896,  748,  804,  880,  786,  868,  819,
103957  /*   380 */   805,  810,  773,  751,  766,  706,  716,  691,  681,  568,
103958  /*   390 */   655,  638,  676,  516,  541,  594,  599,  567,  541,  534,
103959  /*   400 */   507,  527,  498,  523,  466,  382,  409,  384,  357,    6,
103960  /*   410 */   240,  224,  143,   62,   18,   71,   39,    9,    5,
103961 };
103962 #define YY_REDUCE_USE_DFLT (-142)
103963 #define YY_REDUCE_COUNT (312)
103964 #define YY_REDUCE_MIN   (-141)
103965 #define YY_REDUCE_MAX   (1369)
103966 static const short yy_reduce_ofst[] = {
103967  /*     0 */  -141,  994, 1118,  223,  157,  -53,   93,   89,   83,  375,
103968  /*    10 */   386,  381,  379,  308,  295,  325,  -47,   27, 1240, 1234,
103969  /*    20 */  1228, 1221, 1208, 1187, 1151, 1111, 1109, 1077, 1054, 1022,
103970  /*    30 */  1016, 1000,  911,  908,  906,  890,  888,  874,  834,  816,
103971  /*    40 */   800,  760,  758,  755,  742,  739,  726,  685,  672,  668,
103972  /*    50 */   665,  652,  611,  609,  607,  604,  591,  578,  526,  519,
103973  /*    60 */   453,  474,  454,  461,  443,  245,  442,  473,  484,  484,
103974  /*    70 */   484,  484,  484,  484,  484,  484,  484,  484,  484,  484,
103975  /*    80 */   484,  484,  484,  484,  484,  484,  484,  484,  484,  484,
103976  /*    90 */   484,  484,  484,  484,  484,  484,  484,  484,  484,  484,
103977  /*   100 */   484,  484,  484,  484,  484,  484,  484,  130,  484,  484,
103978  /*   110 */  1145,  909, 1110, 1088, 1084, 1033, 1002,  965,  820,  837,
103979  /*   120 */   746,  686,  612,  817,  610,  919,  221,  563,  814,  813,
103980  /*   130 */   744,  669,  470,  543,  484,  484,  484,  484,  484,  291,
103981  /*   140 */   569,  671,  658,  970, 1290, 1287, 1286, 1282,  518,  518,
103982  /*   150 */  1280, 1279, 1277, 1270, 1268, 1263, 1261, 1260, 1256, 1251,
103983  /*   160 */  1247, 1227, 1185, 1168, 1167, 1159, 1148, 1139, 1117, 1066,
103984  /*   170 */  1049, 1006,  998,  996,  995,  973,  970,  966,  964,  892,
103985  /*   180 */   762,  -52,  881,  932,  802,  731,  619,  812,  664,  660,
103986  /*   190 */   627,  392,  331,  124, 1358, 1357, 1356, 1354, 1352, 1351,
103987  /*   200 */  1349, 1319, 1334, 1346, 1334, 1334, 1334, 1334, 1334, 1334,
103988  /*   210 */  1334, 1320, 1304, 1334, 1334, 1319, 1360, 1325, 1369, 1326,
103989  /*   220 */  1315, 1311, 1301, 1324, 1300, 1335, 1350, 1345, 1348, 1342,
103990  /*   230 */  1333, 1341, 1303, 1332, 1331, 1284, 1278, 1274, 1339, 1309,
103991  /*   240 */  1308, 1347, 1258, 1344, 1340, 1257, 1253, 1337, 1273, 1302,
103992  /*   250 */  1299, 1298, 1297, 1296, 1295, 1328, 1294, 1264, 1292, 1291,
103993  /*   260 */  1322, 1321, 1238, 1232, 1318, 1317, 1316, 1314, 1312, 1310,
103994  /*   270 */  1307, 1283, 1289, 1288, 1285, 1276, 1229, 1224, 1267, 1281,
103995  /*   280 */  1265, 1262, 1235, 1255, 1205, 1183, 1179, 1177, 1162, 1140,
103996  /*   290 */  1153, 1184, 1182, 1102, 1124, 1103, 1095, 1090, 1089, 1093,
103997  /*   300 */  1112, 1115, 1086, 1105, 1092, 1087, 1068,  962,  955,  957,
103998  /*   310 */  1031, 1023, 1030,
103999 };
104000 static const YYACTIONTYPE yy_default[] = {
104001  /*     0 */   635,  870,  959,  959,  959,  870,  899,  899,  959,  759,
104002  /*    10 */   959,  959,  959,  959,  868,  959,  959,  933,  959,  959,
104003  /*    20 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
104004  /*    30 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
104005  /*    40 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
104006  /*    50 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
104007  /*    60 */   959,  959,  959,  959,  899,  899,  674,  763,  794,  959,
104008  /*    70 */   959,  959,  959,  959,  959,  959,  959,  932,  934,  809,
104009  /*    80 */   808,  802,  801,  912,  774,  799,  792,  785,  796,  871,
104010  /*    90 */   864,  865,  863,  867,  872,  959,  795,  831,  848,  830,
104011  /*   100 */   842,  847,  854,  846,  843,  833,  832,  666,  834,  835,
104012  /*   110 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
104013  /*   120 */   959,  959,  959,  959,  959,  959,  661,  728,  959,  959,
104014  /*   130 */   959,  959,  959,  959,  836,  837,  851,  850,  849,  959,
104015  /*   140 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
104016  /*   150 */   959,  939,  937,  959,  883,  959,  959,  959,  959,  959,
104017  /*   160 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
104018  /*   170 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
104019  /*   180 */   959,  641,  959,  759,  759,  759,  635,  959,  959,  959,
104020  /*   190 */   959,  951,  763,  753,  719,  959,  959,  959,  959,  959,
104021  /*   200 */   959,  959,  959,  959,  959,  959,  959,  804,  742,  922,
104022  /*   210 */   924,  959,  905,  740,  663,  761,  676,  751,  643,  798,
104023  /*   220 */   776,  776,  917,  798,  917,  700,  959,  788,  959,  788,
104024  /*   230 */   697,  788,  776,  788,  788,  866,  959,  959,  959,  760,
104025  /*   240 */   751,  959,  944,  767,  767,  936,  936,  767,  810,  732,
104026  /*   250 */   798,  739,  739,  739,  739,  767,  798,  810,  732,  732,
104027  /*   260 */   767,  658,  911,  909,  767,  767,  658,  767,  658,  767,
104028  /*   270 */   658,  876,  730,  730,  730,  715,  880,  880,  876,  730,
104029  /*   280 */   700,  730,  715,  730,  730,  780,  775,  780,  775,  780,
104030  /*   290 */   775,  767,  767,  959,  793,  781,  791,  789,  798,  959,
104031  /*   300 */   718,  651,  651,  640,  640,  640,  640,  956,  956,  951,
104032  /*   310 */   702,  702,  684,  959,  959,  959,  959,  959,  959,  959,
104033  /*   320 */   885,  959,  959,  959,  959,  959,  959,  959,  959,  959,
104034  /*   330 */   959,  959,  959,  959,  636,  946,  959,  959,  943,  959,
104035  /*   340 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
104036  /*   350 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  915,
104037  /*   360 */   959,  959,  959,  959,  959,  959,  908,  907,  959,  959,
104038  /*   370 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
104039  /*   380 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
104040  /*   390 */   959,  959,  959,  959,  790,  959,  782,  959,  869,  959,
104041  /*   400 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  745,
104042  /*   410 */   819,  959,  818,  822,  817,  668,  959,  649,  959,  632,
104043  /*   420 */   637,  955,  958,  957,  954,  953,  952,  947,  945,  942,
104044  /*   430 */   941,  940,  938,  935,  931,  889,  887,  894,  893,  892,
104045  /*   440 */   891,  890,  888,  886,  884,  805,  803,  800,  797,  930,
104046  /*   450 */   882,  741,  738,  737,  657,  948,  914,  923,  921,  811,
104047  /*   460 */   920,  919,  918,  916,  913,  900,  807,  806,  733,  874,
104048  /*   470 */   873,  660,  904,  903,  902,  906,  910,  901,  769,  659,
104049  /*   480 */   656,  665,  722,  721,  729,  727,  726,  725,  724,  723,
104050  /*   490 */   720,  667,  675,  686,  714,  699,  698,  879,  881,  878,
104051  /*   500 */   877,  707,  706,  712,  711,  710,  709,  708,  705,  704,
104052  /*   510 */   703,  696,  695,  701,  694,  717,  716,  713,  693,  736,
104053  /*   520 */   735,  734,  731,  692,  691,  690,  822,  689,  688,  828,
104054  /*   530 */   827,  815,  858,  756,  755,  754,  766,  765,  778,  777,
104055  /*   540 */   813,  812,  779,  764,  758,  757,  773,  772,  771,  770,
104056  /*   550 */   762,  752,  784,  787,  786,  783,  860,  768,  857,  929,
104057  /*   560 */   928,  927,  926,  925,  862,  861,  829,  826,  679,  680,
104058  /*   570 */   898,  896,  897,  895,  682,  681,  678,  677,  859,  747,
104059  /*   580 */   746,  855,  852,  844,  840,  856,  853,  845,  841,  839,
104060  /*   590 */   838,  824,  823,  821,  820,  816,  825,  670,  748,  744,
104061  /*   600 */   743,  814,  750,  749,  687,  685,  683,  664,  662,  655,
104062  /*   610 */   653,  652,  654,  650,  648,  647,  646,  645,  644,  673,
104063  /*   620 */   672,  671,  669,  668,  642,  639,  638,  634,  633,  631,
104064 };
104065
104066 /* The next table maps tokens into fallback tokens.  If a construct
104067 ** like the following:
104068 ** 
104069 **      %fallback ID X Y Z.
104070 **
104071 ** appears in the grammar, then ID becomes a fallback token for X, Y,
104072 ** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
104073 ** but it does not parse, the type of the token is changed to ID and
104074 ** the parse is retried before an error is thrown.
104075 */
104076 #ifdef YYFALLBACK
104077 static const YYCODETYPE yyFallback[] = {
104078     0,  /*          $ => nothing */
104079     0,  /*       SEMI => nothing */
104080    26,  /*    EXPLAIN => ID */
104081    26,  /*      QUERY => ID */
104082    26,  /*       PLAN => ID */
104083    26,  /*      BEGIN => ID */
104084     0,  /* TRANSACTION => nothing */
104085    26,  /*   DEFERRED => ID */
104086    26,  /*  IMMEDIATE => ID */
104087    26,  /*  EXCLUSIVE => ID */
104088     0,  /*     COMMIT => nothing */
104089    26,  /*        END => ID */
104090    26,  /*   ROLLBACK => ID */
104091    26,  /*  SAVEPOINT => ID */
104092    26,  /*    RELEASE => ID */
104093     0,  /*         TO => nothing */
104094     0,  /*      TABLE => nothing */
104095     0,  /*     CREATE => nothing */
104096    26,  /*         IF => ID */
104097     0,  /*        NOT => nothing */
104098     0,  /*     EXISTS => nothing */
104099    26,  /*       TEMP => ID */
104100     0,  /*         LP => nothing */
104101     0,  /*         RP => nothing */
104102     0,  /*         AS => nothing */
104103     0,  /*      COMMA => nothing */
104104     0,  /*         ID => nothing */
104105     0,  /*    INDEXED => nothing */
104106    26,  /*      ABORT => ID */
104107    26,  /*     ACTION => ID */
104108    26,  /*      AFTER => ID */
104109    26,  /*    ANALYZE => ID */
104110    26,  /*        ASC => ID */
104111    26,  /*     ATTACH => ID */
104112    26,  /*     BEFORE => ID */
104113    26,  /*         BY => ID */
104114    26,  /*    CASCADE => ID */
104115    26,  /*       CAST => ID */
104116    26,  /*   COLUMNKW => ID */
104117    26,  /*   CONFLICT => ID */
104118    26,  /*   DATABASE => ID */
104119    26,  /*       DESC => ID */
104120    26,  /*     DETACH => ID */
104121    26,  /*       EACH => ID */
104122    26,  /*       FAIL => ID */
104123    26,  /*        FOR => ID */
104124    26,  /*     IGNORE => ID */
104125    26,  /*  INITIALLY => ID */
104126    26,  /*    INSTEAD => ID */
104127    26,  /*    LIKE_KW => ID */
104128    26,  /*      MATCH => ID */
104129    26,  /*         NO => ID */
104130    26,  /*        KEY => ID */
104131    26,  /*         OF => ID */
104132    26,  /*     OFFSET => ID */
104133    26,  /*     PRAGMA => ID */
104134    26,  /*      RAISE => ID */
104135    26,  /*    REPLACE => ID */
104136    26,  /*   RESTRICT => ID */
104137    26,  /*        ROW => ID */
104138    26,  /*    TRIGGER => ID */
104139    26,  /*     VACUUM => ID */
104140    26,  /*       VIEW => ID */
104141    26,  /*    VIRTUAL => ID */
104142    26,  /*    REINDEX => ID */
104143    26,  /*     RENAME => ID */
104144    26,  /*   CTIME_KW => ID */
104145 };
104146 #endif /* YYFALLBACK */
104147
104148 /* The following structure represents a single element of the
104149 ** parser's stack.  Information stored includes:
104150 **
104151 **   +  The state number for the parser at this level of the stack.
104152 **
104153 **   +  The value of the token stored at this level of the stack.
104154 **      (In other words, the "major" token.)
104155 **
104156 **   +  The semantic value stored at this level of the stack.  This is
104157 **      the information used by the action routines in the grammar.
104158 **      It is sometimes called the "minor" token.
104159 */
104160 struct yyStackEntry {
104161   YYACTIONTYPE stateno;  /* The state-number */
104162   YYCODETYPE major;      /* The major token value.  This is the code
104163                          ** number for the token at this stack level */
104164   YYMINORTYPE minor;     /* The user-supplied minor token value.  This
104165                          ** is the value of the token  */
104166 };
104167 typedef struct yyStackEntry yyStackEntry;
104168
104169 /* The state of the parser is completely contained in an instance of
104170 ** the following structure */
104171 struct yyParser {
104172   int yyidx;                    /* Index of top element in stack */
104173 #ifdef YYTRACKMAXSTACKDEPTH
104174   int yyidxMax;                 /* Maximum value of yyidx */
104175 #endif
104176   int yyerrcnt;                 /* Shifts left before out of the error */
104177   sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
104178 #if YYSTACKDEPTH<=0
104179   int yystksz;                  /* Current side of the stack */
104180   yyStackEntry *yystack;        /* The parser's stack */
104181 #else
104182   yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
104183 #endif
104184 };
104185 typedef struct yyParser yyParser;
104186
104187 #ifndef NDEBUG
104188 static FILE *yyTraceFILE = 0;
104189 static char *yyTracePrompt = 0;
104190 #endif /* NDEBUG */
104191
104192 #ifndef NDEBUG
104193 /* 
104194 ** Turn parser tracing on by giving a stream to which to write the trace
104195 ** and a prompt to preface each trace message.  Tracing is turned off
104196 ** by making either argument NULL 
104197 **
104198 ** Inputs:
104199 ** <ul>
104200 ** <li> A FILE* to which trace output should be written.
104201 **      If NULL, then tracing is turned off.
104202 ** <li> A prefix string written at the beginning of every
104203 **      line of trace output.  If NULL, then tracing is
104204 **      turned off.
104205 ** </ul>
104206 **
104207 ** Outputs:
104208 ** None.
104209 */
104210 SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
104211   yyTraceFILE = TraceFILE;
104212   yyTracePrompt = zTracePrompt;
104213   if( yyTraceFILE==0 ) yyTracePrompt = 0;
104214   else if( yyTracePrompt==0 ) yyTraceFILE = 0;
104215 }
104216 #endif /* NDEBUG */
104217
104218 #ifndef NDEBUG
104219 /* For tracing shifts, the names of all terminals and nonterminals
104220 ** are required.  The following table supplies these names */
104221 static const char *const yyTokenName[] = { 
104222   "$",             "SEMI",          "EXPLAIN",       "QUERY",       
104223   "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",    
104224   "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",         
104225   "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",          
104226   "TABLE",         "CREATE",        "IF",            "NOT",         
104227   "EXISTS",        "TEMP",          "LP",            "RP",          
104228   "AS",            "COMMA",         "ID",            "INDEXED",     
104229   "ABORT",         "ACTION",        "AFTER",         "ANALYZE",     
104230   "ASC",           "ATTACH",        "BEFORE",        "BY",          
104231   "CASCADE",       "CAST",          "COLUMNKW",      "CONFLICT",    
104232   "DATABASE",      "DESC",          "DETACH",        "EACH",        
104233   "FAIL",          "FOR",           "IGNORE",        "INITIALLY",   
104234   "INSTEAD",       "LIKE_KW",       "MATCH",         "NO",          
104235   "KEY",           "OF",            "OFFSET",        "PRAGMA",      
104236   "RAISE",         "REPLACE",       "RESTRICT",      "ROW",         
104237   "TRIGGER",       "VACUUM",        "VIEW",          "VIRTUAL",     
104238   "REINDEX",       "RENAME",        "CTIME_KW",      "ANY",         
104239   "OR",            "AND",           "IS",            "BETWEEN",     
104240   "IN",            "ISNULL",        "NOTNULL",       "NE",          
104241   "EQ",            "GT",            "LE",            "LT",          
104242   "GE",            "ESCAPE",        "BITAND",        "BITOR",       
104243   "LSHIFT",        "RSHIFT",        "PLUS",          "MINUS",       
104244   "STAR",          "SLASH",         "REM",           "CONCAT",      
104245   "COLLATE",       "BITNOT",        "STRING",        "JOIN_KW",     
104246   "CONSTRAINT",    "DEFAULT",       "NULL",          "PRIMARY",     
104247   "UNIQUE",        "CHECK",         "REFERENCES",    "AUTOINCR",    
104248   "ON",            "INSERT",        "DELETE",        "UPDATE",      
104249   "SET",           "DEFERRABLE",    "FOREIGN",       "DROP",        
104250   "UNION",         "ALL",           "EXCEPT",        "INTERSECT",   
104251   "SELECT",        "DISTINCT",      "DOT",           "FROM",        
104252   "JOIN",          "USING",         "ORDER",         "GROUP",       
104253   "HAVING",        "LIMIT",         "WHERE",         "INTO",        
104254   "VALUES",        "INTEGER",       "FLOAT",         "BLOB",        
104255   "REGISTER",      "VARIABLE",      "CASE",          "WHEN",        
104256   "THEN",          "ELSE",          "INDEX",         "ALTER",       
104257   "ADD",           "error",         "input",         "cmdlist",     
104258   "ecmd",          "explain",       "cmdx",          "cmd",         
104259   "transtype",     "trans_opt",     "nm",            "savepoint_opt",
104260   "create_table",  "create_table_args",  "createkw",      "temp",        
104261   "ifnotexists",   "dbnm",          "columnlist",    "conslist_opt",
104262   "select",        "column",        "columnid",      "type",        
104263   "carglist",      "id",            "ids",           "typetoken",   
104264   "typename",      "signed",        "plus_num",      "minus_num",   
104265   "carg",          "ccons",         "term",          "expr",        
104266   "onconf",        "sortorder",     "autoinc",       "idxlist_opt", 
104267   "refargs",       "defer_subclause",  "refarg",        "refact",      
104268   "init_deferred_pred_opt",  "conslist",      "tcons",         "idxlist",     
104269   "defer_subclause_opt",  "orconf",        "resolvetype",   "raisetype",   
104270   "ifexists",      "fullname",      "oneselect",     "multiselect_op",
104271   "distinct",      "selcollist",    "from",          "where_opt",   
104272   "groupby_opt",   "having_opt",    "orderby_opt",   "limit_opt",   
104273   "sclp",          "as",            "seltablist",    "stl_prefix",  
104274   "joinop",        "indexed_opt",   "on_opt",        "using_opt",   
104275   "joinop2",       "inscollist",    "sortlist",      "sortitem",    
104276   "nexprlist",     "setlist",       "insert_cmd",    "inscollist_opt",
104277   "itemlist",      "exprlist",      "likeop",        "between_op",  
104278   "in_op",         "case_operand",  "case_exprlist",  "case_else",   
104279   "uniqueflag",    "collate",       "nmnum",         "plus_opt",    
104280   "number",        "trigger_decl",  "trigger_cmd_list",  "trigger_time",
104281   "trigger_event",  "foreach_clause",  "when_clause",   "trigger_cmd", 
104282   "trnm",          "tridxby",       "database_kw_opt",  "key_opt",     
104283   "add_column_fullname",  "kwcolumn_opt",  "create_vtab",   "vtabarglist", 
104284   "vtabarg",       "vtabargtoken",  "lp",            "anylist",     
104285 };
104286 #endif /* NDEBUG */
104287
104288 #ifndef NDEBUG
104289 /* For tracing reduce actions, the names of all rules are required.
104290 */
104291 static const char *const yyRuleName[] = {
104292  /*   0 */ "input ::= cmdlist",
104293  /*   1 */ "cmdlist ::= cmdlist ecmd",
104294  /*   2 */ "cmdlist ::= ecmd",
104295  /*   3 */ "ecmd ::= SEMI",
104296  /*   4 */ "ecmd ::= explain cmdx SEMI",
104297  /*   5 */ "explain ::=",
104298  /*   6 */ "explain ::= EXPLAIN",
104299  /*   7 */ "explain ::= EXPLAIN QUERY PLAN",
104300  /*   8 */ "cmdx ::= cmd",
104301  /*   9 */ "cmd ::= BEGIN transtype trans_opt",
104302  /*  10 */ "trans_opt ::=",
104303  /*  11 */ "trans_opt ::= TRANSACTION",
104304  /*  12 */ "trans_opt ::= TRANSACTION nm",
104305  /*  13 */ "transtype ::=",
104306  /*  14 */ "transtype ::= DEFERRED",
104307  /*  15 */ "transtype ::= IMMEDIATE",
104308  /*  16 */ "transtype ::= EXCLUSIVE",
104309  /*  17 */ "cmd ::= COMMIT trans_opt",
104310  /*  18 */ "cmd ::= END trans_opt",
104311  /*  19 */ "cmd ::= ROLLBACK trans_opt",
104312  /*  20 */ "savepoint_opt ::= SAVEPOINT",
104313  /*  21 */ "savepoint_opt ::=",
104314  /*  22 */ "cmd ::= SAVEPOINT nm",
104315  /*  23 */ "cmd ::= RELEASE savepoint_opt nm",
104316  /*  24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
104317  /*  25 */ "cmd ::= create_table create_table_args",
104318  /*  26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
104319  /*  27 */ "createkw ::= CREATE",
104320  /*  28 */ "ifnotexists ::=",
104321  /*  29 */ "ifnotexists ::= IF NOT EXISTS",
104322  /*  30 */ "temp ::= TEMP",
104323  /*  31 */ "temp ::=",
104324  /*  32 */ "create_table_args ::= LP columnlist conslist_opt RP",
104325  /*  33 */ "create_table_args ::= AS select",
104326  /*  34 */ "columnlist ::= columnlist COMMA column",
104327  /*  35 */ "columnlist ::= column",
104328  /*  36 */ "column ::= columnid type carglist",
104329  /*  37 */ "columnid ::= nm",
104330  /*  38 */ "id ::= ID",
104331  /*  39 */ "id ::= INDEXED",
104332  /*  40 */ "ids ::= ID|STRING",
104333  /*  41 */ "nm ::= id",
104334  /*  42 */ "nm ::= STRING",
104335  /*  43 */ "nm ::= JOIN_KW",
104336  /*  44 */ "type ::=",
104337  /*  45 */ "type ::= typetoken",
104338  /*  46 */ "typetoken ::= typename",
104339  /*  47 */ "typetoken ::= typename LP signed RP",
104340  /*  48 */ "typetoken ::= typename LP signed COMMA signed RP",
104341  /*  49 */ "typename ::= ids",
104342  /*  50 */ "typename ::= typename ids",
104343  /*  51 */ "signed ::= plus_num",
104344  /*  52 */ "signed ::= minus_num",
104345  /*  53 */ "carglist ::= carglist carg",
104346  /*  54 */ "carglist ::=",
104347  /*  55 */ "carg ::= CONSTRAINT nm ccons",
104348  /*  56 */ "carg ::= ccons",
104349  /*  57 */ "ccons ::= DEFAULT term",
104350  /*  58 */ "ccons ::= DEFAULT LP expr RP",
104351  /*  59 */ "ccons ::= DEFAULT PLUS term",
104352  /*  60 */ "ccons ::= DEFAULT MINUS term",
104353  /*  61 */ "ccons ::= DEFAULT id",
104354  /*  62 */ "ccons ::= NULL onconf",
104355  /*  63 */ "ccons ::= NOT NULL onconf",
104356  /*  64 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
104357  /*  65 */ "ccons ::= UNIQUE onconf",
104358  /*  66 */ "ccons ::= CHECK LP expr RP",
104359  /*  67 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
104360  /*  68 */ "ccons ::= defer_subclause",
104361  /*  69 */ "ccons ::= COLLATE ids",
104362  /*  70 */ "autoinc ::=",
104363  /*  71 */ "autoinc ::= AUTOINCR",
104364  /*  72 */ "refargs ::=",
104365  /*  73 */ "refargs ::= refargs refarg",
104366  /*  74 */ "refarg ::= MATCH nm",
104367  /*  75 */ "refarg ::= ON INSERT refact",
104368  /*  76 */ "refarg ::= ON DELETE refact",
104369  /*  77 */ "refarg ::= ON UPDATE refact",
104370  /*  78 */ "refact ::= SET NULL",
104371  /*  79 */ "refact ::= SET DEFAULT",
104372  /*  80 */ "refact ::= CASCADE",
104373  /*  81 */ "refact ::= RESTRICT",
104374  /*  82 */ "refact ::= NO ACTION",
104375  /*  83 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
104376  /*  84 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
104377  /*  85 */ "init_deferred_pred_opt ::=",
104378  /*  86 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
104379  /*  87 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
104380  /*  88 */ "conslist_opt ::=",
104381  /*  89 */ "conslist_opt ::= COMMA conslist",
104382  /*  90 */ "conslist ::= conslist COMMA tcons",
104383  /*  91 */ "conslist ::= conslist tcons",
104384  /*  92 */ "conslist ::= tcons",
104385  /*  93 */ "tcons ::= CONSTRAINT nm",
104386  /*  94 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
104387  /*  95 */ "tcons ::= UNIQUE LP idxlist RP onconf",
104388  /*  96 */ "tcons ::= CHECK LP expr RP onconf",
104389  /*  97 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
104390  /*  98 */ "defer_subclause_opt ::=",
104391  /*  99 */ "defer_subclause_opt ::= defer_subclause",
104392  /* 100 */ "onconf ::=",
104393  /* 101 */ "onconf ::= ON CONFLICT resolvetype",
104394  /* 102 */ "orconf ::=",
104395  /* 103 */ "orconf ::= OR resolvetype",
104396  /* 104 */ "resolvetype ::= raisetype",
104397  /* 105 */ "resolvetype ::= IGNORE",
104398  /* 106 */ "resolvetype ::= REPLACE",
104399  /* 107 */ "cmd ::= DROP TABLE ifexists fullname",
104400  /* 108 */ "ifexists ::= IF EXISTS",
104401  /* 109 */ "ifexists ::=",
104402  /* 110 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
104403  /* 111 */ "cmd ::= DROP VIEW ifexists fullname",
104404  /* 112 */ "cmd ::= select",
104405  /* 113 */ "select ::= oneselect",
104406  /* 114 */ "select ::= select multiselect_op oneselect",
104407  /* 115 */ "multiselect_op ::= UNION",
104408  /* 116 */ "multiselect_op ::= UNION ALL",
104409  /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
104410  /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
104411  /* 119 */ "distinct ::= DISTINCT",
104412  /* 120 */ "distinct ::= ALL",
104413  /* 121 */ "distinct ::=",
104414  /* 122 */ "sclp ::= selcollist COMMA",
104415  /* 123 */ "sclp ::=",
104416  /* 124 */ "selcollist ::= sclp expr as",
104417  /* 125 */ "selcollist ::= sclp STAR",
104418  /* 126 */ "selcollist ::= sclp nm DOT STAR",
104419  /* 127 */ "as ::= AS nm",
104420  /* 128 */ "as ::= ids",
104421  /* 129 */ "as ::=",
104422  /* 130 */ "from ::=",
104423  /* 131 */ "from ::= FROM seltablist",
104424  /* 132 */ "stl_prefix ::= seltablist joinop",
104425  /* 133 */ "stl_prefix ::=",
104426  /* 134 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
104427  /* 135 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
104428  /* 136 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
104429  /* 137 */ "dbnm ::=",
104430  /* 138 */ "dbnm ::= DOT nm",
104431  /* 139 */ "fullname ::= nm dbnm",
104432  /* 140 */ "joinop ::= COMMA|JOIN",
104433  /* 141 */ "joinop ::= JOIN_KW JOIN",
104434  /* 142 */ "joinop ::= JOIN_KW nm JOIN",
104435  /* 143 */ "joinop ::= JOIN_KW nm nm JOIN",
104436  /* 144 */ "on_opt ::= ON expr",
104437  /* 145 */ "on_opt ::=",
104438  /* 146 */ "indexed_opt ::=",
104439  /* 147 */ "indexed_opt ::= INDEXED BY nm",
104440  /* 148 */ "indexed_opt ::= NOT INDEXED",
104441  /* 149 */ "using_opt ::= USING LP inscollist RP",
104442  /* 150 */ "using_opt ::=",
104443  /* 151 */ "orderby_opt ::=",
104444  /* 152 */ "orderby_opt ::= ORDER BY sortlist",
104445  /* 153 */ "sortlist ::= sortlist COMMA sortitem sortorder",
104446  /* 154 */ "sortlist ::= sortitem sortorder",
104447  /* 155 */ "sortitem ::= expr",
104448  /* 156 */ "sortorder ::= ASC",
104449  /* 157 */ "sortorder ::= DESC",
104450  /* 158 */ "sortorder ::=",
104451  /* 159 */ "groupby_opt ::=",
104452  /* 160 */ "groupby_opt ::= GROUP BY nexprlist",
104453  /* 161 */ "having_opt ::=",
104454  /* 162 */ "having_opt ::= HAVING expr",
104455  /* 163 */ "limit_opt ::=",
104456  /* 164 */ "limit_opt ::= LIMIT expr",
104457  /* 165 */ "limit_opt ::= LIMIT expr OFFSET expr",
104458  /* 166 */ "limit_opt ::= LIMIT expr COMMA expr",
104459  /* 167 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
104460  /* 168 */ "where_opt ::=",
104461  /* 169 */ "where_opt ::= WHERE expr",
104462  /* 170 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
104463  /* 171 */ "setlist ::= setlist COMMA nm EQ expr",
104464  /* 172 */ "setlist ::= nm EQ expr",
104465  /* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP",
104466  /* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
104467  /* 175 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
104468  /* 176 */ "insert_cmd ::= INSERT orconf",
104469  /* 177 */ "insert_cmd ::= REPLACE",
104470  /* 178 */ "itemlist ::= itemlist COMMA expr",
104471  /* 179 */ "itemlist ::= expr",
104472  /* 180 */ "inscollist_opt ::=",
104473  /* 181 */ "inscollist_opt ::= LP inscollist RP",
104474  /* 182 */ "inscollist ::= inscollist COMMA nm",
104475  /* 183 */ "inscollist ::= nm",
104476  /* 184 */ "expr ::= term",
104477  /* 185 */ "expr ::= LP expr RP",
104478  /* 186 */ "term ::= NULL",
104479  /* 187 */ "expr ::= id",
104480  /* 188 */ "expr ::= JOIN_KW",
104481  /* 189 */ "expr ::= nm DOT nm",
104482  /* 190 */ "expr ::= nm DOT nm DOT nm",
104483  /* 191 */ "term ::= INTEGER|FLOAT|BLOB",
104484  /* 192 */ "term ::= STRING",
104485  /* 193 */ "expr ::= REGISTER",
104486  /* 194 */ "expr ::= VARIABLE",
104487  /* 195 */ "expr ::= expr COLLATE ids",
104488  /* 196 */ "expr ::= CAST LP expr AS typetoken RP",
104489  /* 197 */ "expr ::= ID LP distinct exprlist RP",
104490  /* 198 */ "expr ::= ID LP STAR RP",
104491  /* 199 */ "term ::= CTIME_KW",
104492  /* 200 */ "expr ::= expr AND expr",
104493  /* 201 */ "expr ::= expr OR expr",
104494  /* 202 */ "expr ::= expr LT|GT|GE|LE expr",
104495  /* 203 */ "expr ::= expr EQ|NE expr",
104496  /* 204 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
104497  /* 205 */ "expr ::= expr PLUS|MINUS expr",
104498  /* 206 */ "expr ::= expr STAR|SLASH|REM expr",
104499  /* 207 */ "expr ::= expr CONCAT expr",
104500  /* 208 */ "likeop ::= LIKE_KW",
104501  /* 209 */ "likeop ::= NOT LIKE_KW",
104502  /* 210 */ "likeop ::= MATCH",
104503  /* 211 */ "likeop ::= NOT MATCH",
104504  /* 212 */ "expr ::= expr likeop expr",
104505  /* 213 */ "expr ::= expr likeop expr ESCAPE expr",
104506  /* 214 */ "expr ::= expr ISNULL|NOTNULL",
104507  /* 215 */ "expr ::= expr NOT NULL",
104508  /* 216 */ "expr ::= expr IS expr",
104509  /* 217 */ "expr ::= expr IS NOT expr",
104510  /* 218 */ "expr ::= NOT expr",
104511  /* 219 */ "expr ::= BITNOT expr",
104512  /* 220 */ "expr ::= MINUS expr",
104513  /* 221 */ "expr ::= PLUS expr",
104514  /* 222 */ "between_op ::= BETWEEN",
104515  /* 223 */ "between_op ::= NOT BETWEEN",
104516  /* 224 */ "expr ::= expr between_op expr AND expr",
104517  /* 225 */ "in_op ::= IN",
104518  /* 226 */ "in_op ::= NOT IN",
104519  /* 227 */ "expr ::= expr in_op LP exprlist RP",
104520  /* 228 */ "expr ::= LP select RP",
104521  /* 229 */ "expr ::= expr in_op LP select RP",
104522  /* 230 */ "expr ::= expr in_op nm dbnm",
104523  /* 231 */ "expr ::= EXISTS LP select RP",
104524  /* 232 */ "expr ::= CASE case_operand case_exprlist case_else END",
104525  /* 233 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
104526  /* 234 */ "case_exprlist ::= WHEN expr THEN expr",
104527  /* 235 */ "case_else ::= ELSE expr",
104528  /* 236 */ "case_else ::=",
104529  /* 237 */ "case_operand ::= expr",
104530  /* 238 */ "case_operand ::=",
104531  /* 239 */ "exprlist ::= nexprlist",
104532  /* 240 */ "exprlist ::=",
104533  /* 241 */ "nexprlist ::= nexprlist COMMA expr",
104534  /* 242 */ "nexprlist ::= expr",
104535  /* 243 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
104536  /* 244 */ "uniqueflag ::= UNIQUE",
104537  /* 245 */ "uniqueflag ::=",
104538  /* 246 */ "idxlist_opt ::=",
104539  /* 247 */ "idxlist_opt ::= LP idxlist RP",
104540  /* 248 */ "idxlist ::= idxlist COMMA nm collate sortorder",
104541  /* 249 */ "idxlist ::= nm collate sortorder",
104542  /* 250 */ "collate ::=",
104543  /* 251 */ "collate ::= COLLATE ids",
104544  /* 252 */ "cmd ::= DROP INDEX ifexists fullname",
104545  /* 253 */ "cmd ::= VACUUM",
104546  /* 254 */ "cmd ::= VACUUM nm",
104547  /* 255 */ "cmd ::= PRAGMA nm dbnm",
104548  /* 256 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
104549  /* 257 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
104550  /* 258 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
104551  /* 259 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
104552  /* 260 */ "nmnum ::= plus_num",
104553  /* 261 */ "nmnum ::= nm",
104554  /* 262 */ "nmnum ::= ON",
104555  /* 263 */ "nmnum ::= DELETE",
104556  /* 264 */ "nmnum ::= DEFAULT",
104557  /* 265 */ "plus_num ::= plus_opt number",
104558  /* 266 */ "minus_num ::= MINUS number",
104559  /* 267 */ "number ::= INTEGER|FLOAT",
104560  /* 268 */ "plus_opt ::= PLUS",
104561  /* 269 */ "plus_opt ::=",
104562  /* 270 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
104563  /* 271 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
104564  /* 272 */ "trigger_time ::= BEFORE",
104565  /* 273 */ "trigger_time ::= AFTER",
104566  /* 274 */ "trigger_time ::= INSTEAD OF",
104567  /* 275 */ "trigger_time ::=",
104568  /* 276 */ "trigger_event ::= DELETE|INSERT",
104569  /* 277 */ "trigger_event ::= UPDATE",
104570  /* 278 */ "trigger_event ::= UPDATE OF inscollist",
104571  /* 279 */ "foreach_clause ::=",
104572  /* 280 */ "foreach_clause ::= FOR EACH ROW",
104573  /* 281 */ "when_clause ::=",
104574  /* 282 */ "when_clause ::= WHEN expr",
104575  /* 283 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
104576  /* 284 */ "trigger_cmd_list ::= trigger_cmd SEMI",
104577  /* 285 */ "trnm ::= nm",
104578  /* 286 */ "trnm ::= nm DOT nm",
104579  /* 287 */ "tridxby ::=",
104580  /* 288 */ "tridxby ::= INDEXED BY nm",
104581  /* 289 */ "tridxby ::= NOT INDEXED",
104582  /* 290 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
104583  /* 291 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP",
104584  /* 292 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
104585  /* 293 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
104586  /* 294 */ "trigger_cmd ::= select",
104587  /* 295 */ "expr ::= RAISE LP IGNORE RP",
104588  /* 296 */ "expr ::= RAISE LP raisetype COMMA nm RP",
104589  /* 297 */ "raisetype ::= ROLLBACK",
104590  /* 298 */ "raisetype ::= ABORT",
104591  /* 299 */ "raisetype ::= FAIL",
104592  /* 300 */ "cmd ::= DROP TRIGGER ifexists fullname",
104593  /* 301 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
104594  /* 302 */ "cmd ::= DETACH database_kw_opt expr",
104595  /* 303 */ "key_opt ::=",
104596  /* 304 */ "key_opt ::= KEY expr",
104597  /* 305 */ "database_kw_opt ::= DATABASE",
104598  /* 306 */ "database_kw_opt ::=",
104599  /* 307 */ "cmd ::= REINDEX",
104600  /* 308 */ "cmd ::= REINDEX nm dbnm",
104601  /* 309 */ "cmd ::= ANALYZE",
104602  /* 310 */ "cmd ::= ANALYZE nm dbnm",
104603  /* 311 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
104604  /* 312 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
104605  /* 313 */ "add_column_fullname ::= fullname",
104606  /* 314 */ "kwcolumn_opt ::=",
104607  /* 315 */ "kwcolumn_opt ::= COLUMNKW",
104608  /* 316 */ "cmd ::= create_vtab",
104609  /* 317 */ "cmd ::= create_vtab LP vtabarglist RP",
104610  /* 318 */ "create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm",
104611  /* 319 */ "vtabarglist ::= vtabarg",
104612  /* 320 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
104613  /* 321 */ "vtabarg ::=",
104614  /* 322 */ "vtabarg ::= vtabarg vtabargtoken",
104615  /* 323 */ "vtabargtoken ::= ANY",
104616  /* 324 */ "vtabargtoken ::= lp anylist RP",
104617  /* 325 */ "lp ::= LP",
104618  /* 326 */ "anylist ::=",
104619  /* 327 */ "anylist ::= anylist LP anylist RP",
104620  /* 328 */ "anylist ::= anylist ANY",
104621 };
104622 #endif /* NDEBUG */
104623
104624
104625 #if YYSTACKDEPTH<=0
104626 /*
104627 ** Try to increase the size of the parser stack.
104628 */
104629 static void yyGrowStack(yyParser *p){
104630   int newSize;
104631   yyStackEntry *pNew;
104632
104633   newSize = p->yystksz*2 + 100;
104634   pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
104635   if( pNew ){
104636     p->yystack = pNew;
104637     p->yystksz = newSize;
104638 #ifndef NDEBUG
104639     if( yyTraceFILE ){
104640       fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
104641               yyTracePrompt, p->yystksz);
104642     }
104643 #endif
104644   }
104645 }
104646 #endif
104647
104648 /* 
104649 ** This function allocates a new parser.
104650 ** The only argument is a pointer to a function which works like
104651 ** malloc.
104652 **
104653 ** Inputs:
104654 ** A pointer to the function used to allocate memory.
104655 **
104656 ** Outputs:
104657 ** A pointer to a parser.  This pointer is used in subsequent calls
104658 ** to sqlite3Parser and sqlite3ParserFree.
104659 */
104660 SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
104661   yyParser *pParser;
104662   pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
104663   if( pParser ){
104664     pParser->yyidx = -1;
104665 #ifdef YYTRACKMAXSTACKDEPTH
104666     pParser->yyidxMax = 0;
104667 #endif
104668 #if YYSTACKDEPTH<=0
104669     pParser->yystack = NULL;
104670     pParser->yystksz = 0;
104671     yyGrowStack(pParser);
104672 #endif
104673   }
104674   return pParser;
104675 }
104676
104677 /* The following function deletes the value associated with a
104678 ** symbol.  The symbol can be either a terminal or nonterminal.
104679 ** "yymajor" is the symbol code, and "yypminor" is a pointer to
104680 ** the value.
104681 */
104682 static void yy_destructor(
104683   yyParser *yypParser,    /* The parser */
104684   YYCODETYPE yymajor,     /* Type code for object to destroy */
104685   YYMINORTYPE *yypminor   /* The object to be destroyed */
104686 ){
104687   sqlite3ParserARG_FETCH;
104688   switch( yymajor ){
104689     /* Here is inserted the actions which take place when a
104690     ** terminal or non-terminal is destroyed.  This can happen
104691     ** when the symbol is popped from the stack during a
104692     ** reduce or during error processing or when a parser is 
104693     ** being destroyed before it is finished parsing.
104694     **
104695     ** Note: during a reduce, the only symbols destroyed are those
104696     ** which appear on the RHS of the rule, but which are not used
104697     ** inside the C code.
104698     */
104699     case 160: /* select */
104700     case 194: /* oneselect */
104701 {
104702 sqlite3SelectDelete(pParse->db, (yypminor->yy387));
104703 }
104704       break;
104705     case 174: /* term */
104706     case 175: /* expr */
104707 {
104708 sqlite3ExprDelete(pParse->db, (yypminor->yy118).pExpr);
104709 }
104710       break;
104711     case 179: /* idxlist_opt */
104712     case 187: /* idxlist */
104713     case 197: /* selcollist */
104714     case 200: /* groupby_opt */
104715     case 202: /* orderby_opt */
104716     case 204: /* sclp */
104717     case 214: /* sortlist */
104718     case 216: /* nexprlist */
104719     case 217: /* setlist */
104720     case 220: /* itemlist */
104721     case 221: /* exprlist */
104722     case 226: /* case_exprlist */
104723 {
104724 sqlite3ExprListDelete(pParse->db, (yypminor->yy322));
104725 }
104726       break;
104727     case 193: /* fullname */
104728     case 198: /* from */
104729     case 206: /* seltablist */
104730     case 207: /* stl_prefix */
104731 {
104732 sqlite3SrcListDelete(pParse->db, (yypminor->yy259));
104733 }
104734       break;
104735     case 199: /* where_opt */
104736     case 201: /* having_opt */
104737     case 210: /* on_opt */
104738     case 215: /* sortitem */
104739     case 225: /* case_operand */
104740     case 227: /* case_else */
104741     case 238: /* when_clause */
104742     case 243: /* key_opt */
104743 {
104744 sqlite3ExprDelete(pParse->db, (yypminor->yy314));
104745 }
104746       break;
104747     case 211: /* using_opt */
104748     case 213: /* inscollist */
104749     case 219: /* inscollist_opt */
104750 {
104751 sqlite3IdListDelete(pParse->db, (yypminor->yy384));
104752 }
104753       break;
104754     case 234: /* trigger_cmd_list */
104755     case 239: /* trigger_cmd */
104756 {
104757 sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy203));
104758 }
104759       break;
104760     case 236: /* trigger_event */
104761 {
104762 sqlite3IdListDelete(pParse->db, (yypminor->yy90).b);
104763 }
104764       break;
104765     default:  break;   /* If no destructor action specified: do nothing */
104766   }
104767 }
104768
104769 /*
104770 ** Pop the parser's stack once.
104771 **
104772 ** If there is a destructor routine associated with the token which
104773 ** is popped from the stack, then call it.
104774 **
104775 ** Return the major token number for the symbol popped.
104776 */
104777 static int yy_pop_parser_stack(yyParser *pParser){
104778   YYCODETYPE yymajor;
104779   yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
104780
104781   /* There is no mechanism by which the parser stack can be popped below
104782   ** empty in SQLite.  */
104783   if( NEVER(pParser->yyidx<0) ) return 0;
104784 #ifndef NDEBUG
104785   if( yyTraceFILE && pParser->yyidx>=0 ){
104786     fprintf(yyTraceFILE,"%sPopping %s\n",
104787       yyTracePrompt,
104788       yyTokenName[yytos->major]);
104789   }
104790 #endif
104791   yymajor = yytos->major;
104792   yy_destructor(pParser, yymajor, &yytos->minor);
104793   pParser->yyidx--;
104794   return yymajor;
104795 }
104796
104797 /* 
104798 ** Deallocate and destroy a parser.  Destructors are all called for
104799 ** all stack elements before shutting the parser down.
104800 **
104801 ** Inputs:
104802 ** <ul>
104803 ** <li>  A pointer to the parser.  This should be a pointer
104804 **       obtained from sqlite3ParserAlloc.
104805 ** <li>  A pointer to a function used to reclaim memory obtained
104806 **       from malloc.
104807 ** </ul>
104808 */
104809 SQLITE_PRIVATE void sqlite3ParserFree(
104810   void *p,                    /* The parser to be deleted */
104811   void (*freeProc)(void*)     /* Function used to reclaim memory */
104812 ){
104813   yyParser *pParser = (yyParser*)p;
104814   /* In SQLite, we never try to destroy a parser that was not successfully
104815   ** created in the first place. */
104816   if( NEVER(pParser==0) ) return;
104817   while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
104818 #if YYSTACKDEPTH<=0
104819   free(pParser->yystack);
104820 #endif
104821   (*freeProc)((void*)pParser);
104822 }
104823
104824 /*
104825 ** Return the peak depth of the stack for a parser.
104826 */
104827 #ifdef YYTRACKMAXSTACKDEPTH
104828 SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
104829   yyParser *pParser = (yyParser*)p;
104830   return pParser->yyidxMax;
104831 }
104832 #endif
104833
104834 /*
104835 ** Find the appropriate action for a parser given the terminal
104836 ** look-ahead token iLookAhead.
104837 **
104838 ** If the look-ahead token is YYNOCODE, then check to see if the action is
104839 ** independent of the look-ahead.  If it is, return the action, otherwise
104840 ** return YY_NO_ACTION.
104841 */
104842 static int yy_find_shift_action(
104843   yyParser *pParser,        /* The parser */
104844   YYCODETYPE iLookAhead     /* The look-ahead token */
104845 ){
104846   int i;
104847   int stateno = pParser->yystack[pParser->yyidx].stateno;
104848  
104849   if( stateno>YY_SHIFT_COUNT
104850    || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
104851     return yy_default[stateno];
104852   }
104853   assert( iLookAhead!=YYNOCODE );
104854   i += iLookAhead;
104855   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
104856     if( iLookAhead>0 ){
104857 #ifdef YYFALLBACK
104858       YYCODETYPE iFallback;            /* Fallback token */
104859       if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
104860              && (iFallback = yyFallback[iLookAhead])!=0 ){
104861 #ifndef NDEBUG
104862         if( yyTraceFILE ){
104863           fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
104864              yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
104865         }
104866 #endif
104867         return yy_find_shift_action(pParser, iFallback);
104868       }
104869 #endif
104870 #ifdef YYWILDCARD
104871       {
104872         int j = i - iLookAhead + YYWILDCARD;
104873         if( 
104874 #if YY_SHIFT_MIN+YYWILDCARD<0
104875           j>=0 &&
104876 #endif
104877 #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
104878           j<YY_ACTTAB_COUNT &&
104879 #endif
104880           yy_lookahead[j]==YYWILDCARD
104881         ){
104882 #ifndef NDEBUG
104883           if( yyTraceFILE ){
104884             fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
104885                yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
104886           }
104887 #endif /* NDEBUG */
104888           return yy_action[j];
104889         }
104890       }
104891 #endif /* YYWILDCARD */
104892     }
104893     return yy_default[stateno];
104894   }else{
104895     return yy_action[i];
104896   }
104897 }
104898
104899 /*
104900 ** Find the appropriate action for a parser given the non-terminal
104901 ** look-ahead token iLookAhead.
104902 **
104903 ** If the look-ahead token is YYNOCODE, then check to see if the action is
104904 ** independent of the look-ahead.  If it is, return the action, otherwise
104905 ** return YY_NO_ACTION.
104906 */
104907 static int yy_find_reduce_action(
104908   int stateno,              /* Current state number */
104909   YYCODETYPE iLookAhead     /* The look-ahead token */
104910 ){
104911   int i;
104912 #ifdef YYERRORSYMBOL
104913   if( stateno>YY_REDUCE_COUNT ){
104914     return yy_default[stateno];
104915   }
104916 #else
104917   assert( stateno<=YY_REDUCE_COUNT );
104918 #endif
104919   i = yy_reduce_ofst[stateno];
104920   assert( i!=YY_REDUCE_USE_DFLT );
104921   assert( iLookAhead!=YYNOCODE );
104922   i += iLookAhead;
104923 #ifdef YYERRORSYMBOL
104924   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
104925     return yy_default[stateno];
104926   }
104927 #else
104928   assert( i>=0 && i<YY_ACTTAB_COUNT );
104929   assert( yy_lookahead[i]==iLookAhead );
104930 #endif
104931   return yy_action[i];
104932 }
104933
104934 /*
104935 ** The following routine is called if the stack overflows.
104936 */
104937 static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
104938    sqlite3ParserARG_FETCH;
104939    yypParser->yyidx--;
104940 #ifndef NDEBUG
104941    if( yyTraceFILE ){
104942      fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
104943    }
104944 #endif
104945    while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
104946    /* Here code is inserted which will execute if the parser
104947    ** stack every overflows */
104948
104949   UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
104950   sqlite3ErrorMsg(pParse, "parser stack overflow");
104951   pParse->parseError = 1;
104952    sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
104953 }
104954
104955 /*
104956 ** Perform a shift action.
104957 */
104958 static void yy_shift(
104959   yyParser *yypParser,          /* The parser to be shifted */
104960   int yyNewState,               /* The new state to shift in */
104961   int yyMajor,                  /* The major token to shift in */
104962   YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */
104963 ){
104964   yyStackEntry *yytos;
104965   yypParser->yyidx++;
104966 #ifdef YYTRACKMAXSTACKDEPTH
104967   if( yypParser->yyidx>yypParser->yyidxMax ){
104968     yypParser->yyidxMax = yypParser->yyidx;
104969   }
104970 #endif
104971 #if YYSTACKDEPTH>0 
104972   if( yypParser->yyidx>=YYSTACKDEPTH ){
104973     yyStackOverflow(yypParser, yypMinor);
104974     return;
104975   }
104976 #else
104977   if( yypParser->yyidx>=yypParser->yystksz ){
104978     yyGrowStack(yypParser);
104979     if( yypParser->yyidx>=yypParser->yystksz ){
104980       yyStackOverflow(yypParser, yypMinor);
104981       return;
104982     }
104983   }
104984 #endif
104985   yytos = &yypParser->yystack[yypParser->yyidx];
104986   yytos->stateno = (YYACTIONTYPE)yyNewState;
104987   yytos->major = (YYCODETYPE)yyMajor;
104988   yytos->minor = *yypMinor;
104989 #ifndef NDEBUG
104990   if( yyTraceFILE && yypParser->yyidx>0 ){
104991     int i;
104992     fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
104993     fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
104994     for(i=1; i<=yypParser->yyidx; i++)
104995       fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
104996     fprintf(yyTraceFILE,"\n");
104997   }
104998 #endif
104999 }
105000
105001 /* The following table contains information about every rule that
105002 ** is used during the reduce.
105003 */
105004 static const struct {
105005   YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
105006   unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
105007 } yyRuleInfo[] = {
105008   { 142, 1 },
105009   { 143, 2 },
105010   { 143, 1 },
105011   { 144, 1 },
105012   { 144, 3 },
105013   { 145, 0 },
105014   { 145, 1 },
105015   { 145, 3 },
105016   { 146, 1 },
105017   { 147, 3 },
105018   { 149, 0 },
105019   { 149, 1 },
105020   { 149, 2 },
105021   { 148, 0 },
105022   { 148, 1 },
105023   { 148, 1 },
105024   { 148, 1 },
105025   { 147, 2 },
105026   { 147, 2 },
105027   { 147, 2 },
105028   { 151, 1 },
105029   { 151, 0 },
105030   { 147, 2 },
105031   { 147, 3 },
105032   { 147, 5 },
105033   { 147, 2 },
105034   { 152, 6 },
105035   { 154, 1 },
105036   { 156, 0 },
105037   { 156, 3 },
105038   { 155, 1 },
105039   { 155, 0 },
105040   { 153, 4 },
105041   { 153, 2 },
105042   { 158, 3 },
105043   { 158, 1 },
105044   { 161, 3 },
105045   { 162, 1 },
105046   { 165, 1 },
105047   { 165, 1 },
105048   { 166, 1 },
105049   { 150, 1 },
105050   { 150, 1 },
105051   { 150, 1 },
105052   { 163, 0 },
105053   { 163, 1 },
105054   { 167, 1 },
105055   { 167, 4 },
105056   { 167, 6 },
105057   { 168, 1 },
105058   { 168, 2 },
105059   { 169, 1 },
105060   { 169, 1 },
105061   { 164, 2 },
105062   { 164, 0 },
105063   { 172, 3 },
105064   { 172, 1 },
105065   { 173, 2 },
105066   { 173, 4 },
105067   { 173, 3 },
105068   { 173, 3 },
105069   { 173, 2 },
105070   { 173, 2 },
105071   { 173, 3 },
105072   { 173, 5 },
105073   { 173, 2 },
105074   { 173, 4 },
105075   { 173, 4 },
105076   { 173, 1 },
105077   { 173, 2 },
105078   { 178, 0 },
105079   { 178, 1 },
105080   { 180, 0 },
105081   { 180, 2 },
105082   { 182, 2 },
105083   { 182, 3 },
105084   { 182, 3 },
105085   { 182, 3 },
105086   { 183, 2 },
105087   { 183, 2 },
105088   { 183, 1 },
105089   { 183, 1 },
105090   { 183, 2 },
105091   { 181, 3 },
105092   { 181, 2 },
105093   { 184, 0 },
105094   { 184, 2 },
105095   { 184, 2 },
105096   { 159, 0 },
105097   { 159, 2 },
105098   { 185, 3 },
105099   { 185, 2 },
105100   { 185, 1 },
105101   { 186, 2 },
105102   { 186, 7 },
105103   { 186, 5 },
105104   { 186, 5 },
105105   { 186, 10 },
105106   { 188, 0 },
105107   { 188, 1 },
105108   { 176, 0 },
105109   { 176, 3 },
105110   { 189, 0 },
105111   { 189, 2 },
105112   { 190, 1 },
105113   { 190, 1 },
105114   { 190, 1 },
105115   { 147, 4 },
105116   { 192, 2 },
105117   { 192, 0 },
105118   { 147, 8 },
105119   { 147, 4 },
105120   { 147, 1 },
105121   { 160, 1 },
105122   { 160, 3 },
105123   { 195, 1 },
105124   { 195, 2 },
105125   { 195, 1 },
105126   { 194, 9 },
105127   { 196, 1 },
105128   { 196, 1 },
105129   { 196, 0 },
105130   { 204, 2 },
105131   { 204, 0 },
105132   { 197, 3 },
105133   { 197, 2 },
105134   { 197, 4 },
105135   { 205, 2 },
105136   { 205, 1 },
105137   { 205, 0 },
105138   { 198, 0 },
105139   { 198, 2 },
105140   { 207, 2 },
105141   { 207, 0 },
105142   { 206, 7 },
105143   { 206, 7 },
105144   { 206, 7 },
105145   { 157, 0 },
105146   { 157, 2 },
105147   { 193, 2 },
105148   { 208, 1 },
105149   { 208, 2 },
105150   { 208, 3 },
105151   { 208, 4 },
105152   { 210, 2 },
105153   { 210, 0 },
105154   { 209, 0 },
105155   { 209, 3 },
105156   { 209, 2 },
105157   { 211, 4 },
105158   { 211, 0 },
105159   { 202, 0 },
105160   { 202, 3 },
105161   { 214, 4 },
105162   { 214, 2 },
105163   { 215, 1 },
105164   { 177, 1 },
105165   { 177, 1 },
105166   { 177, 0 },
105167   { 200, 0 },
105168   { 200, 3 },
105169   { 201, 0 },
105170   { 201, 2 },
105171   { 203, 0 },
105172   { 203, 2 },
105173   { 203, 4 },
105174   { 203, 4 },
105175   { 147, 5 },
105176   { 199, 0 },
105177   { 199, 2 },
105178   { 147, 7 },
105179   { 217, 5 },
105180   { 217, 3 },
105181   { 147, 8 },
105182   { 147, 5 },
105183   { 147, 6 },
105184   { 218, 2 },
105185   { 218, 1 },
105186   { 220, 3 },
105187   { 220, 1 },
105188   { 219, 0 },
105189   { 219, 3 },
105190   { 213, 3 },
105191   { 213, 1 },
105192   { 175, 1 },
105193   { 175, 3 },
105194   { 174, 1 },
105195   { 175, 1 },
105196   { 175, 1 },
105197   { 175, 3 },
105198   { 175, 5 },
105199   { 174, 1 },
105200   { 174, 1 },
105201   { 175, 1 },
105202   { 175, 1 },
105203   { 175, 3 },
105204   { 175, 6 },
105205   { 175, 5 },
105206   { 175, 4 },
105207   { 174, 1 },
105208   { 175, 3 },
105209   { 175, 3 },
105210   { 175, 3 },
105211   { 175, 3 },
105212   { 175, 3 },
105213   { 175, 3 },
105214   { 175, 3 },
105215   { 175, 3 },
105216   { 222, 1 },
105217   { 222, 2 },
105218   { 222, 1 },
105219   { 222, 2 },
105220   { 175, 3 },
105221   { 175, 5 },
105222   { 175, 2 },
105223   { 175, 3 },
105224   { 175, 3 },
105225   { 175, 4 },
105226   { 175, 2 },
105227   { 175, 2 },
105228   { 175, 2 },
105229   { 175, 2 },
105230   { 223, 1 },
105231   { 223, 2 },
105232   { 175, 5 },
105233   { 224, 1 },
105234   { 224, 2 },
105235   { 175, 5 },
105236   { 175, 3 },
105237   { 175, 5 },
105238   { 175, 4 },
105239   { 175, 4 },
105240   { 175, 5 },
105241   { 226, 5 },
105242   { 226, 4 },
105243   { 227, 2 },
105244   { 227, 0 },
105245   { 225, 1 },
105246   { 225, 0 },
105247   { 221, 1 },
105248   { 221, 0 },
105249   { 216, 3 },
105250   { 216, 1 },
105251   { 147, 11 },
105252   { 228, 1 },
105253   { 228, 0 },
105254   { 179, 0 },
105255   { 179, 3 },
105256   { 187, 5 },
105257   { 187, 3 },
105258   { 229, 0 },
105259   { 229, 2 },
105260   { 147, 4 },
105261   { 147, 1 },
105262   { 147, 2 },
105263   { 147, 3 },
105264   { 147, 5 },
105265   { 147, 6 },
105266   { 147, 5 },
105267   { 147, 6 },
105268   { 230, 1 },
105269   { 230, 1 },
105270   { 230, 1 },
105271   { 230, 1 },
105272   { 230, 1 },
105273   { 170, 2 },
105274   { 171, 2 },
105275   { 232, 1 },
105276   { 231, 1 },
105277   { 231, 0 },
105278   { 147, 5 },
105279   { 233, 11 },
105280   { 235, 1 },
105281   { 235, 1 },
105282   { 235, 2 },
105283   { 235, 0 },
105284   { 236, 1 },
105285   { 236, 1 },
105286   { 236, 3 },
105287   { 237, 0 },
105288   { 237, 3 },
105289   { 238, 0 },
105290   { 238, 2 },
105291   { 234, 3 },
105292   { 234, 2 },
105293   { 240, 1 },
105294   { 240, 3 },
105295   { 241, 0 },
105296   { 241, 3 },
105297   { 241, 2 },
105298   { 239, 7 },
105299   { 239, 8 },
105300   { 239, 5 },
105301   { 239, 5 },
105302   { 239, 1 },
105303   { 175, 4 },
105304   { 175, 6 },
105305   { 191, 1 },
105306   { 191, 1 },
105307   { 191, 1 },
105308   { 147, 4 },
105309   { 147, 6 },
105310   { 147, 3 },
105311   { 243, 0 },
105312   { 243, 2 },
105313   { 242, 1 },
105314   { 242, 0 },
105315   { 147, 1 },
105316   { 147, 3 },
105317   { 147, 1 },
105318   { 147, 3 },
105319   { 147, 6 },
105320   { 147, 6 },
105321   { 244, 1 },
105322   { 245, 0 },
105323   { 245, 1 },
105324   { 147, 1 },
105325   { 147, 4 },
105326   { 246, 7 },
105327   { 247, 1 },
105328   { 247, 3 },
105329   { 248, 0 },
105330   { 248, 2 },
105331   { 249, 1 },
105332   { 249, 3 },
105333   { 250, 1 },
105334   { 251, 0 },
105335   { 251, 4 },
105336   { 251, 2 },
105337 };
105338
105339 static void yy_accept(yyParser*);  /* Forward Declaration */
105340
105341 /*
105342 ** Perform a reduce action and the shift that must immediately
105343 ** follow the reduce.
105344 */
105345 static void yy_reduce(
105346   yyParser *yypParser,         /* The parser */
105347   int yyruleno                 /* Number of the rule by which to reduce */
105348 ){
105349   int yygoto;                     /* The next state */
105350   int yyact;                      /* The next action */
105351   YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
105352   yyStackEntry *yymsp;            /* The top of the parser's stack */
105353   int yysize;                     /* Amount to pop the stack */
105354   sqlite3ParserARG_FETCH;
105355   yymsp = &yypParser->yystack[yypParser->yyidx];
105356 #ifndef NDEBUG
105357   if( yyTraceFILE && yyruleno>=0 
105358         && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
105359     fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
105360       yyRuleName[yyruleno]);
105361   }
105362 #endif /* NDEBUG */
105363
105364   /* Silence complaints from purify about yygotominor being uninitialized
105365   ** in some cases when it is copied into the stack after the following
105366   ** switch.  yygotominor is uninitialized when a rule reduces that does
105367   ** not set the value of its left-hand side nonterminal.  Leaving the
105368   ** value of the nonterminal uninitialized is utterly harmless as long
105369   ** as the value is never used.  So really the only thing this code
105370   ** accomplishes is to quieten purify.  
105371   **
105372   ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
105373   ** without this code, their parser segfaults.  I'm not sure what there
105374   ** parser is doing to make this happen.  This is the second bug report
105375   ** from wireshark this week.  Clearly they are stressing Lemon in ways
105376   ** that it has not been previously stressed...  (SQLite ticket #2172)
105377   */
105378   /*memset(&yygotominor, 0, sizeof(yygotominor));*/
105379   yygotominor = yyzerominor;
105380
105381
105382   switch( yyruleno ){
105383   /* Beginning here are the reduction cases.  A typical example
105384   ** follows:
105385   **   case 0:
105386   **  #line <lineno> <grammarfile>
105387   **     { ... }           // User supplied code
105388   **  #line <lineno> <thisfile>
105389   **     break;
105390   */
105391       case 5: /* explain ::= */
105392 { sqlite3BeginParse(pParse, 0); }
105393         break;
105394       case 6: /* explain ::= EXPLAIN */
105395 { sqlite3BeginParse(pParse, 1); }
105396         break;
105397       case 7: /* explain ::= EXPLAIN QUERY PLAN */
105398 { sqlite3BeginParse(pParse, 2); }
105399         break;
105400       case 8: /* cmdx ::= cmd */
105401 { sqlite3FinishCoding(pParse); }
105402         break;
105403       case 9: /* cmd ::= BEGIN transtype trans_opt */
105404 {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy4);}
105405         break;
105406       case 13: /* transtype ::= */
105407 {yygotominor.yy4 = TK_DEFERRED;}
105408         break;
105409       case 14: /* transtype ::= DEFERRED */
105410       case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
105411       case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
105412       case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
105413       case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
105414 {yygotominor.yy4 = yymsp[0].major;}
105415         break;
105416       case 17: /* cmd ::= COMMIT trans_opt */
105417       case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
105418 {sqlite3CommitTransaction(pParse);}
105419         break;
105420       case 19: /* cmd ::= ROLLBACK trans_opt */
105421 {sqlite3RollbackTransaction(pParse);}
105422         break;
105423       case 22: /* cmd ::= SAVEPOINT nm */
105424 {
105425   sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
105426 }
105427         break;
105428       case 23: /* cmd ::= RELEASE savepoint_opt nm */
105429 {
105430   sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
105431 }
105432         break;
105433       case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
105434 {
105435   sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
105436 }
105437         break;
105438       case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
105439 {
105440    sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy4,0,0,yymsp[-2].minor.yy4);
105441 }
105442         break;
105443       case 27: /* createkw ::= CREATE */
105444 {
105445   pParse->db->lookaside.bEnabled = 0;
105446   yygotominor.yy0 = yymsp[0].minor.yy0;
105447 }
105448         break;
105449       case 28: /* ifnotexists ::= */
105450       case 31: /* temp ::= */ yytestcase(yyruleno==31);
105451       case 70: /* autoinc ::= */ yytestcase(yyruleno==70);
105452       case 83: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==83);
105453       case 85: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==85);
105454       case 87: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==87);
105455       case 98: /* defer_subclause_opt ::= */ yytestcase(yyruleno==98);
105456       case 109: /* ifexists ::= */ yytestcase(yyruleno==109);
105457       case 120: /* distinct ::= ALL */ yytestcase(yyruleno==120);
105458       case 121: /* distinct ::= */ yytestcase(yyruleno==121);
105459       case 222: /* between_op ::= BETWEEN */ yytestcase(yyruleno==222);
105460       case 225: /* in_op ::= IN */ yytestcase(yyruleno==225);
105461 {yygotominor.yy4 = 0;}
105462         break;
105463       case 29: /* ifnotexists ::= IF NOT EXISTS */
105464       case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
105465       case 71: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==71);
105466       case 86: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==86);
105467       case 108: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==108);
105468       case 119: /* distinct ::= DISTINCT */ yytestcase(yyruleno==119);
105469       case 223: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==223);
105470       case 226: /* in_op ::= NOT IN */ yytestcase(yyruleno==226);
105471 {yygotominor.yy4 = 1;}
105472         break;
105473       case 32: /* create_table_args ::= LP columnlist conslist_opt RP */
105474 {
105475   sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
105476 }
105477         break;
105478       case 33: /* create_table_args ::= AS select */
105479 {
105480   sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy387);
105481   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy387);
105482 }
105483         break;
105484       case 36: /* column ::= columnid type carglist */
105485 {
105486   yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
105487   yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
105488 }
105489         break;
105490       case 37: /* columnid ::= nm */
105491 {
105492   sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
105493   yygotominor.yy0 = yymsp[0].minor.yy0;
105494 }
105495         break;
105496       case 38: /* id ::= ID */
105497       case 39: /* id ::= INDEXED */ yytestcase(yyruleno==39);
105498       case 40: /* ids ::= ID|STRING */ yytestcase(yyruleno==40);
105499       case 41: /* nm ::= id */ yytestcase(yyruleno==41);
105500       case 42: /* nm ::= STRING */ yytestcase(yyruleno==42);
105501       case 43: /* nm ::= JOIN_KW */ yytestcase(yyruleno==43);
105502       case 46: /* typetoken ::= typename */ yytestcase(yyruleno==46);
105503       case 49: /* typename ::= ids */ yytestcase(yyruleno==49);
105504       case 127: /* as ::= AS nm */ yytestcase(yyruleno==127);
105505       case 128: /* as ::= ids */ yytestcase(yyruleno==128);
105506       case 138: /* dbnm ::= DOT nm */ yytestcase(yyruleno==138);
105507       case 147: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==147);
105508       case 251: /* collate ::= COLLATE ids */ yytestcase(yyruleno==251);
105509       case 260: /* nmnum ::= plus_num */ yytestcase(yyruleno==260);
105510       case 261: /* nmnum ::= nm */ yytestcase(yyruleno==261);
105511       case 262: /* nmnum ::= ON */ yytestcase(yyruleno==262);
105512       case 263: /* nmnum ::= DELETE */ yytestcase(yyruleno==263);
105513       case 264: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==264);
105514       case 265: /* plus_num ::= plus_opt number */ yytestcase(yyruleno==265);
105515       case 266: /* minus_num ::= MINUS number */ yytestcase(yyruleno==266);
105516       case 267: /* number ::= INTEGER|FLOAT */ yytestcase(yyruleno==267);
105517       case 285: /* trnm ::= nm */ yytestcase(yyruleno==285);
105518 {yygotominor.yy0 = yymsp[0].minor.yy0;}
105519         break;
105520       case 45: /* type ::= typetoken */
105521 {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
105522         break;
105523       case 47: /* typetoken ::= typename LP signed RP */
105524 {
105525   yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
105526   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
105527 }
105528         break;
105529       case 48: /* typetoken ::= typename LP signed COMMA signed RP */
105530 {
105531   yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
105532   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
105533 }
105534         break;
105535       case 50: /* typename ::= typename ids */
105536 {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);}
105537         break;
105538       case 57: /* ccons ::= DEFAULT term */
105539       case 59: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==59);
105540 {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy118);}
105541         break;
105542       case 58: /* ccons ::= DEFAULT LP expr RP */
105543 {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy118);}
105544         break;
105545       case 60: /* ccons ::= DEFAULT MINUS term */
105546 {
105547   ExprSpan v;
105548   v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy118.pExpr, 0, 0);
105549   v.zStart = yymsp[-1].minor.yy0.z;
105550   v.zEnd = yymsp[0].minor.yy118.zEnd;
105551   sqlite3AddDefaultValue(pParse,&v);
105552 }
105553         break;
105554       case 61: /* ccons ::= DEFAULT id */
105555 {
105556   ExprSpan v;
105557   spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
105558   sqlite3AddDefaultValue(pParse,&v);
105559 }
105560         break;
105561       case 63: /* ccons ::= NOT NULL onconf */
105562 {sqlite3AddNotNull(pParse, yymsp[0].minor.yy4);}
105563         break;
105564       case 64: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
105565 {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy4,yymsp[0].minor.yy4,yymsp[-2].minor.yy4);}
105566         break;
105567       case 65: /* ccons ::= UNIQUE onconf */
105568 {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy4,0,0,0,0);}
105569         break;
105570       case 66: /* ccons ::= CHECK LP expr RP */
105571 {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy118.pExpr);}
105572         break;
105573       case 67: /* ccons ::= REFERENCES nm idxlist_opt refargs */
105574 {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy322,yymsp[0].minor.yy4);}
105575         break;
105576       case 68: /* ccons ::= defer_subclause */
105577 {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy4);}
105578         break;
105579       case 69: /* ccons ::= COLLATE ids */
105580 {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
105581         break;
105582       case 72: /* refargs ::= */
105583 { yygotominor.yy4 = OE_None*0x0101; /* EV: R-19803-45884 */}
105584         break;
105585       case 73: /* refargs ::= refargs refarg */
105586 { yygotominor.yy4 = (yymsp[-1].minor.yy4 & ~yymsp[0].minor.yy215.mask) | yymsp[0].minor.yy215.value; }
105587         break;
105588       case 74: /* refarg ::= MATCH nm */
105589       case 75: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==75);
105590 { yygotominor.yy215.value = 0;     yygotominor.yy215.mask = 0x000000; }
105591         break;
105592       case 76: /* refarg ::= ON DELETE refact */
105593 { yygotominor.yy215.value = yymsp[0].minor.yy4;     yygotominor.yy215.mask = 0x0000ff; }
105594         break;
105595       case 77: /* refarg ::= ON UPDATE refact */
105596 { yygotominor.yy215.value = yymsp[0].minor.yy4<<8;  yygotominor.yy215.mask = 0x00ff00; }
105597         break;
105598       case 78: /* refact ::= SET NULL */
105599 { yygotominor.yy4 = OE_SetNull;  /* EV: R-33326-45252 */}
105600         break;
105601       case 79: /* refact ::= SET DEFAULT */
105602 { yygotominor.yy4 = OE_SetDflt;  /* EV: R-33326-45252 */}
105603         break;
105604       case 80: /* refact ::= CASCADE */
105605 { yygotominor.yy4 = OE_Cascade;  /* EV: R-33326-45252 */}
105606         break;
105607       case 81: /* refact ::= RESTRICT */
105608 { yygotominor.yy4 = OE_Restrict; /* EV: R-33326-45252 */}
105609         break;
105610       case 82: /* refact ::= NO ACTION */
105611 { yygotominor.yy4 = OE_None;     /* EV: R-33326-45252 */}
105612         break;
105613       case 84: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
105614       case 99: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==99);
105615       case 101: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==101);
105616       case 104: /* resolvetype ::= raisetype */ yytestcase(yyruleno==104);
105617 {yygotominor.yy4 = yymsp[0].minor.yy4;}
105618         break;
105619       case 88: /* conslist_opt ::= */
105620 {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
105621         break;
105622       case 89: /* conslist_opt ::= COMMA conslist */
105623 {yygotominor.yy0 = yymsp[-1].minor.yy0;}
105624         break;
105625       case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
105626 {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy322,yymsp[0].minor.yy4,yymsp[-2].minor.yy4,0);}
105627         break;
105628       case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */
105629 {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy322,yymsp[0].minor.yy4,0,0,0,0);}
105630         break;
105631       case 96: /* tcons ::= CHECK LP expr RP onconf */
105632 {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy118.pExpr);}
105633         break;
105634       case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
105635 {
105636     sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy322, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy322, yymsp[-1].minor.yy4);
105637     sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy4);
105638 }
105639         break;
105640       case 100: /* onconf ::= */
105641 {yygotominor.yy4 = OE_Default;}
105642         break;
105643       case 102: /* orconf ::= */
105644 {yygotominor.yy210 = OE_Default;}
105645         break;
105646       case 103: /* orconf ::= OR resolvetype */
105647 {yygotominor.yy210 = (u8)yymsp[0].minor.yy4;}
105648         break;
105649       case 105: /* resolvetype ::= IGNORE */
105650 {yygotominor.yy4 = OE_Ignore;}
105651         break;
105652       case 106: /* resolvetype ::= REPLACE */
105653 {yygotominor.yy4 = OE_Replace;}
105654         break;
105655       case 107: /* cmd ::= DROP TABLE ifexists fullname */
105656 {
105657   sqlite3DropTable(pParse, yymsp[0].minor.yy259, 0, yymsp[-1].minor.yy4);
105658 }
105659         break;
105660       case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
105661 {
105662   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);
105663 }
105664         break;
105665       case 111: /* cmd ::= DROP VIEW ifexists fullname */
105666 {
105667   sqlite3DropTable(pParse, yymsp[0].minor.yy259, 1, yymsp[-1].minor.yy4);
105668 }
105669         break;
105670       case 112: /* cmd ::= select */
105671 {
105672   SelectDest dest = {SRT_Output, 0, 0, 0, 0};
105673   sqlite3Select(pParse, yymsp[0].minor.yy387, &dest);
105674   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy387);
105675 }
105676         break;
105677       case 113: /* select ::= oneselect */
105678 {yygotominor.yy387 = yymsp[0].minor.yy387;}
105679         break;
105680       case 114: /* select ::= select multiselect_op oneselect */
105681 {
105682   if( yymsp[0].minor.yy387 ){
105683     yymsp[0].minor.yy387->op = (u8)yymsp[-1].minor.yy4;
105684     yymsp[0].minor.yy387->pPrior = yymsp[-2].minor.yy387;
105685   }else{
105686     sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy387);
105687   }
105688   yygotominor.yy387 = yymsp[0].minor.yy387;
105689 }
105690         break;
105691       case 116: /* multiselect_op ::= UNION ALL */
105692 {yygotominor.yy4 = TK_ALL;}
105693         break;
105694       case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
105695 {
105696   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);
105697 }
105698         break;
105699       case 122: /* sclp ::= selcollist COMMA */
105700       case 247: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==247);
105701 {yygotominor.yy322 = yymsp[-1].minor.yy322;}
105702         break;
105703       case 123: /* sclp ::= */
105704       case 151: /* orderby_opt ::= */ yytestcase(yyruleno==151);
105705       case 159: /* groupby_opt ::= */ yytestcase(yyruleno==159);
105706       case 240: /* exprlist ::= */ yytestcase(yyruleno==240);
105707       case 246: /* idxlist_opt ::= */ yytestcase(yyruleno==246);
105708 {yygotominor.yy322 = 0;}
105709         break;
105710       case 124: /* selcollist ::= sclp expr as */
105711 {
105712    yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy322, yymsp[-1].minor.yy118.pExpr);
105713    if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[0].minor.yy0, 1);
105714    sqlite3ExprListSetSpan(pParse,yygotominor.yy322,&yymsp[-1].minor.yy118);
105715 }
105716         break;
105717       case 125: /* selcollist ::= sclp STAR */
105718 {
105719   Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
105720   yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy322, p);
105721 }
105722         break;
105723       case 126: /* selcollist ::= sclp nm DOT STAR */
105724 {
105725   Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
105726   Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
105727   Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
105728   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy322, pDot);
105729 }
105730         break;
105731       case 129: /* as ::= */
105732 {yygotominor.yy0.n = 0;}
105733         break;
105734       case 130: /* from ::= */
105735 {yygotominor.yy259 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy259));}
105736         break;
105737       case 131: /* from ::= FROM seltablist */
105738 {
105739   yygotominor.yy259 = yymsp[0].minor.yy259;
105740   sqlite3SrcListShiftJoinType(yygotominor.yy259);
105741 }
105742         break;
105743       case 132: /* stl_prefix ::= seltablist joinop */
105744 {
105745    yygotominor.yy259 = yymsp[-1].minor.yy259;
105746    if( ALWAYS(yygotominor.yy259 && yygotominor.yy259->nSrc>0) ) yygotominor.yy259->a[yygotominor.yy259->nSrc-1].jointype = (u8)yymsp[0].minor.yy4;
105747 }
105748         break;
105749       case 133: /* stl_prefix ::= */
105750 {yygotominor.yy259 = 0;}
105751         break;
105752       case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
105753 {
105754   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);
105755   sqlite3SrcListIndexedBy(pParse, yygotominor.yy259, &yymsp[-2].minor.yy0);
105756 }
105757         break;
105758       case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
105759 {
105760     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);
105761   }
105762         break;
105763       case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
105764 {
105765     if( yymsp[-6].minor.yy259==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy314==0 && yymsp[0].minor.yy384==0 ){
105766       yygotominor.yy259 = yymsp[-4].minor.yy259;
105767     }else{
105768       Select *pSubquery;
105769       sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy259);
105770       pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy259,0,0,0,0,0,0,0);
105771       yygotominor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
105772     }
105773   }
105774         break;
105775       case 137: /* dbnm ::= */
105776       case 146: /* indexed_opt ::= */ yytestcase(yyruleno==146);
105777 {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
105778         break;
105779       case 139: /* fullname ::= nm dbnm */
105780 {yygotominor.yy259 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
105781         break;
105782       case 140: /* joinop ::= COMMA|JOIN */
105783 { yygotominor.yy4 = JT_INNER; }
105784         break;
105785       case 141: /* joinop ::= JOIN_KW JOIN */
105786 { yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
105787         break;
105788       case 142: /* joinop ::= JOIN_KW nm JOIN */
105789 { yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
105790         break;
105791       case 143: /* joinop ::= JOIN_KW nm nm JOIN */
105792 { yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
105793         break;
105794       case 144: /* on_opt ::= ON expr */
105795       case 155: /* sortitem ::= expr */ yytestcase(yyruleno==155);
105796       case 162: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==162);
105797       case 169: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==169);
105798       case 235: /* case_else ::= ELSE expr */ yytestcase(yyruleno==235);
105799       case 237: /* case_operand ::= expr */ yytestcase(yyruleno==237);
105800 {yygotominor.yy314 = yymsp[0].minor.yy118.pExpr;}
105801         break;
105802       case 145: /* on_opt ::= */
105803       case 161: /* having_opt ::= */ yytestcase(yyruleno==161);
105804       case 168: /* where_opt ::= */ yytestcase(yyruleno==168);
105805       case 236: /* case_else ::= */ yytestcase(yyruleno==236);
105806       case 238: /* case_operand ::= */ yytestcase(yyruleno==238);
105807 {yygotominor.yy314 = 0;}
105808         break;
105809       case 148: /* indexed_opt ::= NOT INDEXED */
105810 {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
105811         break;
105812       case 149: /* using_opt ::= USING LP inscollist RP */
105813       case 181: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==181);
105814 {yygotominor.yy384 = yymsp[-1].minor.yy384;}
105815         break;
105816       case 150: /* using_opt ::= */
105817       case 180: /* inscollist_opt ::= */ yytestcase(yyruleno==180);
105818 {yygotominor.yy384 = 0;}
105819         break;
105820       case 152: /* orderby_opt ::= ORDER BY sortlist */
105821       case 160: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==160);
105822       case 239: /* exprlist ::= nexprlist */ yytestcase(yyruleno==239);
105823 {yygotominor.yy322 = yymsp[0].minor.yy322;}
105824         break;
105825       case 153: /* sortlist ::= sortlist COMMA sortitem sortorder */
105826 {
105827   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy322,yymsp[-1].minor.yy314);
105828   if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
105829 }
105830         break;
105831       case 154: /* sortlist ::= sortitem sortorder */
105832 {
105833   yygotominor.yy322 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy314);
105834   if( yygotominor.yy322 && ALWAYS(yygotominor.yy322->a) ) yygotominor.yy322->a[0].sortOrder = (u8)yymsp[0].minor.yy4;
105835 }
105836         break;
105837       case 156: /* sortorder ::= ASC */
105838       case 158: /* sortorder ::= */ yytestcase(yyruleno==158);
105839 {yygotominor.yy4 = SQLITE_SO_ASC;}
105840         break;
105841       case 157: /* sortorder ::= DESC */
105842 {yygotominor.yy4 = SQLITE_SO_DESC;}
105843         break;
105844       case 163: /* limit_opt ::= */
105845 {yygotominor.yy292.pLimit = 0; yygotominor.yy292.pOffset = 0;}
105846         break;
105847       case 164: /* limit_opt ::= LIMIT expr */
105848 {yygotominor.yy292.pLimit = yymsp[0].minor.yy118.pExpr; yygotominor.yy292.pOffset = 0;}
105849         break;
105850       case 165: /* limit_opt ::= LIMIT expr OFFSET expr */
105851 {yygotominor.yy292.pLimit = yymsp[-2].minor.yy118.pExpr; yygotominor.yy292.pOffset = yymsp[0].minor.yy118.pExpr;}
105852         break;
105853       case 166: /* limit_opt ::= LIMIT expr COMMA expr */
105854 {yygotominor.yy292.pOffset = yymsp[-2].minor.yy118.pExpr; yygotominor.yy292.pLimit = yymsp[0].minor.yy118.pExpr;}
105855         break;
105856       case 167: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
105857 {
105858   sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy259, &yymsp[-1].minor.yy0);
105859   sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy259,yymsp[0].minor.yy314);
105860 }
105861         break;
105862       case 170: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
105863 {
105864   sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy259, &yymsp[-3].minor.yy0);
105865   sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy322,"set list"); 
105866   sqlite3Update(pParse,yymsp[-4].minor.yy259,yymsp[-1].minor.yy322,yymsp[0].minor.yy314,yymsp[-5].minor.yy210);
105867 }
105868         break;
105869       case 171: /* setlist ::= setlist COMMA nm EQ expr */
105870 {
105871   yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy322, yymsp[0].minor.yy118.pExpr);
105872   sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
105873 }
105874         break;
105875       case 172: /* setlist ::= nm EQ expr */
105876 {
105877   yygotominor.yy322 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy118.pExpr);
105878   sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
105879 }
105880         break;
105881       case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP */
105882 {sqlite3Insert(pParse, yymsp[-5].minor.yy259, yymsp[-1].minor.yy322, 0, yymsp[-4].minor.yy384, yymsp[-7].minor.yy210);}
105883         break;
105884       case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
105885 {sqlite3Insert(pParse, yymsp[-2].minor.yy259, 0, yymsp[0].minor.yy387, yymsp[-1].minor.yy384, yymsp[-4].minor.yy210);}
105886         break;
105887       case 175: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
105888 {sqlite3Insert(pParse, yymsp[-3].minor.yy259, 0, 0, yymsp[-2].minor.yy384, yymsp[-5].minor.yy210);}
105889         break;
105890       case 176: /* insert_cmd ::= INSERT orconf */
105891 {yygotominor.yy210 = yymsp[0].minor.yy210;}
105892         break;
105893       case 177: /* insert_cmd ::= REPLACE */
105894 {yygotominor.yy210 = OE_Replace;}
105895         break;
105896       case 178: /* itemlist ::= itemlist COMMA expr */
105897       case 241: /* nexprlist ::= nexprlist COMMA expr */ yytestcase(yyruleno==241);
105898 {yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy322,yymsp[0].minor.yy118.pExpr);}
105899         break;
105900       case 179: /* itemlist ::= expr */
105901       case 242: /* nexprlist ::= expr */ yytestcase(yyruleno==242);
105902 {yygotominor.yy322 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy118.pExpr);}
105903         break;
105904       case 182: /* inscollist ::= inscollist COMMA nm */
105905 {yygotominor.yy384 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy384,&yymsp[0].minor.yy0);}
105906         break;
105907       case 183: /* inscollist ::= nm */
105908 {yygotominor.yy384 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
105909         break;
105910       case 184: /* expr ::= term */
105911 {yygotominor.yy118 = yymsp[0].minor.yy118;}
105912         break;
105913       case 185: /* expr ::= LP expr RP */
105914 {yygotominor.yy118.pExpr = yymsp[-1].minor.yy118.pExpr; spanSet(&yygotominor.yy118,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
105915         break;
105916       case 186: /* term ::= NULL */
105917       case 191: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==191);
105918       case 192: /* term ::= STRING */ yytestcase(yyruleno==192);
105919 {spanExpr(&yygotominor.yy118, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
105920         break;
105921       case 187: /* expr ::= id */
105922       case 188: /* expr ::= JOIN_KW */ yytestcase(yyruleno==188);
105923 {spanExpr(&yygotominor.yy118, pParse, TK_ID, &yymsp[0].minor.yy0);}
105924         break;
105925       case 189: /* expr ::= nm DOT nm */
105926 {
105927   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
105928   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
105929   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
105930   spanSet(&yygotominor.yy118,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
105931 }
105932         break;
105933       case 190: /* expr ::= nm DOT nm DOT nm */
105934 {
105935   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
105936   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
105937   Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
105938   Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
105939   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
105940   spanSet(&yygotominor.yy118,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
105941 }
105942         break;
105943       case 193: /* expr ::= REGISTER */
105944 {
105945   /* When doing a nested parse, one can include terms in an expression
105946   ** that look like this:   #1 #2 ...  These terms refer to registers
105947   ** in the virtual machine.  #N is the N-th register. */
105948   if( pParse->nested==0 ){
105949     sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
105950     yygotominor.yy118.pExpr = 0;
105951   }else{
105952     yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
105953     if( yygotominor.yy118.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy118.pExpr->iTable);
105954   }
105955   spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
105956 }
105957         break;
105958       case 194: /* expr ::= VARIABLE */
105959 {
105960   spanExpr(&yygotominor.yy118, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
105961   sqlite3ExprAssignVarNumber(pParse, yygotominor.yy118.pExpr);
105962   spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
105963 }
105964         break;
105965       case 195: /* expr ::= expr COLLATE ids */
105966 {
105967   yygotominor.yy118.pExpr = sqlite3ExprSetCollByToken(pParse, yymsp[-2].minor.yy118.pExpr, &yymsp[0].minor.yy0);
105968   yygotominor.yy118.zStart = yymsp[-2].minor.yy118.zStart;
105969   yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
105970 }
105971         break;
105972       case 196: /* expr ::= CAST LP expr AS typetoken RP */
105973 {
105974   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy118.pExpr, 0, &yymsp[-1].minor.yy0);
105975   spanSet(&yygotominor.yy118,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
105976 }
105977         break;
105978       case 197: /* expr ::= ID LP distinct exprlist RP */
105979 {
105980   if( yymsp[-1].minor.yy322 && yymsp[-1].minor.yy322->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
105981     sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
105982   }
105983   yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy322, &yymsp[-4].minor.yy0);
105984   spanSet(&yygotominor.yy118,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
105985   if( yymsp[-2].minor.yy4 && yygotominor.yy118.pExpr ){
105986     yygotominor.yy118.pExpr->flags |= EP_Distinct;
105987   }
105988 }
105989         break;
105990       case 198: /* expr ::= ID LP STAR RP */
105991 {
105992   yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
105993   spanSet(&yygotominor.yy118,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
105994 }
105995         break;
105996       case 199: /* term ::= CTIME_KW */
105997 {
105998   /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
105999   ** treated as functions that return constants */
106000   yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
106001   if( yygotominor.yy118.pExpr ){
106002     yygotominor.yy118.pExpr->op = TK_CONST_FUNC;  
106003   }
106004   spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
106005 }
106006         break;
106007       case 200: /* expr ::= expr AND expr */
106008       case 201: /* expr ::= expr OR expr */ yytestcase(yyruleno==201);
106009       case 202: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==202);
106010       case 203: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==203);
106011       case 204: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==204);
106012       case 205: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==205);
106013       case 206: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==206);
106014       case 207: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==207);
106015 {spanBinaryExpr(&yygotominor.yy118,pParse,yymsp[-1].major,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy118);}
106016         break;
106017       case 208: /* likeop ::= LIKE_KW */
106018       case 210: /* likeop ::= MATCH */ yytestcase(yyruleno==210);
106019 {yygotominor.yy342.eOperator = yymsp[0].minor.yy0; yygotominor.yy342.not = 0;}
106020         break;
106021       case 209: /* likeop ::= NOT LIKE_KW */
106022       case 211: /* likeop ::= NOT MATCH */ yytestcase(yyruleno==211);
106023 {yygotominor.yy342.eOperator = yymsp[0].minor.yy0; yygotominor.yy342.not = 1;}
106024         break;
106025       case 212: /* expr ::= expr likeop expr */
106026 {
106027   ExprList *pList;
106028   pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy118.pExpr);
106029   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy118.pExpr);
106030   yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy342.eOperator);
106031   if( yymsp[-1].minor.yy342.not ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
106032   yygotominor.yy118.zStart = yymsp[-2].minor.yy118.zStart;
106033   yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
106034   if( yygotominor.yy118.pExpr ) yygotominor.yy118.pExpr->flags |= EP_InfixFunc;
106035 }
106036         break;
106037       case 213: /* expr ::= expr likeop expr ESCAPE expr */
106038 {
106039   ExprList *pList;
106040   pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
106041   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy118.pExpr);
106042   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy118.pExpr);
106043   yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy342.eOperator);
106044   if( yymsp[-3].minor.yy342.not ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
106045   yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
106046   yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
106047   if( yygotominor.yy118.pExpr ) yygotominor.yy118.pExpr->flags |= EP_InfixFunc;
106048 }
106049         break;
106050       case 214: /* expr ::= expr ISNULL|NOTNULL */
106051 {spanUnaryPostfix(&yygotominor.yy118,pParse,yymsp[0].major,&yymsp[-1].minor.yy118,&yymsp[0].minor.yy0);}
106052         break;
106053       case 215: /* expr ::= expr NOT NULL */
106054 {spanUnaryPostfix(&yygotominor.yy118,pParse,TK_NOTNULL,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy0);}
106055         break;
106056       case 216: /* expr ::= expr IS expr */
106057 {
106058   spanBinaryExpr(&yygotominor.yy118,pParse,TK_IS,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy118);
106059   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy118.pExpr, yygotominor.yy118.pExpr, TK_ISNULL);
106060 }
106061         break;
106062       case 217: /* expr ::= expr IS NOT expr */
106063 {
106064   spanBinaryExpr(&yygotominor.yy118,pParse,TK_ISNOT,&yymsp[-3].minor.yy118,&yymsp[0].minor.yy118);
106065   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy118.pExpr, yygotominor.yy118.pExpr, TK_NOTNULL);
106066 }
106067         break;
106068       case 218: /* expr ::= NOT expr */
106069       case 219: /* expr ::= BITNOT expr */ yytestcase(yyruleno==219);
106070 {spanUnaryPrefix(&yygotominor.yy118,pParse,yymsp[-1].major,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
106071         break;
106072       case 220: /* expr ::= MINUS expr */
106073 {spanUnaryPrefix(&yygotominor.yy118,pParse,TK_UMINUS,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
106074         break;
106075       case 221: /* expr ::= PLUS expr */
106076 {spanUnaryPrefix(&yygotominor.yy118,pParse,TK_UPLUS,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
106077         break;
106078       case 224: /* expr ::= expr between_op expr AND expr */
106079 {
106080   ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
106081   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy118.pExpr);
106082   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy118.pExpr, 0, 0);
106083   if( yygotominor.yy118.pExpr ){
106084     yygotominor.yy118.pExpr->x.pList = pList;
106085   }else{
106086     sqlite3ExprListDelete(pParse->db, pList);
106087   } 
106088   if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
106089   yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
106090   yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
106091 }
106092         break;
106093       case 227: /* expr ::= expr in_op LP exprlist RP */
106094 {
106095     if( yymsp[-1].minor.yy322==0 ){
106096       /* Expressions of the form
106097       **
106098       **      expr1 IN ()
106099       **      expr1 NOT IN ()
106100       **
106101       ** simplify to constants 0 (false) and 1 (true), respectively,
106102       ** regardless of the value of expr1.
106103       */
106104       yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy4]);
106105       sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy118.pExpr);
106106     }else{
106107       yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy118.pExpr, 0, 0);
106108       if( yygotominor.yy118.pExpr ){
106109         yygotominor.yy118.pExpr->x.pList = yymsp[-1].minor.yy322;
106110         sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
106111       }else{
106112         sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy322);
106113       }
106114       if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
106115     }
106116     yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
106117     yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
106118   }
106119         break;
106120       case 228: /* expr ::= LP select RP */
106121 {
106122     yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
106123     if( yygotominor.yy118.pExpr ){
106124       yygotominor.yy118.pExpr->x.pSelect = yymsp[-1].minor.yy387;
106125       ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
106126       sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
106127     }else{
106128       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
106129     }
106130     yygotominor.yy118.zStart = yymsp[-2].minor.yy0.z;
106131     yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
106132   }
106133         break;
106134       case 229: /* expr ::= expr in_op LP select RP */
106135 {
106136     yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy118.pExpr, 0, 0);
106137     if( yygotominor.yy118.pExpr ){
106138       yygotominor.yy118.pExpr->x.pSelect = yymsp[-1].minor.yy387;
106139       ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
106140       sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
106141     }else{
106142       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
106143     }
106144     if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
106145     yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
106146     yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
106147   }
106148         break;
106149       case 230: /* expr ::= expr in_op nm dbnm */
106150 {
106151     SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
106152     yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy118.pExpr, 0, 0);
106153     if( yygotominor.yy118.pExpr ){
106154       yygotominor.yy118.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
106155       ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
106156       sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
106157     }else{
106158       sqlite3SrcListDelete(pParse->db, pSrc);
106159     }
106160     if( yymsp[-2].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
106161     yygotominor.yy118.zStart = yymsp[-3].minor.yy118.zStart;
106162     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];
106163   }
106164         break;
106165       case 231: /* expr ::= EXISTS LP select RP */
106166 {
106167     Expr *p = yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
106168     if( p ){
106169       p->x.pSelect = yymsp[-1].minor.yy387;
106170       ExprSetProperty(p, EP_xIsSelect);
106171       sqlite3ExprSetHeight(pParse, p);
106172     }else{
106173       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
106174     }
106175     yygotominor.yy118.zStart = yymsp[-3].minor.yy0.z;
106176     yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
106177   }
106178         break;
106179       case 232: /* expr ::= CASE case_operand case_exprlist case_else END */
106180 {
106181   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy314, yymsp[-1].minor.yy314, 0);
106182   if( yygotominor.yy118.pExpr ){
106183     yygotominor.yy118.pExpr->x.pList = yymsp[-2].minor.yy322;
106184     sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
106185   }else{
106186     sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy322);
106187   }
106188   yygotominor.yy118.zStart = yymsp[-4].minor.yy0.z;
106189   yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
106190 }
106191         break;
106192       case 233: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
106193 {
106194   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, yymsp[-2].minor.yy118.pExpr);
106195   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yygotominor.yy322, yymsp[0].minor.yy118.pExpr);
106196 }
106197         break;
106198       case 234: /* case_exprlist ::= WHEN expr THEN expr */
106199 {
106200   yygotominor.yy322 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
106201   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yygotominor.yy322, yymsp[0].minor.yy118.pExpr);
106202 }
106203         break;
106204       case 243: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
106205 {
106206   sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0, 
106207                      sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy322, yymsp[-9].minor.yy4,
106208                       &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy4);
106209 }
106210         break;
106211       case 244: /* uniqueflag ::= UNIQUE */
106212       case 298: /* raisetype ::= ABORT */ yytestcase(yyruleno==298);
106213 {yygotominor.yy4 = OE_Abort;}
106214         break;
106215       case 245: /* uniqueflag ::= */
106216 {yygotominor.yy4 = OE_None;}
106217         break;
106218       case 248: /* idxlist ::= idxlist COMMA nm collate sortorder */
106219 {
106220   Expr *p = 0;
106221   if( yymsp[-1].minor.yy0.n>0 ){
106222     p = sqlite3Expr(pParse->db, TK_COLUMN, 0);
106223     sqlite3ExprSetCollByToken(pParse, p, &yymsp[-1].minor.yy0);
106224   }
106225   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, p);
106226   sqlite3ExprListSetName(pParse,yygotominor.yy322,&yymsp[-2].minor.yy0,1);
106227   sqlite3ExprListCheckLength(pParse, yygotominor.yy322, "index");
106228   if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
106229 }
106230         break;
106231       case 249: /* idxlist ::= nm collate sortorder */
106232 {
106233   Expr *p = 0;
106234   if( yymsp[-1].minor.yy0.n>0 ){
106235     p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
106236     sqlite3ExprSetCollByToken(pParse, p, &yymsp[-1].minor.yy0);
106237   }
106238   yygotominor.yy322 = sqlite3ExprListAppend(pParse,0, p);
106239   sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
106240   sqlite3ExprListCheckLength(pParse, yygotominor.yy322, "index");
106241   if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
106242 }
106243         break;
106244       case 250: /* collate ::= */
106245 {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
106246         break;
106247       case 252: /* cmd ::= DROP INDEX ifexists fullname */
106248 {sqlite3DropIndex(pParse, yymsp[0].minor.yy259, yymsp[-1].minor.yy4);}
106249         break;
106250       case 253: /* cmd ::= VACUUM */
106251       case 254: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==254);
106252 {sqlite3Vacuum(pParse);}
106253         break;
106254       case 255: /* cmd ::= PRAGMA nm dbnm */
106255 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
106256         break;
106257       case 256: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
106258 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
106259         break;
106260       case 257: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
106261 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
106262         break;
106263       case 258: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
106264 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
106265         break;
106266       case 259: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
106267 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
106268         break;
106269       case 270: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
106270 {
106271   Token all;
106272   all.z = yymsp[-3].minor.yy0.z;
106273   all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
106274   sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy203, &all);
106275 }
106276         break;
106277       case 271: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
106278 {
106279   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);
106280   yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
106281 }
106282         break;
106283       case 272: /* trigger_time ::= BEFORE */
106284       case 275: /* trigger_time ::= */ yytestcase(yyruleno==275);
106285 { yygotominor.yy4 = TK_BEFORE; }
106286         break;
106287       case 273: /* trigger_time ::= AFTER */
106288 { yygotominor.yy4 = TK_AFTER;  }
106289         break;
106290       case 274: /* trigger_time ::= INSTEAD OF */
106291 { yygotominor.yy4 = TK_INSTEAD;}
106292         break;
106293       case 276: /* trigger_event ::= DELETE|INSERT */
106294       case 277: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==277);
106295 {yygotominor.yy90.a = yymsp[0].major; yygotominor.yy90.b = 0;}
106296         break;
106297       case 278: /* trigger_event ::= UPDATE OF inscollist */
106298 {yygotominor.yy90.a = TK_UPDATE; yygotominor.yy90.b = yymsp[0].minor.yy384;}
106299         break;
106300       case 281: /* when_clause ::= */
106301       case 303: /* key_opt ::= */ yytestcase(yyruleno==303);
106302 { yygotominor.yy314 = 0; }
106303         break;
106304       case 282: /* when_clause ::= WHEN expr */
106305       case 304: /* key_opt ::= KEY expr */ yytestcase(yyruleno==304);
106306 { yygotominor.yy314 = yymsp[0].minor.yy118.pExpr; }
106307         break;
106308       case 283: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
106309 {
106310   assert( yymsp[-2].minor.yy203!=0 );
106311   yymsp[-2].minor.yy203->pLast->pNext = yymsp[-1].minor.yy203;
106312   yymsp[-2].minor.yy203->pLast = yymsp[-1].minor.yy203;
106313   yygotominor.yy203 = yymsp[-2].minor.yy203;
106314 }
106315         break;
106316       case 284: /* trigger_cmd_list ::= trigger_cmd SEMI */
106317
106318   assert( yymsp[-1].minor.yy203!=0 );
106319   yymsp[-1].minor.yy203->pLast = yymsp[-1].minor.yy203;
106320   yygotominor.yy203 = yymsp[-1].minor.yy203;
106321 }
106322         break;
106323       case 286: /* trnm ::= nm DOT nm */
106324 {
106325   yygotominor.yy0 = yymsp[0].minor.yy0;
106326   sqlite3ErrorMsg(pParse, 
106327         "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
106328         "statements within triggers");
106329 }
106330         break;
106331       case 288: /* tridxby ::= INDEXED BY nm */
106332 {
106333   sqlite3ErrorMsg(pParse,
106334         "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
106335         "within triggers");
106336 }
106337         break;
106338       case 289: /* tridxby ::= NOT INDEXED */
106339 {
106340   sqlite3ErrorMsg(pParse,
106341         "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
106342         "within triggers");
106343 }
106344         break;
106345       case 290: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
106346 { yygotominor.yy203 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy322, yymsp[0].minor.yy314, yymsp[-5].minor.yy210); }
106347         break;
106348       case 291: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP */
106349 {yygotominor.yy203 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy384, yymsp[-1].minor.yy322, 0, yymsp[-7].minor.yy210);}
106350         break;
106351       case 292: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
106352 {yygotominor.yy203 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy384, 0, yymsp[0].minor.yy387, yymsp[-4].minor.yy210);}
106353         break;
106354       case 293: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
106355 {yygotominor.yy203 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy314);}
106356         break;
106357       case 294: /* trigger_cmd ::= select */
106358 {yygotominor.yy203 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy387); }
106359         break;
106360       case 295: /* expr ::= RAISE LP IGNORE RP */
106361 {
106362   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0); 
106363   if( yygotominor.yy118.pExpr ){
106364     yygotominor.yy118.pExpr->affinity = OE_Ignore;
106365   }
106366   yygotominor.yy118.zStart = yymsp[-3].minor.yy0.z;
106367   yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
106368 }
106369         break;
106370       case 296: /* expr ::= RAISE LP raisetype COMMA nm RP */
106371 {
106372   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0); 
106373   if( yygotominor.yy118.pExpr ) {
106374     yygotominor.yy118.pExpr->affinity = (char)yymsp[-3].minor.yy4;
106375   }
106376   yygotominor.yy118.zStart = yymsp[-5].minor.yy0.z;
106377   yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
106378 }
106379         break;
106380       case 297: /* raisetype ::= ROLLBACK */
106381 {yygotominor.yy4 = OE_Rollback;}
106382         break;
106383       case 299: /* raisetype ::= FAIL */
106384 {yygotominor.yy4 = OE_Fail;}
106385         break;
106386       case 300: /* cmd ::= DROP TRIGGER ifexists fullname */
106387 {
106388   sqlite3DropTrigger(pParse,yymsp[0].minor.yy259,yymsp[-1].minor.yy4);
106389 }
106390         break;
106391       case 301: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
106392 {
106393   sqlite3Attach(pParse, yymsp[-3].minor.yy118.pExpr, yymsp[-1].minor.yy118.pExpr, yymsp[0].minor.yy314);
106394 }
106395         break;
106396       case 302: /* cmd ::= DETACH database_kw_opt expr */
106397 {
106398   sqlite3Detach(pParse, yymsp[0].minor.yy118.pExpr);
106399 }
106400         break;
106401       case 307: /* cmd ::= REINDEX */
106402 {sqlite3Reindex(pParse, 0, 0);}
106403         break;
106404       case 308: /* cmd ::= REINDEX nm dbnm */
106405 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
106406         break;
106407       case 309: /* cmd ::= ANALYZE */
106408 {sqlite3Analyze(pParse, 0, 0);}
106409         break;
106410       case 310: /* cmd ::= ANALYZE nm dbnm */
106411 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
106412         break;
106413       case 311: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
106414 {
106415   sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy259,&yymsp[0].minor.yy0);
106416 }
106417         break;
106418       case 312: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
106419 {
106420   sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
106421 }
106422         break;
106423       case 313: /* add_column_fullname ::= fullname */
106424 {
106425   pParse->db->lookaside.bEnabled = 0;
106426   sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy259);
106427 }
106428         break;
106429       case 316: /* cmd ::= create_vtab */
106430 {sqlite3VtabFinishParse(pParse,0);}
106431         break;
106432       case 317: /* cmd ::= create_vtab LP vtabarglist RP */
106433 {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
106434         break;
106435       case 318: /* create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm */
106436 {
106437     sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);
106438 }
106439         break;
106440       case 321: /* vtabarg ::= */
106441 {sqlite3VtabArgInit(pParse);}
106442         break;
106443       case 323: /* vtabargtoken ::= ANY */
106444       case 324: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==324);
106445       case 325: /* lp ::= LP */ yytestcase(yyruleno==325);
106446 {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
106447         break;
106448       default:
106449       /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
106450       /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
106451       /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
106452       /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
106453       /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
106454       /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
106455       /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
106456       /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
106457       /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
106458       /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
106459       /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
106460       /* (34) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==34);
106461       /* (35) columnlist ::= column */ yytestcase(yyruleno==35);
106462       /* (44) type ::= */ yytestcase(yyruleno==44);
106463       /* (51) signed ::= plus_num */ yytestcase(yyruleno==51);
106464       /* (52) signed ::= minus_num */ yytestcase(yyruleno==52);
106465       /* (53) carglist ::= carglist carg */ yytestcase(yyruleno==53);
106466       /* (54) carglist ::= */ yytestcase(yyruleno==54);
106467       /* (55) carg ::= CONSTRAINT nm ccons */ yytestcase(yyruleno==55);
106468       /* (56) carg ::= ccons */ yytestcase(yyruleno==56);
106469       /* (62) ccons ::= NULL onconf */ yytestcase(yyruleno==62);
106470       /* (90) conslist ::= conslist COMMA tcons */ yytestcase(yyruleno==90);
106471       /* (91) conslist ::= conslist tcons */ yytestcase(yyruleno==91);
106472       /* (92) conslist ::= tcons */ yytestcase(yyruleno==92);
106473       /* (93) tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==93);
106474       /* (268) plus_opt ::= PLUS */ yytestcase(yyruleno==268);
106475       /* (269) plus_opt ::= */ yytestcase(yyruleno==269);
106476       /* (279) foreach_clause ::= */ yytestcase(yyruleno==279);
106477       /* (280) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==280);
106478       /* (287) tridxby ::= */ yytestcase(yyruleno==287);
106479       /* (305) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==305);
106480       /* (306) database_kw_opt ::= */ yytestcase(yyruleno==306);
106481       /* (314) kwcolumn_opt ::= */ yytestcase(yyruleno==314);
106482       /* (315) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==315);
106483       /* (319) vtabarglist ::= vtabarg */ yytestcase(yyruleno==319);
106484       /* (320) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==320);
106485       /* (322) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==322);
106486       /* (326) anylist ::= */ yytestcase(yyruleno==326);
106487       /* (327) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==327);
106488       /* (328) anylist ::= anylist ANY */ yytestcase(yyruleno==328);
106489         break;
106490   };
106491   yygoto = yyRuleInfo[yyruleno].lhs;
106492   yysize = yyRuleInfo[yyruleno].nrhs;
106493   yypParser->yyidx -= yysize;
106494   yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
106495   if( yyact < YYNSTATE ){
106496 #ifdef NDEBUG
106497     /* If we are not debugging and the reduce action popped at least
106498     ** one element off the stack, then we can push the new element back
106499     ** onto the stack here, and skip the stack overflow test in yy_shift().
106500     ** That gives a significant speed improvement. */
106501     if( yysize ){
106502       yypParser->yyidx++;
106503       yymsp -= yysize-1;
106504       yymsp->stateno = (YYACTIONTYPE)yyact;
106505       yymsp->major = (YYCODETYPE)yygoto;
106506       yymsp->minor = yygotominor;
106507     }else
106508 #endif
106509     {
106510       yy_shift(yypParser,yyact,yygoto,&yygotominor);
106511     }
106512   }else{
106513     assert( yyact == YYNSTATE + YYNRULE + 1 );
106514     yy_accept(yypParser);
106515   }
106516 }
106517
106518 /*
106519 ** The following code executes when the parse fails
106520 */
106521 #ifndef YYNOERRORRECOVERY
106522 static void yy_parse_failed(
106523   yyParser *yypParser           /* The parser */
106524 ){
106525   sqlite3ParserARG_FETCH;
106526 #ifndef NDEBUG
106527   if( yyTraceFILE ){
106528     fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
106529   }
106530 #endif
106531   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
106532   /* Here code is inserted which will be executed whenever the
106533   ** parser fails */
106534   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
106535 }
106536 #endif /* YYNOERRORRECOVERY */
106537
106538 /*
106539 ** The following code executes when a syntax error first occurs.
106540 */
106541 static void yy_syntax_error(
106542   yyParser *yypParser,           /* The parser */
106543   int yymajor,                   /* The major type of the error token */
106544   YYMINORTYPE yyminor            /* The minor type of the error token */
106545 ){
106546   sqlite3ParserARG_FETCH;
106547 #define TOKEN (yyminor.yy0)
106548
106549   UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
106550   assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
106551   sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
106552   pParse->parseError = 1;
106553   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
106554 }
106555
106556 /*
106557 ** The following is executed when the parser accepts
106558 */
106559 static void yy_accept(
106560   yyParser *yypParser           /* The parser */
106561 ){
106562   sqlite3ParserARG_FETCH;
106563 #ifndef NDEBUG
106564   if( yyTraceFILE ){
106565     fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
106566   }
106567 #endif
106568   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
106569   /* Here code is inserted which will be executed whenever the
106570   ** parser accepts */
106571   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
106572 }
106573
106574 /* The main parser program.
106575 ** The first argument is a pointer to a structure obtained from
106576 ** "sqlite3ParserAlloc" which describes the current state of the parser.
106577 ** The second argument is the major token number.  The third is
106578 ** the minor token.  The fourth optional argument is whatever the
106579 ** user wants (and specified in the grammar) and is available for
106580 ** use by the action routines.
106581 **
106582 ** Inputs:
106583 ** <ul>
106584 ** <li> A pointer to the parser (an opaque structure.)
106585 ** <li> The major token number.
106586 ** <li> The minor token number.
106587 ** <li> An option argument of a grammar-specified type.
106588 ** </ul>
106589 **
106590 ** Outputs:
106591 ** None.
106592 */
106593 SQLITE_PRIVATE void sqlite3Parser(
106594   void *yyp,                   /* The parser */
106595   int yymajor,                 /* The major token code number */
106596   sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
106597   sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
106598 ){
106599   YYMINORTYPE yyminorunion;
106600   int yyact;            /* The parser action. */
106601   int yyendofinput;     /* True if we are at the end of input */
106602 #ifdef YYERRORSYMBOL
106603   int yyerrorhit = 0;   /* True if yymajor has invoked an error */
106604 #endif
106605   yyParser *yypParser;  /* The parser */
106606
106607   /* (re)initialize the parser, if necessary */
106608   yypParser = (yyParser*)yyp;
106609   if( yypParser->yyidx<0 ){
106610 #if YYSTACKDEPTH<=0
106611     if( yypParser->yystksz <=0 ){
106612       /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
106613       yyminorunion = yyzerominor;
106614       yyStackOverflow(yypParser, &yyminorunion);
106615       return;
106616     }
106617 #endif
106618     yypParser->yyidx = 0;
106619     yypParser->yyerrcnt = -1;
106620     yypParser->yystack[0].stateno = 0;
106621     yypParser->yystack[0].major = 0;
106622   }
106623   yyminorunion.yy0 = yyminor;
106624   yyendofinput = (yymajor==0);
106625   sqlite3ParserARG_STORE;
106626
106627 #ifndef NDEBUG
106628   if( yyTraceFILE ){
106629     fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
106630   }
106631 #endif
106632
106633   do{
106634     yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
106635     if( yyact<YYNSTATE ){
106636       assert( !yyendofinput );  /* Impossible to shift the $ token */
106637       yy_shift(yypParser,yyact,yymajor,&yyminorunion);
106638       yypParser->yyerrcnt--;
106639       yymajor = YYNOCODE;
106640     }else if( yyact < YYNSTATE + YYNRULE ){
106641       yy_reduce(yypParser,yyact-YYNSTATE);
106642     }else{
106643       assert( yyact == YY_ERROR_ACTION );
106644 #ifdef YYERRORSYMBOL
106645       int yymx;
106646 #endif
106647 #ifndef NDEBUG
106648       if( yyTraceFILE ){
106649         fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
106650       }
106651 #endif
106652 #ifdef YYERRORSYMBOL
106653       /* A syntax error has occurred.
106654       ** The response to an error depends upon whether or not the
106655       ** grammar defines an error token "ERROR".  
106656       **
106657       ** This is what we do if the grammar does define ERROR:
106658       **
106659       **  * Call the %syntax_error function.
106660       **
106661       **  * Begin popping the stack until we enter a state where
106662       **    it is legal to shift the error symbol, then shift
106663       **    the error symbol.
106664       **
106665       **  * Set the error count to three.
106666       **
106667       **  * Begin accepting and shifting new tokens.  No new error
106668       **    processing will occur until three tokens have been
106669       **    shifted successfully.
106670       **
106671       */
106672       if( yypParser->yyerrcnt<0 ){
106673         yy_syntax_error(yypParser,yymajor,yyminorunion);
106674       }
106675       yymx = yypParser->yystack[yypParser->yyidx].major;
106676       if( yymx==YYERRORSYMBOL || yyerrorhit ){
106677 #ifndef NDEBUG
106678         if( yyTraceFILE ){
106679           fprintf(yyTraceFILE,"%sDiscard input token %s\n",
106680              yyTracePrompt,yyTokenName[yymajor]);
106681         }
106682 #endif
106683         yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
106684         yymajor = YYNOCODE;
106685       }else{
106686          while(
106687           yypParser->yyidx >= 0 &&
106688           yymx != YYERRORSYMBOL &&
106689           (yyact = yy_find_reduce_action(
106690                         yypParser->yystack[yypParser->yyidx].stateno,
106691                         YYERRORSYMBOL)) >= YYNSTATE
106692         ){
106693           yy_pop_parser_stack(yypParser);
106694         }
106695         if( yypParser->yyidx < 0 || yymajor==0 ){
106696           yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
106697           yy_parse_failed(yypParser);
106698           yymajor = YYNOCODE;
106699         }else if( yymx!=YYERRORSYMBOL ){
106700           YYMINORTYPE u2;
106701           u2.YYERRSYMDT = 0;
106702           yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
106703         }
106704       }
106705       yypParser->yyerrcnt = 3;
106706       yyerrorhit = 1;
106707 #elif defined(YYNOERRORRECOVERY)
106708       /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
106709       ** do any kind of error recovery.  Instead, simply invoke the syntax
106710       ** error routine and continue going as if nothing had happened.
106711       **
106712       ** Applications can set this macro (for example inside %include) if
106713       ** they intend to abandon the parse upon the first syntax error seen.
106714       */
106715       yy_syntax_error(yypParser,yymajor,yyminorunion);
106716       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
106717       yymajor = YYNOCODE;
106718       
106719 #else  /* YYERRORSYMBOL is not defined */
106720       /* This is what we do if the grammar does not define ERROR:
106721       **
106722       **  * Report an error message, and throw away the input token.
106723       **
106724       **  * If the input token is $, then fail the parse.
106725       **
106726       ** As before, subsequent error messages are suppressed until
106727       ** three input tokens have been successfully shifted.
106728       */
106729       if( yypParser->yyerrcnt<=0 ){
106730         yy_syntax_error(yypParser,yymajor,yyminorunion);
106731       }
106732       yypParser->yyerrcnt = 3;
106733       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
106734       if( yyendofinput ){
106735         yy_parse_failed(yypParser);
106736       }
106737       yymajor = YYNOCODE;
106738 #endif
106739     }
106740   }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
106741   return;
106742 }
106743
106744 /************** End of parse.c ***********************************************/
106745 /************** Begin file tokenize.c ****************************************/
106746 /*
106747 ** 2001 September 15
106748 **
106749 ** The author disclaims copyright to this source code.  In place of
106750 ** a legal notice, here is a blessing:
106751 **
106752 **    May you do good and not evil.
106753 **    May you find forgiveness for yourself and forgive others.
106754 **    May you share freely, never taking more than you give.
106755 **
106756 *************************************************************************
106757 ** An tokenizer for SQL
106758 **
106759 ** This file contains C code that splits an SQL input string up into
106760 ** individual tokens and sends those tokens one-by-one over to the
106761 ** parser for analysis.
106762 */
106763
106764 /*
106765 ** The charMap() macro maps alphabetic characters into their
106766 ** lower-case ASCII equivalent.  On ASCII machines, this is just
106767 ** an upper-to-lower case map.  On EBCDIC machines we also need
106768 ** to adjust the encoding.  Only alphabetic characters and underscores
106769 ** need to be translated.
106770 */
106771 #ifdef SQLITE_ASCII
106772 # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
106773 #endif
106774 #ifdef SQLITE_EBCDIC
106775 # define charMap(X) ebcdicToAscii[(unsigned char)X]
106776 const unsigned char ebcdicToAscii[] = {
106777 /* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
106778    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
106779    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
106780    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
106781    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
106782    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
106783    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
106784    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
106785    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
106786    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
106787    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
106788    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
106789    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
106790    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
106791    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
106792    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
106793    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
106794 };
106795 #endif
106796
106797 /*
106798 ** The sqlite3KeywordCode function looks up an identifier to determine if
106799 ** it is a keyword.  If it is a keyword, the token code of that keyword is 
106800 ** returned.  If the input is not a keyword, TK_ID is returned.
106801 **
106802 ** The implementation of this routine was generated by a program,
106803 ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
106804 ** The output of the mkkeywordhash.c program is written into a file
106805 ** named keywordhash.h and then included into this source file by
106806 ** the #include below.
106807 */
106808 /************** Include keywordhash.h in the middle of tokenize.c ************/
106809 /************** Begin file keywordhash.h *************************************/
106810 /***** This file contains automatically generated code ******
106811 **
106812 ** The code in this file has been automatically generated by
106813 **
106814 **   sqlite/tool/mkkeywordhash.c
106815 **
106816 ** The code in this file implements a function that determines whether
106817 ** or not a given identifier is really an SQL keyword.  The same thing
106818 ** might be implemented more directly using a hand-written hash table.
106819 ** But by using this automatically generated code, the size of the code
106820 ** is substantially reduced.  This is important for embedded applications
106821 ** on platforms with limited memory.
106822 */
106823 /* Hash score: 175 */
106824 static int keywordCode(const char *z, int n){
106825   /* zText[] encodes 811 bytes of keywords in 541 bytes */
106826   /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
106827   /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
106828   /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
106829   /*   UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE          */
106830   /*   CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN        */
106831   /*   SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME         */
106832   /*   AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS     */
106833   /*   CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF      */
106834   /*   ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW         */
106835   /*   INITIALLY                                                          */
106836   static const char zText[540] = {
106837     'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
106838     'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
106839     'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
106840     'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
106841     'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
106842     'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
106843     'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
106844     'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
106845     'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
106846     'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
106847     'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
106848     'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
106849     'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
106850     'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
106851     'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
106852     'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
106853     'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
106854     'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
106855     'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
106856     'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
106857     'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
106858     'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
106859     'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
106860     'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
106861     'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
106862     'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
106863     'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
106864     'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
106865     'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
106866     'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
106867   };
106868   static const unsigned char aHash[127] = {
106869       72, 101, 114,  70,   0,  45,   0,   0,  78,   0,  73,   0,   0,
106870       42,  12,  74,  15,   0, 113,  81,  50, 108,   0,  19,   0,   0,
106871      118,   0, 116, 111,   0,  22,  89,   0,   9,   0,   0,  66,  67,
106872        0,  65,   6,   0,  48,  86,  98,   0, 115,  97,   0,   0,  44,
106873        0,  99,  24,   0,  17,   0, 119,  49,  23,   0,   5, 106,  25,
106874       92,   0,   0, 121, 102,  56, 120,  53,  28,  51,   0,  87,   0,
106875       96,  26,   0,  95,   0,   0,   0,  91,  88,  93,  84, 105,  14,
106876       39, 104,   0,  77,   0,  18,  85, 107,  32,   0, 117,  76, 109,
106877       58,  46,  80,   0,   0,  90,  40,   0, 112,   0,  36,   0,   0,
106878       29,   0,  82,  59,  60,   0,  20,  57,   0,  52,
106879   };
106880   static const unsigned char aNext[121] = {
106881        0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
106882        0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
106883        0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
106884        0,   0,   0,   0,  33,   0,  21,   0,   0,   0,  43,   3,  47,
106885        0,   0,   0,   0,  30,   0,  54,   0,  38,   0,   0,   0,   1,
106886       62,   0,   0,  63,   0,  41,   0,   0,   0,   0,   0,   0,   0,
106887       61,   0,   0,   0,   0,  31,  55,  16,  34,  10,   0,   0,   0,
106888        0,   0,   0,   0,  11,  68,  75,   0,   8,   0, 100,  94,   0,
106889      103,   0,  83,   0,  71,   0,   0, 110,  27,  37,  69,  79,   0,
106890       35,  64,   0,   0,
106891   };
106892   static const unsigned char aLen[121] = {
106893        7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
106894        7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
106895       11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
106896        4,   6,   2,   3,   9,   4,   2,   6,   5,   6,   6,   5,   6,
106897        5,   5,   7,   7,   7,   3,   2,   4,   4,   7,   3,   6,   4,
106898        7,   6,  12,   6,   9,   4,   6,   5,   4,   7,   6,   5,   6,
106899        7,   5,   4,   5,   6,   5,   7,   3,   7,  13,   2,   2,   4,
106900        6,   6,   8,   5,  17,  12,   7,   8,   8,   2,   4,   4,   4,
106901        4,   4,   2,   2,   6,   5,   8,   5,   5,   8,   3,   5,   5,
106902        6,   4,   9,   3,
106903   };
106904   static const unsigned short int aOffset[121] = {
106905        0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
106906       36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
106907       86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
106908      159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197,
106909      203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244,
106910      248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320,
106911      326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383,
106912      387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458,
106913      462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516,
106914      521, 527, 531, 536,
106915   };
106916   static const unsigned char aCode[121] = {
106917     TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,     
106918     TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,    
106919     TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,    
106920     TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,      
106921     TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,       
106922     TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,    
106923     TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,  
106924     TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,       
106925     TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,       
106926     TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_ATTACH,     TK_HAVING,     
106927     TK_GROUP,      TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RELEASE,    
106928     TK_BETWEEN,    TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,       
106929     TK_LIKE_KW,    TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,       
106930     TK_COLLATE,    TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,  
106931     TK_JOIN,       TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,    
106932     TK_PRAGMA,     TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,      
106933     TK_WHEN,       TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,    
106934     TK_AND,        TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,         
106935     TK_CAST,       TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,    
106936     TK_CTIME_KW,   TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,   
106937     TK_IS,         TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,    
106938     TK_LIKE_KW,    TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,      
106939     TK_RESTRICT,   TK_JOIN_KW,    TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,        
106940     TK_UNION,      TK_USING,      TK_VACUUM,     TK_VIEW,       TK_INITIALLY,  
106941     TK_ALL,        
106942   };
106943   int h, i;
106944   if( n<2 ) return TK_ID;
106945   h = ((charMap(z[0])*4) ^
106946       (charMap(z[n-1])*3) ^
106947       n) % 127;
106948   for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
106949     if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
106950       testcase( i==0 ); /* REINDEX */
106951       testcase( i==1 ); /* INDEXED */
106952       testcase( i==2 ); /* INDEX */
106953       testcase( i==3 ); /* DESC */
106954       testcase( i==4 ); /* ESCAPE */
106955       testcase( i==5 ); /* EACH */
106956       testcase( i==6 ); /* CHECK */
106957       testcase( i==7 ); /* KEY */
106958       testcase( i==8 ); /* BEFORE */
106959       testcase( i==9 ); /* FOREIGN */
106960       testcase( i==10 ); /* FOR */
106961       testcase( i==11 ); /* IGNORE */
106962       testcase( i==12 ); /* REGEXP */
106963       testcase( i==13 ); /* EXPLAIN */
106964       testcase( i==14 ); /* INSTEAD */
106965       testcase( i==15 ); /* ADD */
106966       testcase( i==16 ); /* DATABASE */
106967       testcase( i==17 ); /* AS */
106968       testcase( i==18 ); /* SELECT */
106969       testcase( i==19 ); /* TABLE */
106970       testcase( i==20 ); /* LEFT */
106971       testcase( i==21 ); /* THEN */
106972       testcase( i==22 ); /* END */
106973       testcase( i==23 ); /* DEFERRABLE */
106974       testcase( i==24 ); /* ELSE */
106975       testcase( i==25 ); /* EXCEPT */
106976       testcase( i==26 ); /* TRANSACTION */
106977       testcase( i==27 ); /* ACTION */
106978       testcase( i==28 ); /* ON */
106979       testcase( i==29 ); /* NATURAL */
106980       testcase( i==30 ); /* ALTER */
106981       testcase( i==31 ); /* RAISE */
106982       testcase( i==32 ); /* EXCLUSIVE */
106983       testcase( i==33 ); /* EXISTS */
106984       testcase( i==34 ); /* SAVEPOINT */
106985       testcase( i==35 ); /* INTERSECT */
106986       testcase( i==36 ); /* TRIGGER */
106987       testcase( i==37 ); /* REFERENCES */
106988       testcase( i==38 ); /* CONSTRAINT */
106989       testcase( i==39 ); /* INTO */
106990       testcase( i==40 ); /* OFFSET */
106991       testcase( i==41 ); /* OF */
106992       testcase( i==42 ); /* SET */
106993       testcase( i==43 ); /* TEMPORARY */
106994       testcase( i==44 ); /* TEMP */
106995       testcase( i==45 ); /* OR */
106996       testcase( i==46 ); /* UNIQUE */
106997       testcase( i==47 ); /* QUERY */
106998       testcase( i==48 ); /* ATTACH */
106999       testcase( i==49 ); /* HAVING */
107000       testcase( i==50 ); /* GROUP */
107001       testcase( i==51 ); /* UPDATE */
107002       testcase( i==52 ); /* BEGIN */
107003       testcase( i==53 ); /* INNER */
107004       testcase( i==54 ); /* RELEASE */
107005       testcase( i==55 ); /* BETWEEN */
107006       testcase( i==56 ); /* NOTNULL */
107007       testcase( i==57 ); /* NOT */
107008       testcase( i==58 ); /* NO */
107009       testcase( i==59 ); /* NULL */
107010       testcase( i==60 ); /* LIKE */
107011       testcase( i==61 ); /* CASCADE */
107012       testcase( i==62 ); /* ASC */
107013       testcase( i==63 ); /* DELETE */
107014       testcase( i==64 ); /* CASE */
107015       testcase( i==65 ); /* COLLATE */
107016       testcase( i==66 ); /* CREATE */
107017       testcase( i==67 ); /* CURRENT_DATE */
107018       testcase( i==68 ); /* DETACH */
107019       testcase( i==69 ); /* IMMEDIATE */
107020       testcase( i==70 ); /* JOIN */
107021       testcase( i==71 ); /* INSERT */
107022       testcase( i==72 ); /* MATCH */
107023       testcase( i==73 ); /* PLAN */
107024       testcase( i==74 ); /* ANALYZE */
107025       testcase( i==75 ); /* PRAGMA */
107026       testcase( i==76 ); /* ABORT */
107027       testcase( i==77 ); /* VALUES */
107028       testcase( i==78 ); /* VIRTUAL */
107029       testcase( i==79 ); /* LIMIT */
107030       testcase( i==80 ); /* WHEN */
107031       testcase( i==81 ); /* WHERE */
107032       testcase( i==82 ); /* RENAME */
107033       testcase( i==83 ); /* AFTER */
107034       testcase( i==84 ); /* REPLACE */
107035       testcase( i==85 ); /* AND */
107036       testcase( i==86 ); /* DEFAULT */
107037       testcase( i==87 ); /* AUTOINCREMENT */
107038       testcase( i==88 ); /* TO */
107039       testcase( i==89 ); /* IN */
107040       testcase( i==90 ); /* CAST */
107041       testcase( i==91 ); /* COLUMN */
107042       testcase( i==92 ); /* COMMIT */
107043       testcase( i==93 ); /* CONFLICT */
107044       testcase( i==94 ); /* CROSS */
107045       testcase( i==95 ); /* CURRENT_TIMESTAMP */
107046       testcase( i==96 ); /* CURRENT_TIME */
107047       testcase( i==97 ); /* PRIMARY */
107048       testcase( i==98 ); /* DEFERRED */
107049       testcase( i==99 ); /* DISTINCT */
107050       testcase( i==100 ); /* IS */
107051       testcase( i==101 ); /* DROP */
107052       testcase( i==102 ); /* FAIL */
107053       testcase( i==103 ); /* FROM */
107054       testcase( i==104 ); /* FULL */
107055       testcase( i==105 ); /* GLOB */
107056       testcase( i==106 ); /* BY */
107057       testcase( i==107 ); /* IF */
107058       testcase( i==108 ); /* ISNULL */
107059       testcase( i==109 ); /* ORDER */
107060       testcase( i==110 ); /* RESTRICT */
107061       testcase( i==111 ); /* OUTER */
107062       testcase( i==112 ); /* RIGHT */
107063       testcase( i==113 ); /* ROLLBACK */
107064       testcase( i==114 ); /* ROW */
107065       testcase( i==115 ); /* UNION */
107066       testcase( i==116 ); /* USING */
107067       testcase( i==117 ); /* VACUUM */
107068       testcase( i==118 ); /* VIEW */
107069       testcase( i==119 ); /* INITIALLY */
107070       testcase( i==120 ); /* ALL */
107071       return aCode[i];
107072     }
107073   }
107074   return TK_ID;
107075 }
107076 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
107077   return keywordCode((char*)z, n);
107078 }
107079 #define SQLITE_N_KEYWORD 121
107080
107081 /************** End of keywordhash.h *****************************************/
107082 /************** Continuing where we left off in tokenize.c *******************/
107083
107084
107085 /*
107086 ** If X is a character that can be used in an identifier then
107087 ** IdChar(X) will be true.  Otherwise it is false.
107088 **
107089 ** For ASCII, any character with the high-order bit set is
107090 ** allowed in an identifier.  For 7-bit characters, 
107091 ** sqlite3IsIdChar[X] must be 1.
107092 **
107093 ** For EBCDIC, the rules are more complex but have the same
107094 ** end result.
107095 **
107096 ** Ticket #1066.  the SQL standard does not allow '$' in the
107097 ** middle of identfiers.  But many SQL implementations do. 
107098 ** SQLite will allow '$' in identifiers for compatibility.
107099 ** But the feature is undocumented.
107100 */
107101 #ifdef SQLITE_ASCII
107102 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
107103 #endif
107104 #ifdef SQLITE_EBCDIC
107105 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
107106 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
107107     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
107108     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
107109     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
107110     0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
107111     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
107112     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
107113     1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
107114     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
107115     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
107116     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
107117     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
107118     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
107119 };
107120 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
107121 #endif
107122
107123
107124 /*
107125 ** Return the length of the token that begins at z[0]. 
107126 ** Store the token type in *tokenType before returning.
107127 */
107128 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
107129   int i, c;
107130   switch( *z ){
107131     case ' ': case '\t': case '\n': case '\f': case '\r': {
107132       testcase( z[0]==' ' );
107133       testcase( z[0]=='\t' );
107134       testcase( z[0]=='\n' );
107135       testcase( z[0]=='\f' );
107136       testcase( z[0]=='\r' );
107137       for(i=1; sqlite3Isspace(z[i]); i++){}
107138       *tokenType = TK_SPACE;
107139       return i;
107140     }
107141     case '-': {
107142       if( z[1]=='-' ){
107143         /* IMP: R-15891-05542 -- syntax diagram for comments */
107144         for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
107145         *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
107146         return i;
107147       }
107148       *tokenType = TK_MINUS;
107149       return 1;
107150     }
107151     case '(': {
107152       *tokenType = TK_LP;
107153       return 1;
107154     }
107155     case ')': {
107156       *tokenType = TK_RP;
107157       return 1;
107158     }
107159     case ';': {
107160       *tokenType = TK_SEMI;
107161       return 1;
107162     }
107163     case '+': {
107164       *tokenType = TK_PLUS;
107165       return 1;
107166     }
107167     case '*': {
107168       *tokenType = TK_STAR;
107169       return 1;
107170     }
107171     case '/': {
107172       if( z[1]!='*' || z[2]==0 ){
107173         *tokenType = TK_SLASH;
107174         return 1;
107175       }
107176       /* IMP: R-15891-05542 -- syntax diagram for comments */
107177       for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
107178       if( c ) i++;
107179       *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
107180       return i;
107181     }
107182     case '%': {
107183       *tokenType = TK_REM;
107184       return 1;
107185     }
107186     case '=': {
107187       *tokenType = TK_EQ;
107188       return 1 + (z[1]=='=');
107189     }
107190     case '<': {
107191       if( (c=z[1])=='=' ){
107192         *tokenType = TK_LE;
107193         return 2;
107194       }else if( c=='>' ){
107195         *tokenType = TK_NE;
107196         return 2;
107197       }else if( c=='<' ){
107198         *tokenType = TK_LSHIFT;
107199         return 2;
107200       }else{
107201         *tokenType = TK_LT;
107202         return 1;
107203       }
107204     }
107205     case '>': {
107206       if( (c=z[1])=='=' ){
107207         *tokenType = TK_GE;
107208         return 2;
107209       }else if( c=='>' ){
107210         *tokenType = TK_RSHIFT;
107211         return 2;
107212       }else{
107213         *tokenType = TK_GT;
107214         return 1;
107215       }
107216     }
107217     case '!': {
107218       if( z[1]!='=' ){
107219         *tokenType = TK_ILLEGAL;
107220         return 2;
107221       }else{
107222         *tokenType = TK_NE;
107223         return 2;
107224       }
107225     }
107226     case '|': {
107227       if( z[1]!='|' ){
107228         *tokenType = TK_BITOR;
107229         return 1;
107230       }else{
107231         *tokenType = TK_CONCAT;
107232         return 2;
107233       }
107234     }
107235     case ',': {
107236       *tokenType = TK_COMMA;
107237       return 1;
107238     }
107239     case '&': {
107240       *tokenType = TK_BITAND;
107241       return 1;
107242     }
107243     case '~': {
107244       *tokenType = TK_BITNOT;
107245       return 1;
107246     }
107247     case '`':
107248     case '\'':
107249     case '"': {
107250       int delim = z[0];
107251       testcase( delim=='`' );
107252       testcase( delim=='\'' );
107253       testcase( delim=='"' );
107254       for(i=1; (c=z[i])!=0; i++){
107255         if( c==delim ){
107256           if( z[i+1]==delim ){
107257             i++;
107258           }else{
107259             break;
107260           }
107261         }
107262       }
107263       if( c=='\'' ){
107264         *tokenType = TK_STRING;
107265         return i+1;
107266       }else if( c!=0 ){
107267         *tokenType = TK_ID;
107268         return i+1;
107269       }else{
107270         *tokenType = TK_ILLEGAL;
107271         return i;
107272       }
107273     }
107274     case '.': {
107275 #ifndef SQLITE_OMIT_FLOATING_POINT
107276       if( !sqlite3Isdigit(z[1]) )
107277 #endif
107278       {
107279         *tokenType = TK_DOT;
107280         return 1;
107281       }
107282       /* If the next character is a digit, this is a floating point
107283       ** number that begins with ".".  Fall thru into the next case */
107284     }
107285     case '0': case '1': case '2': case '3': case '4':
107286     case '5': case '6': case '7': case '8': case '9': {
107287       testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
107288       testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
107289       testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
107290       testcase( z[0]=='9' );
107291       *tokenType = TK_INTEGER;
107292       for(i=0; sqlite3Isdigit(z[i]); i++){}
107293 #ifndef SQLITE_OMIT_FLOATING_POINT
107294       if( z[i]=='.' ){
107295         i++;
107296         while( sqlite3Isdigit(z[i]) ){ i++; }
107297         *tokenType = TK_FLOAT;
107298       }
107299       if( (z[i]=='e' || z[i]=='E') &&
107300            ( sqlite3Isdigit(z[i+1]) 
107301             || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
107302            )
107303       ){
107304         i += 2;
107305         while( sqlite3Isdigit(z[i]) ){ i++; }
107306         *tokenType = TK_FLOAT;
107307       }
107308 #endif
107309       while( IdChar(z[i]) ){
107310         *tokenType = TK_ILLEGAL;
107311         i++;
107312       }
107313       return i;
107314     }
107315     case '[': {
107316       for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
107317       *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
107318       return i;
107319     }
107320     case '?': {
107321       *tokenType = TK_VARIABLE;
107322       for(i=1; sqlite3Isdigit(z[i]); i++){}
107323       return i;
107324     }
107325     case '#': {
107326       for(i=1; sqlite3Isdigit(z[i]); i++){}
107327       if( i>1 ){
107328         /* Parameters of the form #NNN (where NNN is a number) are used
107329         ** internally by sqlite3NestedParse.  */
107330         *tokenType = TK_REGISTER;
107331         return i;
107332       }
107333       /* Fall through into the next case if the '#' is not followed by
107334       ** a digit. Try to match #AAAA where AAAA is a parameter name. */
107335     }
107336 #ifndef SQLITE_OMIT_TCL_VARIABLE
107337     case '$':
107338 #endif
107339     case '@':  /* For compatibility with MS SQL Server */
107340     case ':': {
107341       int n = 0;
107342       testcase( z[0]=='$' );  testcase( z[0]=='@' );  testcase( z[0]==':' );
107343       *tokenType = TK_VARIABLE;
107344       for(i=1; (c=z[i])!=0; i++){
107345         if( IdChar(c) ){
107346           n++;
107347 #ifndef SQLITE_OMIT_TCL_VARIABLE
107348         }else if( c=='(' && n>0 ){
107349           do{
107350             i++;
107351           }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
107352           if( c==')' ){
107353             i++;
107354           }else{
107355             *tokenType = TK_ILLEGAL;
107356           }
107357           break;
107358         }else if( c==':' && z[i+1]==':' ){
107359           i++;
107360 #endif
107361         }else{
107362           break;
107363         }
107364       }
107365       if( n==0 ) *tokenType = TK_ILLEGAL;
107366       return i;
107367     }
107368 #ifndef SQLITE_OMIT_BLOB_LITERAL
107369     case 'x': case 'X': {
107370       testcase( z[0]=='x' ); testcase( z[0]=='X' );
107371       if( z[1]=='\'' ){
107372         *tokenType = TK_BLOB;
107373         for(i=2; sqlite3Isxdigit(z[i]); i++){}
107374         if( z[i]!='\'' || i%2 ){
107375           *tokenType = TK_ILLEGAL;
107376           while( z[i] && z[i]!='\'' ){ i++; }
107377         }
107378         if( z[i] ) i++;
107379         return i;
107380       }
107381       /* Otherwise fall through to the next case */
107382     }
107383 #endif
107384     default: {
107385       if( !IdChar(*z) ){
107386         break;
107387       }
107388       for(i=1; IdChar(z[i]); i++){}
107389       *tokenType = keywordCode((char*)z, i);
107390       return i;
107391     }
107392   }
107393   *tokenType = TK_ILLEGAL;
107394   return 1;
107395 }
107396
107397 /*
107398 ** Run the parser on the given SQL string.  The parser structure is
107399 ** passed in.  An SQLITE_ status code is returned.  If an error occurs
107400 ** then an and attempt is made to write an error message into 
107401 ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
107402 ** error message.
107403 */
107404 SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
107405   int nErr = 0;                   /* Number of errors encountered */
107406   int i;                          /* Loop counter */
107407   void *pEngine;                  /* The LEMON-generated LALR(1) parser */
107408   int tokenType;                  /* type of the next token */
107409   int lastTokenParsed = -1;       /* type of the previous token */
107410   u8 enableLookaside;             /* Saved value of db->lookaside.bEnabled */
107411   sqlite3 *db = pParse->db;       /* The database connection */
107412   int mxSqlLen;                   /* Max length of an SQL string */
107413
107414
107415   mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
107416   if( db->activeVdbeCnt==0 ){
107417     db->u1.isInterrupted = 0;
107418   }
107419   pParse->rc = SQLITE_OK;
107420   pParse->zTail = zSql;
107421   i = 0;
107422   assert( pzErrMsg!=0 );
107423   pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
107424   if( pEngine==0 ){
107425     db->mallocFailed = 1;
107426     return SQLITE_NOMEM;
107427   }
107428   assert( pParse->pNewTable==0 );
107429   assert( pParse->pNewTrigger==0 );
107430   assert( pParse->nVar==0 );
107431   assert( pParse->nzVar==0 );
107432   assert( pParse->azVar==0 );
107433   enableLookaside = db->lookaside.bEnabled;
107434   if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
107435   while( !db->mallocFailed && zSql[i]!=0 ){
107436     assert( i>=0 );
107437     pParse->sLastToken.z = &zSql[i];
107438     pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
107439     i += pParse->sLastToken.n;
107440     if( i>mxSqlLen ){
107441       pParse->rc = SQLITE_TOOBIG;
107442       break;
107443     }
107444     switch( tokenType ){
107445       case TK_SPACE: {
107446         if( db->u1.isInterrupted ){
107447           sqlite3ErrorMsg(pParse, "interrupt");
107448           pParse->rc = SQLITE_INTERRUPT;
107449           goto abort_parse;
107450         }
107451         break;
107452       }
107453       case TK_ILLEGAL: {
107454         sqlite3DbFree(db, *pzErrMsg);
107455         *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
107456                         &pParse->sLastToken);
107457         nErr++;
107458         goto abort_parse;
107459       }
107460       case TK_SEMI: {
107461         pParse->zTail = &zSql[i];
107462         /* Fall thru into the default case */
107463       }
107464       default: {
107465         sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
107466         lastTokenParsed = tokenType;
107467         if( pParse->rc!=SQLITE_OK ){
107468           goto abort_parse;
107469         }
107470         break;
107471       }
107472     }
107473   }
107474 abort_parse:
107475   if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
107476     if( lastTokenParsed!=TK_SEMI ){
107477       sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
107478       pParse->zTail = &zSql[i];
107479     }
107480     sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
107481   }
107482 #ifdef YYTRACKMAXSTACKDEPTH
107483   sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
107484       sqlite3ParserStackPeak(pEngine)
107485   );
107486 #endif /* YYDEBUG */
107487   sqlite3ParserFree(pEngine, sqlite3_free);
107488   db->lookaside.bEnabled = enableLookaside;
107489   if( db->mallocFailed ){
107490     pParse->rc = SQLITE_NOMEM;
107491   }
107492   if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
107493     sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
107494   }
107495   assert( pzErrMsg!=0 );
107496   if( pParse->zErrMsg ){
107497     *pzErrMsg = pParse->zErrMsg;
107498     sqlite3_log(pParse->rc, "%s", *pzErrMsg);
107499     pParse->zErrMsg = 0;
107500     nErr++;
107501   }
107502   if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
107503     sqlite3VdbeDelete(pParse->pVdbe);
107504     pParse->pVdbe = 0;
107505   }
107506 #ifndef SQLITE_OMIT_SHARED_CACHE
107507   if( pParse->nested==0 ){
107508     sqlite3DbFree(db, pParse->aTableLock);
107509     pParse->aTableLock = 0;
107510     pParse->nTableLock = 0;
107511   }
107512 #endif
107513 #ifndef SQLITE_OMIT_VIRTUALTABLE
107514   sqlite3_free(pParse->apVtabLock);
107515 #endif
107516
107517   if( !IN_DECLARE_VTAB ){
107518     /* If the pParse->declareVtab flag is set, do not delete any table 
107519     ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
107520     ** will take responsibility for freeing the Table structure.
107521     */
107522     sqlite3DeleteTable(db, pParse->pNewTable);
107523   }
107524
107525   sqlite3DeleteTrigger(db, pParse->pNewTrigger);
107526   for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
107527   sqlite3DbFree(db, pParse->azVar);
107528   sqlite3DbFree(db, pParse->aAlias);
107529   while( pParse->pAinc ){
107530     AutoincInfo *p = pParse->pAinc;
107531     pParse->pAinc = p->pNext;
107532     sqlite3DbFree(db, p);
107533   }
107534   while( pParse->pZombieTab ){
107535     Table *p = pParse->pZombieTab;
107536     pParse->pZombieTab = p->pNextZombie;
107537     sqlite3DeleteTable(db, p);
107538   }
107539   if( nErr>0 && pParse->rc==SQLITE_OK ){
107540     pParse->rc = SQLITE_ERROR;
107541   }
107542   return nErr;
107543 }
107544
107545 /************** End of tokenize.c ********************************************/
107546 /************** Begin file complete.c ****************************************/
107547 /*
107548 ** 2001 September 15
107549 **
107550 ** The author disclaims copyright to this source code.  In place of
107551 ** a legal notice, here is a blessing:
107552 **
107553 **    May you do good and not evil.
107554 **    May you find forgiveness for yourself and forgive others.
107555 **    May you share freely, never taking more than you give.
107556 **
107557 *************************************************************************
107558 ** An tokenizer for SQL
107559 **
107560 ** This file contains C code that implements the sqlite3_complete() API.
107561 ** This code used to be part of the tokenizer.c source file.  But by
107562 ** separating it out, the code will be automatically omitted from
107563 ** static links that do not use it.
107564 */
107565 #ifndef SQLITE_OMIT_COMPLETE
107566
107567 /*
107568 ** This is defined in tokenize.c.  We just have to import the definition.
107569 */
107570 #ifndef SQLITE_AMALGAMATION
107571 #ifdef SQLITE_ASCII
107572 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
107573 #endif
107574 #ifdef SQLITE_EBCDIC
107575 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
107576 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
107577 #endif
107578 #endif /* SQLITE_AMALGAMATION */
107579
107580
107581 /*
107582 ** Token types used by the sqlite3_complete() routine.  See the header
107583 ** comments on that procedure for additional information.
107584 */
107585 #define tkSEMI    0
107586 #define tkWS      1
107587 #define tkOTHER   2
107588 #ifndef SQLITE_OMIT_TRIGGER
107589 #define tkEXPLAIN 3
107590 #define tkCREATE  4
107591 #define tkTEMP    5
107592 #define tkTRIGGER 6
107593 #define tkEND     7
107594 #endif
107595
107596 /*
107597 ** Return TRUE if the given SQL string ends in a semicolon.
107598 **
107599 ** Special handling is require for CREATE TRIGGER statements.
107600 ** Whenever the CREATE TRIGGER keywords are seen, the statement
107601 ** must end with ";END;".
107602 **
107603 ** This implementation uses a state machine with 8 states:
107604 **
107605 **   (0) INVALID   We have not yet seen a non-whitespace character.
107606 **
107607 **   (1) START     At the beginning or end of an SQL statement.  This routine
107608 **                 returns 1 if it ends in the START state and 0 if it ends
107609 **                 in any other state.
107610 **
107611 **   (2) NORMAL    We are in the middle of statement which ends with a single
107612 **                 semicolon.
107613 **
107614 **   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of 
107615 **                 a statement.
107616 **
107617 **   (4) CREATE    The keyword CREATE has been seen at the beginning of a
107618 **                 statement, possibly preceeded by EXPLAIN and/or followed by
107619 **                 TEMP or TEMPORARY
107620 **
107621 **   (5) TRIGGER   We are in the middle of a trigger definition that must be
107622 **                 ended by a semicolon, the keyword END, and another semicolon.
107623 **
107624 **   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
107625 **                 the end of a trigger definition.
107626 **
107627 **   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
107628 **                 of a trigger difinition.
107629 **
107630 ** Transitions between states above are determined by tokens extracted
107631 ** from the input.  The following tokens are significant:
107632 **
107633 **   (0) tkSEMI      A semicolon.
107634 **   (1) tkWS        Whitespace.
107635 **   (2) tkOTHER     Any other SQL token.
107636 **   (3) tkEXPLAIN   The "explain" keyword.
107637 **   (4) tkCREATE    The "create" keyword.
107638 **   (5) tkTEMP      The "temp" or "temporary" keyword.
107639 **   (6) tkTRIGGER   The "trigger" keyword.
107640 **   (7) tkEND       The "end" keyword.
107641 **
107642 ** Whitespace never causes a state transition and is always ignored.
107643 ** This means that a SQL string of all whitespace is invalid.
107644 **
107645 ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
107646 ** to recognize the end of a trigger can be omitted.  All we have to do
107647 ** is look for a semicolon that is not part of an string or comment.
107648 */
107649 SQLITE_API int sqlite3_complete(const char *zSql){
107650   u8 state = 0;   /* Current state, using numbers defined in header comment */
107651   u8 token;       /* Value of the next token */
107652
107653 #ifndef SQLITE_OMIT_TRIGGER
107654   /* A complex statement machine used to detect the end of a CREATE TRIGGER
107655   ** statement.  This is the normal case.
107656   */
107657   static const u8 trans[8][8] = {
107658                      /* Token:                                                */
107659      /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
107660      /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
107661      /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
107662      /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
107663      /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
107664      /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
107665      /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
107666      /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
107667      /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
107668   };
107669 #else
107670   /* If triggers are not supported by this compile then the statement machine
107671   ** used to detect the end of a statement is much simplier
107672   */
107673   static const u8 trans[3][3] = {
107674                      /* Token:           */
107675      /* State:       **  SEMI  WS  OTHER */
107676      /* 0 INVALID: */ {    1,  0,     2, },
107677      /* 1   START: */ {    1,  1,     2, },
107678      /* 2  NORMAL: */ {    1,  2,     2, },
107679   };
107680 #endif /* SQLITE_OMIT_TRIGGER */
107681
107682   while( *zSql ){
107683     switch( *zSql ){
107684       case ';': {  /* A semicolon */
107685         token = tkSEMI;
107686         break;
107687       }
107688       case ' ':
107689       case '\r':
107690       case '\t':
107691       case '\n':
107692       case '\f': {  /* White space is ignored */
107693         token = tkWS;
107694         break;
107695       }
107696       case '/': {   /* C-style comments */
107697         if( zSql[1]!='*' ){
107698           token = tkOTHER;
107699           break;
107700         }
107701         zSql += 2;
107702         while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
107703         if( zSql[0]==0 ) return 0;
107704         zSql++;
107705         token = tkWS;
107706         break;
107707       }
107708       case '-': {   /* SQL-style comments from "--" to end of line */
107709         if( zSql[1]!='-' ){
107710           token = tkOTHER;
107711           break;
107712         }
107713         while( *zSql && *zSql!='\n' ){ zSql++; }
107714         if( *zSql==0 ) return state==1;
107715         token = tkWS;
107716         break;
107717       }
107718       case '[': {   /* Microsoft-style identifiers in [...] */
107719         zSql++;
107720         while( *zSql && *zSql!=']' ){ zSql++; }
107721         if( *zSql==0 ) return 0;
107722         token = tkOTHER;
107723         break;
107724       }
107725       case '`':     /* Grave-accent quoted symbols used by MySQL */
107726       case '"':     /* single- and double-quoted strings */
107727       case '\'': {
107728         int c = *zSql;
107729         zSql++;
107730         while( *zSql && *zSql!=c ){ zSql++; }
107731         if( *zSql==0 ) return 0;
107732         token = tkOTHER;
107733         break;
107734       }
107735       default: {
107736 #ifdef SQLITE_EBCDIC
107737         unsigned char c;
107738 #endif
107739         if( IdChar((u8)*zSql) ){
107740           /* Keywords and unquoted identifiers */
107741           int nId;
107742           for(nId=1; IdChar(zSql[nId]); nId++){}
107743 #ifdef SQLITE_OMIT_TRIGGER
107744           token = tkOTHER;
107745 #else
107746           switch( *zSql ){
107747             case 'c': case 'C': {
107748               if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
107749                 token = tkCREATE;
107750               }else{
107751                 token = tkOTHER;
107752               }
107753               break;
107754             }
107755             case 't': case 'T': {
107756               if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
107757                 token = tkTRIGGER;
107758               }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
107759                 token = tkTEMP;
107760               }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
107761                 token = tkTEMP;
107762               }else{
107763                 token = tkOTHER;
107764               }
107765               break;
107766             }
107767             case 'e':  case 'E': {
107768               if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
107769                 token = tkEND;
107770               }else
107771 #ifndef SQLITE_OMIT_EXPLAIN
107772               if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
107773                 token = tkEXPLAIN;
107774               }else
107775 #endif
107776               {
107777                 token = tkOTHER;
107778               }
107779               break;
107780             }
107781             default: {
107782               token = tkOTHER;
107783               break;
107784             }
107785           }
107786 #endif /* SQLITE_OMIT_TRIGGER */
107787           zSql += nId-1;
107788         }else{
107789           /* Operators and special symbols */
107790           token = tkOTHER;
107791         }
107792         break;
107793       }
107794     }
107795     state = trans[state][token];
107796     zSql++;
107797   }
107798   return state==1;
107799 }
107800
107801 #ifndef SQLITE_OMIT_UTF16
107802 /*
107803 ** This routine is the same as the sqlite3_complete() routine described
107804 ** above, except that the parameter is required to be UTF-16 encoded, not
107805 ** UTF-8.
107806 */
107807 SQLITE_API int sqlite3_complete16(const void *zSql){
107808   sqlite3_value *pVal;
107809   char const *zSql8;
107810   int rc = SQLITE_NOMEM;
107811
107812 #ifndef SQLITE_OMIT_AUTOINIT
107813   rc = sqlite3_initialize();
107814   if( rc ) return rc;
107815 #endif
107816   pVal = sqlite3ValueNew(0);
107817   sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
107818   zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
107819   if( zSql8 ){
107820     rc = sqlite3_complete(zSql8);
107821   }else{
107822     rc = SQLITE_NOMEM;
107823   }
107824   sqlite3ValueFree(pVal);
107825   return sqlite3ApiExit(0, rc);
107826 }
107827 #endif /* SQLITE_OMIT_UTF16 */
107828 #endif /* SQLITE_OMIT_COMPLETE */
107829
107830 /************** End of complete.c ********************************************/
107831 /************** Begin file main.c ********************************************/
107832 /*
107833 ** 2001 September 15
107834 **
107835 ** The author disclaims copyright to this source code.  In place of
107836 ** a legal notice, here is a blessing:
107837 **
107838 **    May you do good and not evil.
107839 **    May you find forgiveness for yourself and forgive others.
107840 **    May you share freely, never taking more than you give.
107841 **
107842 *************************************************************************
107843 ** Main file for the SQLite library.  The routines in this file
107844 ** implement the programmer interface to the library.  Routines in
107845 ** other files are for internal use by SQLite and should not be
107846 ** accessed by users of the library.
107847 */
107848
107849 #ifdef SQLITE_ENABLE_FTS3
107850 /************** Include fts3.h in the middle of main.c ***********************/
107851 /************** Begin file fts3.h ********************************************/
107852 /*
107853 ** 2006 Oct 10
107854 **
107855 ** The author disclaims copyright to this source code.  In place of
107856 ** a legal notice, here is a blessing:
107857 **
107858 **    May you do good and not evil.
107859 **    May you find forgiveness for yourself and forgive others.
107860 **    May you share freely, never taking more than you give.
107861 **
107862 ******************************************************************************
107863 **
107864 ** This header file is used by programs that want to link against the
107865 ** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
107866 */
107867
107868 #if 0
107869 extern "C" {
107870 #endif  /* __cplusplus */
107871
107872 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
107873
107874 #if 0
107875 }  /* extern "C" */
107876 #endif  /* __cplusplus */
107877
107878 /************** End of fts3.h ************************************************/
107879 /************** Continuing where we left off in main.c ***********************/
107880 #endif
107881 #ifdef SQLITE_ENABLE_RTREE
107882 /************** Include rtree.h in the middle of main.c **********************/
107883 /************** Begin file rtree.h *******************************************/
107884 /*
107885 ** 2008 May 26
107886 **
107887 ** The author disclaims copyright to this source code.  In place of
107888 ** a legal notice, here is a blessing:
107889 **
107890 **    May you do good and not evil.
107891 **    May you find forgiveness for yourself and forgive others.
107892 **    May you share freely, never taking more than you give.
107893 **
107894 ******************************************************************************
107895 **
107896 ** This header file is used by programs that want to link against the
107897 ** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
107898 */
107899
107900 #if 0
107901 extern "C" {
107902 #endif  /* __cplusplus */
107903
107904 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
107905
107906 #if 0
107907 }  /* extern "C" */
107908 #endif  /* __cplusplus */
107909
107910 /************** End of rtree.h ***********************************************/
107911 /************** Continuing where we left off in main.c ***********************/
107912 #endif
107913 #ifdef SQLITE_ENABLE_ICU
107914 /************** Include sqliteicu.h in the middle of main.c ******************/
107915 /************** Begin file sqliteicu.h ***************************************/
107916 /*
107917 ** 2008 May 26
107918 **
107919 ** The author disclaims copyright to this source code.  In place of
107920 ** a legal notice, here is a blessing:
107921 **
107922 **    May you do good and not evil.
107923 **    May you find forgiveness for yourself and forgive others.
107924 **    May you share freely, never taking more than you give.
107925 **
107926 ******************************************************************************
107927 **
107928 ** This header file is used by programs that want to link against the
107929 ** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
107930 */
107931
107932 #if 0
107933 extern "C" {
107934 #endif  /* __cplusplus */
107935
107936 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
107937
107938 #if 0
107939 }  /* extern "C" */
107940 #endif  /* __cplusplus */
107941
107942
107943 /************** End of sqliteicu.h *******************************************/
107944 /************** Continuing where we left off in main.c ***********************/
107945 #endif
107946
107947 #ifndef SQLITE_AMALGAMATION
107948 /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
107949 ** contains the text of SQLITE_VERSION macro. 
107950 */
107951 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
107952 #endif
107953
107954 /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
107955 ** a pointer to the to the sqlite3_version[] string constant. 
107956 */
107957 SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
107958
107959 /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
107960 ** pointer to a string constant whose value is the same as the
107961 ** SQLITE_SOURCE_ID C preprocessor macro. 
107962 */
107963 SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
107964
107965 /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
107966 ** returns an integer equal to SQLITE_VERSION_NUMBER.
107967 */
107968 SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
107969
107970 /* IMPLEMENTATION-OF: R-54823-41343 The sqlite3_threadsafe() function returns
107971 ** zero if and only if SQLite was compiled mutexing code omitted due to
107972 ** the SQLITE_THREADSAFE compile-time option being set to 0.
107973 */
107974 SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
107975
107976 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
107977 /*
107978 ** If the following function pointer is not NULL and if
107979 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
107980 ** I/O active are written using this function.  These messages
107981 ** are intended for debugging activity only.
107982 */
107983 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
107984 #endif
107985
107986 /*
107987 ** If the following global variable points to a string which is the
107988 ** name of a directory, then that directory will be used to store
107989 ** temporary files.
107990 **
107991 ** See also the "PRAGMA temp_store_directory" SQL command.
107992 */
107993 SQLITE_API char *sqlite3_temp_directory = 0;
107994
107995 /*
107996 ** Initialize SQLite.  
107997 **
107998 ** This routine must be called to initialize the memory allocation,
107999 ** VFS, and mutex subsystems prior to doing any serious work with
108000 ** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
108001 ** this routine will be called automatically by key routines such as
108002 ** sqlite3_open().  
108003 **
108004 ** This routine is a no-op except on its very first call for the process,
108005 ** or for the first call after a call to sqlite3_shutdown.
108006 **
108007 ** The first thread to call this routine runs the initialization to
108008 ** completion.  If subsequent threads call this routine before the first
108009 ** thread has finished the initialization process, then the subsequent
108010 ** threads must block until the first thread finishes with the initialization.
108011 **
108012 ** The first thread might call this routine recursively.  Recursive
108013 ** calls to this routine should not block, of course.  Otherwise the
108014 ** initialization process would never complete.
108015 **
108016 ** Let X be the first thread to enter this routine.  Let Y be some other
108017 ** thread.  Then while the initial invocation of this routine by X is
108018 ** incomplete, it is required that:
108019 **
108020 **    *  Calls to this routine from Y must block until the outer-most
108021 **       call by X completes.
108022 **
108023 **    *  Recursive calls to this routine from thread X return immediately
108024 **       without blocking.
108025 */
108026 SQLITE_API int sqlite3_initialize(void){
108027   sqlite3_mutex *pMaster;                      /* The main static mutex */
108028   int rc;                                      /* Result code */
108029
108030 #ifdef SQLITE_OMIT_WSD
108031   rc = sqlite3_wsd_init(4096, 24);
108032   if( rc!=SQLITE_OK ){
108033     return rc;
108034   }
108035 #endif
108036
108037   /* If SQLite is already completely initialized, then this call
108038   ** to sqlite3_initialize() should be a no-op.  But the initialization
108039   ** must be complete.  So isInit must not be set until the very end
108040   ** of this routine.
108041   */
108042   if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
108043
108044   /* Make sure the mutex subsystem is initialized.  If unable to 
108045   ** initialize the mutex subsystem, return early with the error.
108046   ** If the system is so sick that we are unable to allocate a mutex,
108047   ** there is not much SQLite is going to be able to do.
108048   **
108049   ** The mutex subsystem must take care of serializing its own
108050   ** initialization.
108051   */
108052   rc = sqlite3MutexInit();
108053   if( rc ) return rc;
108054
108055   /* Initialize the malloc() system and the recursive pInitMutex mutex.
108056   ** This operation is protected by the STATIC_MASTER mutex.  Note that
108057   ** MutexAlloc() is called for a static mutex prior to initializing the
108058   ** malloc subsystem - this implies that the allocation of a static
108059   ** mutex must not require support from the malloc subsystem.
108060   */
108061   pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
108062   sqlite3_mutex_enter(pMaster);
108063   sqlite3GlobalConfig.isMutexInit = 1;
108064   if( !sqlite3GlobalConfig.isMallocInit ){
108065     rc = sqlite3MallocInit();
108066   }
108067   if( rc==SQLITE_OK ){
108068     sqlite3GlobalConfig.isMallocInit = 1;
108069     if( !sqlite3GlobalConfig.pInitMutex ){
108070       sqlite3GlobalConfig.pInitMutex =
108071            sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
108072       if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
108073         rc = SQLITE_NOMEM;
108074       }
108075     }
108076   }
108077   if( rc==SQLITE_OK ){
108078     sqlite3GlobalConfig.nRefInitMutex++;
108079   }
108080   sqlite3_mutex_leave(pMaster);
108081
108082   /* If rc is not SQLITE_OK at this point, then either the malloc
108083   ** subsystem could not be initialized or the system failed to allocate
108084   ** the pInitMutex mutex. Return an error in either case.  */
108085   if( rc!=SQLITE_OK ){
108086     return rc;
108087   }
108088
108089   /* Do the rest of the initialization under the recursive mutex so
108090   ** that we will be able to handle recursive calls into
108091   ** sqlite3_initialize().  The recursive calls normally come through
108092   ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
108093   ** recursive calls might also be possible.
108094   **
108095   ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
108096   ** to the xInit method, so the xInit method need not be threadsafe.
108097   **
108098   ** The following mutex is what serializes access to the appdef pcache xInit
108099   ** methods.  The sqlite3_pcache_methods.xInit() all is embedded in the
108100   ** call to sqlite3PcacheInitialize().
108101   */
108102   sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
108103   if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
108104     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
108105     sqlite3GlobalConfig.inProgress = 1;
108106     memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
108107     sqlite3RegisterGlobalFunctions();
108108     if( sqlite3GlobalConfig.isPCacheInit==0 ){
108109       rc = sqlite3PcacheInitialize();
108110     }
108111     if( rc==SQLITE_OK ){
108112       sqlite3GlobalConfig.isPCacheInit = 1;
108113       rc = sqlite3OsInit();
108114     }
108115     if( rc==SQLITE_OK ){
108116       sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage, 
108117           sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
108118       sqlite3GlobalConfig.isInit = 1;
108119     }
108120     sqlite3GlobalConfig.inProgress = 0;
108121   }
108122   sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
108123
108124   /* Go back under the static mutex and clean up the recursive
108125   ** mutex to prevent a resource leak.
108126   */
108127   sqlite3_mutex_enter(pMaster);
108128   sqlite3GlobalConfig.nRefInitMutex--;
108129   if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
108130     assert( sqlite3GlobalConfig.nRefInitMutex==0 );
108131     sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
108132     sqlite3GlobalConfig.pInitMutex = 0;
108133   }
108134   sqlite3_mutex_leave(pMaster);
108135
108136   /* The following is just a sanity check to make sure SQLite has
108137   ** been compiled correctly.  It is important to run this code, but
108138   ** we don't want to run it too often and soak up CPU cycles for no
108139   ** reason.  So we run it once during initialization.
108140   */
108141 #ifndef NDEBUG
108142 #ifndef SQLITE_OMIT_FLOATING_POINT
108143   /* This section of code's only "output" is via assert() statements. */
108144   if ( rc==SQLITE_OK ){
108145     u64 x = (((u64)1)<<63)-1;
108146     double y;
108147     assert(sizeof(x)==8);
108148     assert(sizeof(x)==sizeof(y));
108149     memcpy(&y, &x, 8);
108150     assert( sqlite3IsNaN(y) );
108151   }
108152 #endif
108153 #endif
108154
108155   return rc;
108156 }
108157
108158 /*
108159 ** Undo the effects of sqlite3_initialize().  Must not be called while
108160 ** there are outstanding database connections or memory allocations or
108161 ** while any part of SQLite is otherwise in use in any thread.  This
108162 ** routine is not threadsafe.  But it is safe to invoke this routine
108163 ** on when SQLite is already shut down.  If SQLite is already shut down
108164 ** when this routine is invoked, then this routine is a harmless no-op.
108165 */
108166 SQLITE_API int sqlite3_shutdown(void){
108167   if( sqlite3GlobalConfig.isInit ){
108168     sqlite3_os_end();
108169     sqlite3_reset_auto_extension();
108170     sqlite3GlobalConfig.isInit = 0;
108171   }
108172   if( sqlite3GlobalConfig.isPCacheInit ){
108173     sqlite3PcacheShutdown();
108174     sqlite3GlobalConfig.isPCacheInit = 0;
108175   }
108176   if( sqlite3GlobalConfig.isMallocInit ){
108177     sqlite3MallocEnd();
108178     sqlite3GlobalConfig.isMallocInit = 0;
108179   }
108180   if( sqlite3GlobalConfig.isMutexInit ){
108181     sqlite3MutexEnd();
108182     sqlite3GlobalConfig.isMutexInit = 0;
108183   }
108184
108185   return SQLITE_OK;
108186 }
108187
108188 /*
108189 ** This API allows applications to modify the global configuration of
108190 ** the SQLite library at run-time.
108191 **
108192 ** This routine should only be called when there are no outstanding
108193 ** database connections or memory allocations.  This routine is not
108194 ** threadsafe.  Failure to heed these warnings can lead to unpredictable
108195 ** behavior.
108196 */
108197 SQLITE_API int sqlite3_config(int op, ...){
108198   va_list ap;
108199   int rc = SQLITE_OK;
108200
108201   /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
108202   ** the SQLite library is in use. */
108203   if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
108204
108205   va_start(ap, op);
108206   switch( op ){
108207
108208     /* Mutex configuration options are only available in a threadsafe
108209     ** compile. 
108210     */
108211 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
108212     case SQLITE_CONFIG_SINGLETHREAD: {
108213       /* Disable all mutexing */
108214       sqlite3GlobalConfig.bCoreMutex = 0;
108215       sqlite3GlobalConfig.bFullMutex = 0;
108216       break;
108217     }
108218     case SQLITE_CONFIG_MULTITHREAD: {
108219       /* Disable mutexing of database connections */
108220       /* Enable mutexing of core data structures */
108221       sqlite3GlobalConfig.bCoreMutex = 1;
108222       sqlite3GlobalConfig.bFullMutex = 0;
108223       break;
108224     }
108225     case SQLITE_CONFIG_SERIALIZED: {
108226       /* Enable all mutexing */
108227       sqlite3GlobalConfig.bCoreMutex = 1;
108228       sqlite3GlobalConfig.bFullMutex = 1;
108229       break;
108230     }
108231     case SQLITE_CONFIG_MUTEX: {
108232       /* Specify an alternative mutex implementation */
108233       sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
108234       break;
108235     }
108236     case SQLITE_CONFIG_GETMUTEX: {
108237       /* Retrieve the current mutex implementation */
108238       *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
108239       break;
108240     }
108241 #endif
108242
108243
108244     case SQLITE_CONFIG_MALLOC: {
108245       /* Specify an alternative malloc implementation */
108246       sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
108247       break;
108248     }
108249     case SQLITE_CONFIG_GETMALLOC: {
108250       /* Retrieve the current malloc() implementation */
108251       if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
108252       *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
108253       break;
108254     }
108255     case SQLITE_CONFIG_MEMSTATUS: {
108256       /* Enable or disable the malloc status collection */
108257       sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
108258       break;
108259     }
108260     case SQLITE_CONFIG_SCRATCH: {
108261       /* Designate a buffer for scratch memory space */
108262       sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
108263       sqlite3GlobalConfig.szScratch = va_arg(ap, int);
108264       sqlite3GlobalConfig.nScratch = va_arg(ap, int);
108265       break;
108266     }
108267     case SQLITE_CONFIG_PAGECACHE: {
108268       /* Designate a buffer for page cache memory space */
108269       sqlite3GlobalConfig.pPage = va_arg(ap, void*);
108270       sqlite3GlobalConfig.szPage = va_arg(ap, int);
108271       sqlite3GlobalConfig.nPage = va_arg(ap, int);
108272       break;
108273     }
108274
108275     case SQLITE_CONFIG_PCACHE: {
108276       /* Specify an alternative page cache implementation */
108277       sqlite3GlobalConfig.pcache = *va_arg(ap, sqlite3_pcache_methods*);
108278       break;
108279     }
108280
108281     case SQLITE_CONFIG_GETPCACHE: {
108282       if( sqlite3GlobalConfig.pcache.xInit==0 ){
108283         sqlite3PCacheSetDefault();
108284       }
108285       *va_arg(ap, sqlite3_pcache_methods*) = sqlite3GlobalConfig.pcache;
108286       break;
108287     }
108288
108289 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
108290     case SQLITE_CONFIG_HEAP: {
108291       /* Designate a buffer for heap memory space */
108292       sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
108293       sqlite3GlobalConfig.nHeap = va_arg(ap, int);
108294       sqlite3GlobalConfig.mnReq = va_arg(ap, int);
108295
108296       if( sqlite3GlobalConfig.mnReq<1 ){
108297         sqlite3GlobalConfig.mnReq = 1;
108298       }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
108299         /* cap min request size at 2^12 */
108300         sqlite3GlobalConfig.mnReq = (1<<12);
108301       }
108302
108303       if( sqlite3GlobalConfig.pHeap==0 ){
108304         /* If the heap pointer is NULL, then restore the malloc implementation
108305         ** back to NULL pointers too.  This will cause the malloc to go
108306         ** back to its default implementation when sqlite3_initialize() is
108307         ** run.
108308         */
108309         memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
108310       }else{
108311         /* The heap pointer is not NULL, then install one of the
108312         ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
108313         ** ENABLE_MEMSYS5 is defined, return an error.
108314         */
108315 #ifdef SQLITE_ENABLE_MEMSYS3
108316         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
108317 #endif
108318 #ifdef SQLITE_ENABLE_MEMSYS5
108319         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
108320 #endif
108321       }
108322       break;
108323     }
108324 #endif
108325
108326     case SQLITE_CONFIG_LOOKASIDE: {
108327       sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
108328       sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
108329       break;
108330     }
108331     
108332     /* Record a pointer to the logger funcction and its first argument.
108333     ** The default is NULL.  Logging is disabled if the function pointer is
108334     ** NULL.
108335     */
108336     case SQLITE_CONFIG_LOG: {
108337       /* MSVC is picky about pulling func ptrs from va lists.
108338       ** http://support.microsoft.com/kb/47961
108339       ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
108340       */
108341       typedef void(*LOGFUNC_t)(void*,int,const char*);
108342       sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
108343       sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
108344       break;
108345     }
108346
108347     case SQLITE_CONFIG_URI: {
108348       sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
108349       break;
108350     }
108351
108352     default: {
108353       rc = SQLITE_ERROR;
108354       break;
108355     }
108356   }
108357   va_end(ap);
108358   return rc;
108359 }
108360
108361 /*
108362 ** Set up the lookaside buffers for a database connection.
108363 ** Return SQLITE_OK on success.  
108364 ** If lookaside is already active, return SQLITE_BUSY.
108365 **
108366 ** The sz parameter is the number of bytes in each lookaside slot.
108367 ** The cnt parameter is the number of slots.  If pStart is NULL the
108368 ** space for the lookaside memory is obtained from sqlite3_malloc().
108369 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
108370 ** the lookaside memory.
108371 */
108372 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
108373   void *pStart;
108374   if( db->lookaside.nOut ){
108375     return SQLITE_BUSY;
108376   }
108377   /* Free any existing lookaside buffer for this handle before
108378   ** allocating a new one so we don't have to have space for 
108379   ** both at the same time.
108380   */
108381   if( db->lookaside.bMalloced ){
108382     sqlite3_free(db->lookaside.pStart);
108383   }
108384   /* The size of a lookaside slot needs to be larger than a pointer
108385   ** to be useful.
108386   */
108387   if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
108388   if( cnt<0 ) cnt = 0;
108389   if( sz==0 || cnt==0 ){
108390     sz = 0;
108391     pStart = 0;
108392   }else if( pBuf==0 ){
108393     sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
108394     sqlite3BeginBenignMalloc();
108395     pStart = sqlite3Malloc( sz*cnt );  /* IMP: R-61949-35727 */
108396     sqlite3EndBenignMalloc();
108397   }else{
108398     sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
108399     pStart = pBuf;
108400   }
108401   db->lookaside.pStart = pStart;
108402   db->lookaside.pFree = 0;
108403   db->lookaside.sz = (u16)sz;
108404   if( pStart ){
108405     int i;
108406     LookasideSlot *p;
108407     assert( sz > (int)sizeof(LookasideSlot*) );
108408     p = (LookasideSlot*)pStart;
108409     for(i=cnt-1; i>=0; i--){
108410       p->pNext = db->lookaside.pFree;
108411       db->lookaside.pFree = p;
108412       p = (LookasideSlot*)&((u8*)p)[sz];
108413     }
108414     db->lookaside.pEnd = p;
108415     db->lookaside.bEnabled = 1;
108416     db->lookaside.bMalloced = pBuf==0 ?1:0;
108417   }else{
108418     db->lookaside.pEnd = 0;
108419     db->lookaside.bEnabled = 0;
108420     db->lookaside.bMalloced = 0;
108421   }
108422   return SQLITE_OK;
108423 }
108424
108425 /*
108426 ** Return the mutex associated with a database connection.
108427 */
108428 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
108429   return db->mutex;
108430 }
108431
108432 /*
108433 ** Configuration settings for an individual database connection
108434 */
108435 SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
108436   va_list ap;
108437   int rc;
108438   va_start(ap, op);
108439   switch( op ){
108440     case SQLITE_DBCONFIG_LOOKASIDE: {
108441       void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
108442       int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */
108443       int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */
108444       rc = setupLookaside(db, pBuf, sz, cnt);
108445       break;
108446     }
108447     default: {
108448       static const struct {
108449         int op;      /* The opcode */
108450         u32 mask;    /* Mask of the bit in sqlite3.flags to set/clear */
108451       } aFlagOp[] = {
108452         { SQLITE_DBCONFIG_ENABLE_FKEY,    SQLITE_ForeignKeys    },
108453         { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger  },
108454       };
108455       unsigned int i;
108456       rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
108457       for(i=0; i<ArraySize(aFlagOp); i++){
108458         if( aFlagOp[i].op==op ){
108459           int onoff = va_arg(ap, int);
108460           int *pRes = va_arg(ap, int*);
108461           int oldFlags = db->flags;
108462           if( onoff>0 ){
108463             db->flags |= aFlagOp[i].mask;
108464           }else if( onoff==0 ){
108465             db->flags &= ~aFlagOp[i].mask;
108466           }
108467           if( oldFlags!=db->flags ){
108468             sqlite3ExpirePreparedStatements(db);
108469           }
108470           if( pRes ){
108471             *pRes = (db->flags & aFlagOp[i].mask)!=0;
108472           }
108473           rc = SQLITE_OK;
108474           break;
108475         }
108476       }
108477       break;
108478     }
108479   }
108480   va_end(ap);
108481   return rc;
108482 }
108483
108484
108485 /*
108486 ** Return true if the buffer z[0..n-1] contains all spaces.
108487 */
108488 static int allSpaces(const char *z, int n){
108489   while( n>0 && z[n-1]==' ' ){ n--; }
108490   return n==0;
108491 }
108492
108493 /*
108494 ** This is the default collating function named "BINARY" which is always
108495 ** available.
108496 **
108497 ** If the padFlag argument is not NULL then space padding at the end
108498 ** of strings is ignored.  This implements the RTRIM collation.
108499 */
108500 static int binCollFunc(
108501   void *padFlag,
108502   int nKey1, const void *pKey1,
108503   int nKey2, const void *pKey2
108504 ){
108505   int rc, n;
108506   n = nKey1<nKey2 ? nKey1 : nKey2;
108507   rc = memcmp(pKey1, pKey2, n);
108508   if( rc==0 ){
108509     if( padFlag
108510      && allSpaces(((char*)pKey1)+n, nKey1-n)
108511      && allSpaces(((char*)pKey2)+n, nKey2-n)
108512     ){
108513       /* Leave rc unchanged at 0 */
108514     }else{
108515       rc = nKey1 - nKey2;
108516     }
108517   }
108518   return rc;
108519 }
108520
108521 /*
108522 ** Another built-in collating sequence: NOCASE. 
108523 **
108524 ** This collating sequence is intended to be used for "case independant
108525 ** comparison". SQLite's knowledge of upper and lower case equivalents
108526 ** extends only to the 26 characters used in the English language.
108527 **
108528 ** At the moment there is only a UTF-8 implementation.
108529 */
108530 static int nocaseCollatingFunc(
108531   void *NotUsed,
108532   int nKey1, const void *pKey1,
108533   int nKey2, const void *pKey2
108534 ){
108535   int r = sqlite3StrNICmp(
108536       (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
108537   UNUSED_PARAMETER(NotUsed);
108538   if( 0==r ){
108539     r = nKey1-nKey2;
108540   }
108541   return r;
108542 }
108543
108544 /*
108545 ** Return the ROWID of the most recent insert
108546 */
108547 SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
108548   return db->lastRowid;
108549 }
108550
108551 /*
108552 ** Return the number of changes in the most recent call to sqlite3_exec().
108553 */
108554 SQLITE_API int sqlite3_changes(sqlite3 *db){
108555   return db->nChange;
108556 }
108557
108558 /*
108559 ** Return the number of changes since the database handle was opened.
108560 */
108561 SQLITE_API int sqlite3_total_changes(sqlite3 *db){
108562   return db->nTotalChange;
108563 }
108564
108565 /*
108566 ** Close all open savepoints. This function only manipulates fields of the
108567 ** database handle object, it does not close any savepoints that may be open
108568 ** at the b-tree/pager level.
108569 */
108570 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
108571   while( db->pSavepoint ){
108572     Savepoint *pTmp = db->pSavepoint;
108573     db->pSavepoint = pTmp->pNext;
108574     sqlite3DbFree(db, pTmp);
108575   }
108576   db->nSavepoint = 0;
108577   db->nStatement = 0;
108578   db->isTransactionSavepoint = 0;
108579 }
108580
108581 /*
108582 ** Invoke the destructor function associated with FuncDef p, if any. Except,
108583 ** if this is not the last copy of the function, do not invoke it. Multiple
108584 ** copies of a single function are created when create_function() is called
108585 ** with SQLITE_ANY as the encoding.
108586 */
108587 static void functionDestroy(sqlite3 *db, FuncDef *p){
108588   FuncDestructor *pDestructor = p->pDestructor;
108589   if( pDestructor ){
108590     pDestructor->nRef--;
108591     if( pDestructor->nRef==0 ){
108592       pDestructor->xDestroy(pDestructor->pUserData);
108593       sqlite3DbFree(db, pDestructor);
108594     }
108595   }
108596 }
108597
108598 /*
108599 ** Close an existing SQLite database
108600 */
108601 SQLITE_API int sqlite3_close(sqlite3 *db){
108602   HashElem *i;                    /* Hash table iterator */
108603   int j;
108604
108605   if( !db ){
108606     return SQLITE_OK;
108607   }
108608   if( !sqlite3SafetyCheckSickOrOk(db) ){
108609     return SQLITE_MISUSE_BKPT;
108610   }
108611   sqlite3_mutex_enter(db->mutex);
108612
108613   /* Force xDestroy calls on all virtual tables */
108614   sqlite3ResetInternalSchema(db, -1);
108615
108616   /* If a transaction is open, the ResetInternalSchema() call above
108617   ** will not have called the xDisconnect() method on any virtual
108618   ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
108619   ** call will do so. We need to do this before the check for active
108620   ** SQL statements below, as the v-table implementation may be storing
108621   ** some prepared statements internally.
108622   */
108623   sqlite3VtabRollback(db);
108624
108625   /* If there are any outstanding VMs, return SQLITE_BUSY. */
108626   if( db->pVdbe ){
108627     sqlite3Error(db, SQLITE_BUSY, 
108628         "unable to close due to unfinalised statements");
108629     sqlite3_mutex_leave(db->mutex);
108630     return SQLITE_BUSY;
108631   }
108632   assert( sqlite3SafetyCheckSickOrOk(db) );
108633
108634   for(j=0; j<db->nDb; j++){
108635     Btree *pBt = db->aDb[j].pBt;
108636     if( pBt && sqlite3BtreeIsInBackup(pBt) ){
108637       sqlite3Error(db, SQLITE_BUSY, 
108638           "unable to close due to unfinished backup operation");
108639       sqlite3_mutex_leave(db->mutex);
108640       return SQLITE_BUSY;
108641     }
108642   }
108643
108644   /* Free any outstanding Savepoint structures. */
108645   sqlite3CloseSavepoints(db);
108646
108647   for(j=0; j<db->nDb; j++){
108648     struct Db *pDb = &db->aDb[j];
108649     if( pDb->pBt ){
108650       sqlite3BtreeClose(pDb->pBt);
108651       pDb->pBt = 0;
108652       if( j!=1 ){
108653         pDb->pSchema = 0;
108654       }
108655     }
108656   }
108657   sqlite3ResetInternalSchema(db, -1);
108658
108659   /* Tell the code in notify.c that the connection no longer holds any
108660   ** locks and does not require any further unlock-notify callbacks.
108661   */
108662   sqlite3ConnectionClosed(db);
108663
108664   assert( db->nDb<=2 );
108665   assert( db->aDb==db->aDbStatic );
108666   for(j=0; j<ArraySize(db->aFunc.a); j++){
108667     FuncDef *pNext, *pHash, *p;
108668     for(p=db->aFunc.a[j]; p; p=pHash){
108669       pHash = p->pHash;
108670       while( p ){
108671         functionDestroy(db, p);
108672         pNext = p->pNext;
108673         sqlite3DbFree(db, p);
108674         p = pNext;
108675       }
108676     }
108677   }
108678   for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
108679     CollSeq *pColl = (CollSeq *)sqliteHashData(i);
108680     /* Invoke any destructors registered for collation sequence user data. */
108681     for(j=0; j<3; j++){
108682       if( pColl[j].xDel ){
108683         pColl[j].xDel(pColl[j].pUser);
108684       }
108685     }
108686     sqlite3DbFree(db, pColl);
108687   }
108688   sqlite3HashClear(&db->aCollSeq);
108689 #ifndef SQLITE_OMIT_VIRTUALTABLE
108690   for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
108691     Module *pMod = (Module *)sqliteHashData(i);
108692     if( pMod->xDestroy ){
108693       pMod->xDestroy(pMod->pAux);
108694     }
108695     sqlite3DbFree(db, pMod);
108696   }
108697   sqlite3HashClear(&db->aModule);
108698 #endif
108699
108700   sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
108701   if( db->pErr ){
108702     sqlite3ValueFree(db->pErr);
108703   }
108704   sqlite3CloseExtensions(db);
108705
108706   db->magic = SQLITE_MAGIC_ERROR;
108707
108708   /* The temp-database schema is allocated differently from the other schema
108709   ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
108710   ** So it needs to be freed here. Todo: Why not roll the temp schema into
108711   ** the same sqliteMalloc() as the one that allocates the database 
108712   ** structure?
108713   */
108714   sqlite3DbFree(db, db->aDb[1].pSchema);
108715   sqlite3_mutex_leave(db->mutex);
108716   db->magic = SQLITE_MAGIC_CLOSED;
108717   sqlite3_mutex_free(db->mutex);
108718   assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
108719   if( db->lookaside.bMalloced ){
108720     sqlite3_free(db->lookaside.pStart);
108721   }
108722   sqlite3_free(db);
108723   return SQLITE_OK;
108724 }
108725
108726 /*
108727 ** Rollback all database files.
108728 */
108729 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db){
108730   int i;
108731   int inTrans = 0;
108732   assert( sqlite3_mutex_held(db->mutex) );
108733   sqlite3BeginBenignMalloc();
108734   for(i=0; i<db->nDb; i++){
108735     if( db->aDb[i].pBt ){
108736       if( sqlite3BtreeIsInTrans(db->aDb[i].pBt) ){
108737         inTrans = 1;
108738       }
108739       sqlite3BtreeRollback(db->aDb[i].pBt);
108740       db->aDb[i].inTrans = 0;
108741     }
108742   }
108743   sqlite3VtabRollback(db);
108744   sqlite3EndBenignMalloc();
108745
108746   if( db->flags&SQLITE_InternChanges ){
108747     sqlite3ExpirePreparedStatements(db);
108748     sqlite3ResetInternalSchema(db, -1);
108749   }
108750
108751   /* Any deferred constraint violations have now been resolved. */
108752   db->nDeferredCons = 0;
108753
108754   /* If one has been configured, invoke the rollback-hook callback */
108755   if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
108756     db->xRollbackCallback(db->pRollbackArg);
108757   }
108758 }
108759
108760 /*
108761 ** Return a static string that describes the kind of error specified in the
108762 ** argument.
108763 */
108764 SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
108765   static const char* const aMsg[] = {
108766     /* SQLITE_OK          */ "not an error",
108767     /* SQLITE_ERROR       */ "SQL logic error or missing database",
108768     /* SQLITE_INTERNAL    */ 0,
108769     /* SQLITE_PERM        */ "access permission denied",
108770     /* SQLITE_ABORT       */ "callback requested query abort",
108771     /* SQLITE_BUSY        */ "database is locked",
108772     /* SQLITE_LOCKED      */ "database table is locked",
108773     /* SQLITE_NOMEM       */ "out of memory",
108774     /* SQLITE_READONLY    */ "attempt to write a readonly database",
108775     /* SQLITE_INTERRUPT   */ "interrupted",
108776     /* SQLITE_IOERR       */ "disk I/O error",
108777     /* SQLITE_CORRUPT     */ "database disk image is malformed",
108778     /* SQLITE_NOTFOUND    */ "unknown operation",
108779     /* SQLITE_FULL        */ "database or disk is full",
108780     /* SQLITE_CANTOPEN    */ "unable to open database file",
108781     /* SQLITE_PROTOCOL    */ "locking protocol",
108782     /* SQLITE_EMPTY       */ "table contains no data",
108783     /* SQLITE_SCHEMA      */ "database schema has changed",
108784     /* SQLITE_TOOBIG      */ "string or blob too big",
108785     /* SQLITE_CONSTRAINT  */ "constraint failed",
108786     /* SQLITE_MISMATCH    */ "datatype mismatch",
108787     /* SQLITE_MISUSE      */ "library routine called out of sequence",
108788     /* SQLITE_NOLFS       */ "large file support is disabled",
108789     /* SQLITE_AUTH        */ "authorization denied",
108790     /* SQLITE_FORMAT      */ "auxiliary database format error",
108791     /* SQLITE_RANGE       */ "bind or column index out of range",
108792     /* SQLITE_NOTADB      */ "file is encrypted or is not a database",
108793   };
108794   rc &= 0xff;
108795   if( ALWAYS(rc>=0) && rc<(int)(sizeof(aMsg)/sizeof(aMsg[0])) && aMsg[rc]!=0 ){
108796     return aMsg[rc];
108797   }else{
108798     return "unknown error";
108799   }
108800 }
108801
108802 /*
108803 ** This routine implements a busy callback that sleeps and tries
108804 ** again until a timeout value is reached.  The timeout value is
108805 ** an integer number of milliseconds passed in as the first
108806 ** argument.
108807 */
108808 static int sqliteDefaultBusyCallback(
108809  void *ptr,               /* Database connection */
108810  int count                /* Number of times table has been busy */
108811 ){
108812 #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
108813   static const u8 delays[] =
108814      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
108815   static const u8 totals[] =
108816      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
108817 # define NDELAY ArraySize(delays)
108818   sqlite3 *db = (sqlite3 *)ptr;
108819   int timeout = db->busyTimeout;
108820   int delay, prior;
108821
108822   assert( count>=0 );
108823   if( count < NDELAY ){
108824     delay = delays[count];
108825     prior = totals[count];
108826   }else{
108827     delay = delays[NDELAY-1];
108828     prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
108829   }
108830   if( prior + delay > timeout ){
108831     delay = timeout - prior;
108832     if( delay<=0 ) return 0;
108833   }
108834   sqlite3OsSleep(db->pVfs, delay*1000);
108835   return 1;
108836 #else
108837   sqlite3 *db = (sqlite3 *)ptr;
108838   int timeout = ((sqlite3 *)ptr)->busyTimeout;
108839   if( (count+1)*1000 > timeout ){
108840     return 0;
108841   }
108842   sqlite3OsSleep(db->pVfs, 1000000);
108843   return 1;
108844 #endif
108845 }
108846
108847 /*
108848 ** Invoke the given busy handler.
108849 **
108850 ** This routine is called when an operation failed with a lock.
108851 ** If this routine returns non-zero, the lock is retried.  If it
108852 ** returns 0, the operation aborts with an SQLITE_BUSY error.
108853 */
108854 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
108855   int rc;
108856   if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
108857   rc = p->xFunc(p->pArg, p->nBusy);
108858   if( rc==0 ){
108859     p->nBusy = -1;
108860   }else{
108861     p->nBusy++;
108862   }
108863   return rc; 
108864 }
108865
108866 /*
108867 ** This routine sets the busy callback for an Sqlite database to the
108868 ** given callback function with the given argument.
108869 */
108870 SQLITE_API int sqlite3_busy_handler(
108871   sqlite3 *db,
108872   int (*xBusy)(void*,int),
108873   void *pArg
108874 ){
108875   sqlite3_mutex_enter(db->mutex);
108876   db->busyHandler.xFunc = xBusy;
108877   db->busyHandler.pArg = pArg;
108878   db->busyHandler.nBusy = 0;
108879   sqlite3_mutex_leave(db->mutex);
108880   return SQLITE_OK;
108881 }
108882
108883 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
108884 /*
108885 ** This routine sets the progress callback for an Sqlite database to the
108886 ** given callback function with the given argument. The progress callback will
108887 ** be invoked every nOps opcodes.
108888 */
108889 SQLITE_API void sqlite3_progress_handler(
108890   sqlite3 *db, 
108891   int nOps,
108892   int (*xProgress)(void*), 
108893   void *pArg
108894 ){
108895   sqlite3_mutex_enter(db->mutex);
108896   if( nOps>0 ){
108897     db->xProgress = xProgress;
108898     db->nProgressOps = nOps;
108899     db->pProgressArg = pArg;
108900   }else{
108901     db->xProgress = 0;
108902     db->nProgressOps = 0;
108903     db->pProgressArg = 0;
108904   }
108905   sqlite3_mutex_leave(db->mutex);
108906 }
108907 #endif
108908
108909
108910 /*
108911 ** This routine installs a default busy handler that waits for the
108912 ** specified number of milliseconds before returning 0.
108913 */
108914 SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
108915   if( ms>0 ){
108916     db->busyTimeout = ms;
108917     sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
108918   }else{
108919     sqlite3_busy_handler(db, 0, 0);
108920   }
108921   return SQLITE_OK;
108922 }
108923
108924 /*
108925 ** Cause any pending operation to stop at its earliest opportunity.
108926 */
108927 SQLITE_API void sqlite3_interrupt(sqlite3 *db){
108928   db->u1.isInterrupted = 1;
108929 }
108930
108931
108932 /*
108933 ** This function is exactly the same as sqlite3_create_function(), except
108934 ** that it is designed to be called by internal code. The difference is
108935 ** that if a malloc() fails in sqlite3_create_function(), an error code
108936 ** is returned and the mallocFailed flag cleared. 
108937 */
108938 SQLITE_PRIVATE int sqlite3CreateFunc(
108939   sqlite3 *db,
108940   const char *zFunctionName,
108941   int nArg,
108942   int enc,
108943   void *pUserData,
108944   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
108945   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
108946   void (*xFinal)(sqlite3_context*),
108947   FuncDestructor *pDestructor
108948 ){
108949   FuncDef *p;
108950   int nName;
108951
108952   assert( sqlite3_mutex_held(db->mutex) );
108953   if( zFunctionName==0 ||
108954       (xFunc && (xFinal || xStep)) || 
108955       (!xFunc && (xFinal && !xStep)) ||
108956       (!xFunc && (!xFinal && xStep)) ||
108957       (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
108958       (255<(nName = sqlite3Strlen30( zFunctionName))) ){
108959     return SQLITE_MISUSE_BKPT;
108960   }
108961   
108962 #ifndef SQLITE_OMIT_UTF16
108963   /* If SQLITE_UTF16 is specified as the encoding type, transform this
108964   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
108965   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
108966   **
108967   ** If SQLITE_ANY is specified, add three versions of the function
108968   ** to the hash table.
108969   */
108970   if( enc==SQLITE_UTF16 ){
108971     enc = SQLITE_UTF16NATIVE;
108972   }else if( enc==SQLITE_ANY ){
108973     int rc;
108974     rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
108975          pUserData, xFunc, xStep, xFinal, pDestructor);
108976     if( rc==SQLITE_OK ){
108977       rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
108978           pUserData, xFunc, xStep, xFinal, pDestructor);
108979     }
108980     if( rc!=SQLITE_OK ){
108981       return rc;
108982     }
108983     enc = SQLITE_UTF16BE;
108984   }
108985 #else
108986   enc = SQLITE_UTF8;
108987 #endif
108988   
108989   /* Check if an existing function is being overridden or deleted. If so,
108990   ** and there are active VMs, then return SQLITE_BUSY. If a function
108991   ** is being overridden/deleted but there are no active VMs, allow the
108992   ** operation to continue but invalidate all precompiled statements.
108993   */
108994   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
108995   if( p && p->iPrefEnc==enc && p->nArg==nArg ){
108996     if( db->activeVdbeCnt ){
108997       sqlite3Error(db, SQLITE_BUSY, 
108998         "unable to delete/modify user-function due to active statements");
108999       assert( !db->mallocFailed );
109000       return SQLITE_BUSY;
109001     }else{
109002       sqlite3ExpirePreparedStatements(db);
109003     }
109004   }
109005
109006   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
109007   assert(p || db->mallocFailed);
109008   if( !p ){
109009     return SQLITE_NOMEM;
109010   }
109011
109012   /* If an older version of the function with a configured destructor is
109013   ** being replaced invoke the destructor function here. */
109014   functionDestroy(db, p);
109015
109016   if( pDestructor ){
109017     pDestructor->nRef++;
109018   }
109019   p->pDestructor = pDestructor;
109020   p->flags = 0;
109021   p->xFunc = xFunc;
109022   p->xStep = xStep;
109023   p->xFinalize = xFinal;
109024   p->pUserData = pUserData;
109025   p->nArg = (u16)nArg;
109026   return SQLITE_OK;
109027 }
109028
109029 /*
109030 ** Create new user functions.
109031 */
109032 SQLITE_API int sqlite3_create_function(
109033   sqlite3 *db,
109034   const char *zFunc,
109035   int nArg,
109036   int enc,
109037   void *p,
109038   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
109039   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
109040   void (*xFinal)(sqlite3_context*)
109041 ){
109042   return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
109043                                     xFinal, 0);
109044 }
109045
109046 SQLITE_API int sqlite3_create_function_v2(
109047   sqlite3 *db,
109048   const char *zFunc,
109049   int nArg,
109050   int enc,
109051   void *p,
109052   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
109053   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
109054   void (*xFinal)(sqlite3_context*),
109055   void (*xDestroy)(void *)
109056 ){
109057   int rc = SQLITE_ERROR;
109058   FuncDestructor *pArg = 0;
109059   sqlite3_mutex_enter(db->mutex);
109060   if( xDestroy ){
109061     pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
109062     if( !pArg ){
109063       xDestroy(p);
109064       goto out;
109065     }
109066     pArg->xDestroy = xDestroy;
109067     pArg->pUserData = p;
109068   }
109069   rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
109070   if( pArg && pArg->nRef==0 ){
109071     assert( rc!=SQLITE_OK );
109072     xDestroy(p);
109073     sqlite3DbFree(db, pArg);
109074   }
109075
109076  out:
109077   rc = sqlite3ApiExit(db, rc);
109078   sqlite3_mutex_leave(db->mutex);
109079   return rc;
109080 }
109081
109082 #ifndef SQLITE_OMIT_UTF16
109083 SQLITE_API int sqlite3_create_function16(
109084   sqlite3 *db,
109085   const void *zFunctionName,
109086   int nArg,
109087   int eTextRep,
109088   void *p,
109089   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
109090   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
109091   void (*xFinal)(sqlite3_context*)
109092 ){
109093   int rc;
109094   char *zFunc8;
109095   sqlite3_mutex_enter(db->mutex);
109096   assert( !db->mallocFailed );
109097   zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
109098   rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
109099   sqlite3DbFree(db, zFunc8);
109100   rc = sqlite3ApiExit(db, rc);
109101   sqlite3_mutex_leave(db->mutex);
109102   return rc;
109103 }
109104 #endif
109105
109106
109107 /*
109108 ** Declare that a function has been overloaded by a virtual table.
109109 **
109110 ** If the function already exists as a regular global function, then
109111 ** this routine is a no-op.  If the function does not exist, then create
109112 ** a new one that always throws a run-time error.  
109113 **
109114 ** When virtual tables intend to provide an overloaded function, they
109115 ** should call this routine to make sure the global function exists.
109116 ** A global function must exist in order for name resolution to work
109117 ** properly.
109118 */
109119 SQLITE_API int sqlite3_overload_function(
109120   sqlite3 *db,
109121   const char *zName,
109122   int nArg
109123 ){
109124   int nName = sqlite3Strlen30(zName);
109125   int rc;
109126   sqlite3_mutex_enter(db->mutex);
109127   if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
109128     sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
109129                       0, sqlite3InvalidFunction, 0, 0, 0);
109130   }
109131   rc = sqlite3ApiExit(db, SQLITE_OK);
109132   sqlite3_mutex_leave(db->mutex);
109133   return rc;
109134 }
109135
109136 #ifndef SQLITE_OMIT_TRACE
109137 /*
109138 ** Register a trace function.  The pArg from the previously registered trace
109139 ** is returned.  
109140 **
109141 ** A NULL trace function means that no tracing is executes.  A non-NULL
109142 ** trace is a pointer to a function that is invoked at the start of each
109143 ** SQL statement.
109144 */
109145 SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
109146   void *pOld;
109147   sqlite3_mutex_enter(db->mutex);
109148   pOld = db->pTraceArg;
109149   db->xTrace = xTrace;
109150   db->pTraceArg = pArg;
109151   sqlite3_mutex_leave(db->mutex);
109152   return pOld;
109153 }
109154 /*
109155 ** Register a profile function.  The pArg from the previously registered 
109156 ** profile function is returned.  
109157 **
109158 ** A NULL profile function means that no profiling is executes.  A non-NULL
109159 ** profile is a pointer to a function that is invoked at the conclusion of
109160 ** each SQL statement that is run.
109161 */
109162 SQLITE_API void *sqlite3_profile(
109163   sqlite3 *db,
109164   void (*xProfile)(void*,const char*,sqlite_uint64),
109165   void *pArg
109166 ){
109167   void *pOld;
109168   sqlite3_mutex_enter(db->mutex);
109169   pOld = db->pProfileArg;
109170   db->xProfile = xProfile;
109171   db->pProfileArg = pArg;
109172   sqlite3_mutex_leave(db->mutex);
109173   return pOld;
109174 }
109175 #endif /* SQLITE_OMIT_TRACE */
109176
109177 /*** EXPERIMENTAL ***
109178 **
109179 ** Register a function to be invoked when a transaction comments.
109180 ** If the invoked function returns non-zero, then the commit becomes a
109181 ** rollback.
109182 */
109183 SQLITE_API void *sqlite3_commit_hook(
109184   sqlite3 *db,              /* Attach the hook to this database */
109185   int (*xCallback)(void*),  /* Function to invoke on each commit */
109186   void *pArg                /* Argument to the function */
109187 ){
109188   void *pOld;
109189   sqlite3_mutex_enter(db->mutex);
109190   pOld = db->pCommitArg;
109191   db->xCommitCallback = xCallback;
109192   db->pCommitArg = pArg;
109193   sqlite3_mutex_leave(db->mutex);
109194   return pOld;
109195 }
109196
109197 /*
109198 ** Register a callback to be invoked each time a row is updated,
109199 ** inserted or deleted using this database connection.
109200 */
109201 SQLITE_API void *sqlite3_update_hook(
109202   sqlite3 *db,              /* Attach the hook to this database */
109203   void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
109204   void *pArg                /* Argument to the function */
109205 ){
109206   void *pRet;
109207   sqlite3_mutex_enter(db->mutex);
109208   pRet = db->pUpdateArg;
109209   db->xUpdateCallback = xCallback;
109210   db->pUpdateArg = pArg;
109211   sqlite3_mutex_leave(db->mutex);
109212   return pRet;
109213 }
109214
109215 /*
109216 ** Register a callback to be invoked each time a transaction is rolled
109217 ** back by this database connection.
109218 */
109219 SQLITE_API void *sqlite3_rollback_hook(
109220   sqlite3 *db,              /* Attach the hook to this database */
109221   void (*xCallback)(void*), /* Callback function */
109222   void *pArg                /* Argument to the function */
109223 ){
109224   void *pRet;
109225   sqlite3_mutex_enter(db->mutex);
109226   pRet = db->pRollbackArg;
109227   db->xRollbackCallback = xCallback;
109228   db->pRollbackArg = pArg;
109229   sqlite3_mutex_leave(db->mutex);
109230   return pRet;
109231 }
109232
109233 #ifndef SQLITE_OMIT_WAL
109234 /*
109235 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
109236 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
109237 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
109238 ** wal_autocheckpoint()).
109239 */ 
109240 SQLITE_PRIVATE int sqlite3WalDefaultHook(
109241   void *pClientData,     /* Argument */
109242   sqlite3 *db,           /* Connection */
109243   const char *zDb,       /* Database */
109244   int nFrame             /* Size of WAL */
109245 ){
109246   if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
109247     sqlite3BeginBenignMalloc();
109248     sqlite3_wal_checkpoint(db, zDb);
109249     sqlite3EndBenignMalloc();
109250   }
109251   return SQLITE_OK;
109252 }
109253 #endif /* SQLITE_OMIT_WAL */
109254
109255 /*
109256 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
109257 ** a database after committing a transaction if there are nFrame or
109258 ** more frames in the log file. Passing zero or a negative value as the
109259 ** nFrame parameter disables automatic checkpoints entirely.
109260 **
109261 ** The callback registered by this function replaces any existing callback
109262 ** registered using sqlite3_wal_hook(). Likewise, registering a callback
109263 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
109264 ** configured by this function.
109265 */
109266 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
109267 #ifdef SQLITE_OMIT_WAL
109268   UNUSED_PARAMETER(db);
109269   UNUSED_PARAMETER(nFrame);
109270 #else
109271   if( nFrame>0 ){
109272     sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
109273   }else{
109274     sqlite3_wal_hook(db, 0, 0);
109275   }
109276 #endif
109277   return SQLITE_OK;
109278 }
109279
109280 /*
109281 ** Register a callback to be invoked each time a transaction is written
109282 ** into the write-ahead-log by this database connection.
109283 */
109284 SQLITE_API void *sqlite3_wal_hook(
109285   sqlite3 *db,                    /* Attach the hook to this db handle */
109286   int(*xCallback)(void *, sqlite3*, const char*, int),
109287   void *pArg                      /* First argument passed to xCallback() */
109288 ){
109289 #ifndef SQLITE_OMIT_WAL
109290   void *pRet;
109291   sqlite3_mutex_enter(db->mutex);
109292   pRet = db->pWalArg;
109293   db->xWalCallback = xCallback;
109294   db->pWalArg = pArg;
109295   sqlite3_mutex_leave(db->mutex);
109296   return pRet;
109297 #else
109298   return 0;
109299 #endif
109300 }
109301
109302 /*
109303 ** Checkpoint database zDb.
109304 */
109305 SQLITE_API int sqlite3_wal_checkpoint_v2(
109306   sqlite3 *db,                    /* Database handle */
109307   const char *zDb,                /* Name of attached database (or NULL) */
109308   int eMode,                      /* SQLITE_CHECKPOINT_* value */
109309   int *pnLog,                     /* OUT: Size of WAL log in frames */
109310   int *pnCkpt                     /* OUT: Total number of frames checkpointed */
109311 ){
109312 #ifdef SQLITE_OMIT_WAL
109313   return SQLITE_OK;
109314 #else
109315   int rc;                         /* Return code */
109316   int iDb = SQLITE_MAX_ATTACHED;  /* sqlite3.aDb[] index of db to checkpoint */
109317
109318   /* Initialize the output variables to -1 in case an error occurs. */
109319   if( pnLog ) *pnLog = -1;
109320   if( pnCkpt ) *pnCkpt = -1;
109321
109322   assert( SQLITE_CHECKPOINT_FULL>SQLITE_CHECKPOINT_PASSIVE );
109323   assert( SQLITE_CHECKPOINT_FULL<SQLITE_CHECKPOINT_RESTART );
109324   assert( SQLITE_CHECKPOINT_PASSIVE+2==SQLITE_CHECKPOINT_RESTART );
109325   if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_RESTART ){
109326     return SQLITE_MISUSE;
109327   }
109328
109329   sqlite3_mutex_enter(db->mutex);
109330   if( zDb && zDb[0] ){
109331     iDb = sqlite3FindDbName(db, zDb);
109332   }
109333   if( iDb<0 ){
109334     rc = SQLITE_ERROR;
109335     sqlite3Error(db, SQLITE_ERROR, "unknown database: %s", zDb);
109336   }else{
109337     rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
109338     sqlite3Error(db, rc, 0);
109339   }
109340   rc = sqlite3ApiExit(db, rc);
109341   sqlite3_mutex_leave(db->mutex);
109342   return rc;
109343 #endif
109344 }
109345
109346
109347 /*
109348 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
109349 ** to contains a zero-length string, all attached databases are 
109350 ** checkpointed.
109351 */
109352 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
109353   return sqlite3_wal_checkpoint_v2(db, zDb, SQLITE_CHECKPOINT_PASSIVE, 0, 0);
109354 }
109355
109356 #ifndef SQLITE_OMIT_WAL
109357 /*
109358 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
109359 ** not currently open in WAL mode.
109360 **
109361 ** If a transaction is open on the database being checkpointed, this 
109362 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If 
109363 ** an error occurs while running the checkpoint, an SQLite error code is 
109364 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
109365 **
109366 ** The mutex on database handle db should be held by the caller. The mutex
109367 ** associated with the specific b-tree being checkpointed is taken by
109368 ** this function while the checkpoint is running.
109369 **
109370 ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
109371 ** checkpointed. If an error is encountered it is returned immediately -
109372 ** no attempt is made to checkpoint any remaining databases.
109373 **
109374 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
109375 */
109376 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
109377   int rc = SQLITE_OK;             /* Return code */
109378   int i;                          /* Used to iterate through attached dbs */
109379   int bBusy = 0;                  /* True if SQLITE_BUSY has been encountered */
109380
109381   assert( sqlite3_mutex_held(db->mutex) );
109382   assert( !pnLog || *pnLog==-1 );
109383   assert( !pnCkpt || *pnCkpt==-1 );
109384
109385   for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
109386     if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
109387       rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
109388       pnLog = 0;
109389       pnCkpt = 0;
109390       if( rc==SQLITE_BUSY ){
109391         bBusy = 1;
109392         rc = SQLITE_OK;
109393       }
109394     }
109395   }
109396
109397   return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
109398 }
109399 #endif /* SQLITE_OMIT_WAL */
109400
109401 /*
109402 ** This function returns true if main-memory should be used instead of
109403 ** a temporary file for transient pager files and statement journals.
109404 ** The value returned depends on the value of db->temp_store (runtime
109405 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
109406 ** following table describes the relationship between these two values
109407 ** and this functions return value.
109408 **
109409 **   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
109410 **   -----------------     --------------     ------------------------------
109411 **   0                     any                file      (return 0)
109412 **   1                     1                  file      (return 0)
109413 **   1                     2                  memory    (return 1)
109414 **   1                     0                  file      (return 0)
109415 **   2                     1                  file      (return 0)
109416 **   2                     2                  memory    (return 1)
109417 **   2                     0                  memory    (return 1)
109418 **   3                     any                memory    (return 1)
109419 */
109420 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
109421 #if SQLITE_TEMP_STORE==1
109422   return ( db->temp_store==2 );
109423 #endif
109424 #if SQLITE_TEMP_STORE==2
109425   return ( db->temp_store!=1 );
109426 #endif
109427 #if SQLITE_TEMP_STORE==3
109428   return 1;
109429 #endif
109430 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
109431   return 0;
109432 #endif
109433 }
109434
109435 /*
109436 ** Return UTF-8 encoded English language explanation of the most recent
109437 ** error.
109438 */
109439 SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
109440   const char *z;
109441   if( !db ){
109442     return sqlite3ErrStr(SQLITE_NOMEM);
109443   }
109444   if( !sqlite3SafetyCheckSickOrOk(db) ){
109445     return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
109446   }
109447   sqlite3_mutex_enter(db->mutex);
109448   if( db->mallocFailed ){
109449     z = sqlite3ErrStr(SQLITE_NOMEM);
109450   }else{
109451     z = (char*)sqlite3_value_text(db->pErr);
109452     assert( !db->mallocFailed );
109453     if( z==0 ){
109454       z = sqlite3ErrStr(db->errCode);
109455     }
109456   }
109457   sqlite3_mutex_leave(db->mutex);
109458   return z;
109459 }
109460
109461 #ifndef SQLITE_OMIT_UTF16
109462 /*
109463 ** Return UTF-16 encoded English language explanation of the most recent
109464 ** error.
109465 */
109466 SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
109467   static const u16 outOfMem[] = {
109468     'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
109469   };
109470   static const u16 misuse[] = {
109471     'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ', 
109472     'r', 'o', 'u', 't', 'i', 'n', 'e', ' ', 
109473     'c', 'a', 'l', 'l', 'e', 'd', ' ', 
109474     'o', 'u', 't', ' ', 
109475     'o', 'f', ' ', 
109476     's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
109477   };
109478
109479   const void *z;
109480   if( !db ){
109481     return (void *)outOfMem;
109482   }
109483   if( !sqlite3SafetyCheckSickOrOk(db) ){
109484     return (void *)misuse;
109485   }
109486   sqlite3_mutex_enter(db->mutex);
109487   if( db->mallocFailed ){
109488     z = (void *)outOfMem;
109489   }else{
109490     z = sqlite3_value_text16(db->pErr);
109491     if( z==0 ){
109492       sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
109493            SQLITE_UTF8, SQLITE_STATIC);
109494       z = sqlite3_value_text16(db->pErr);
109495     }
109496     /* A malloc() may have failed within the call to sqlite3_value_text16()
109497     ** above. If this is the case, then the db->mallocFailed flag needs to
109498     ** be cleared before returning. Do this directly, instead of via
109499     ** sqlite3ApiExit(), to avoid setting the database handle error message.
109500     */
109501     db->mallocFailed = 0;
109502   }
109503   sqlite3_mutex_leave(db->mutex);
109504   return z;
109505 }
109506 #endif /* SQLITE_OMIT_UTF16 */
109507
109508 /*
109509 ** Return the most recent error code generated by an SQLite routine. If NULL is
109510 ** passed to this function, we assume a malloc() failed during sqlite3_open().
109511 */
109512 SQLITE_API int sqlite3_errcode(sqlite3 *db){
109513   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
109514     return SQLITE_MISUSE_BKPT;
109515   }
109516   if( !db || db->mallocFailed ){
109517     return SQLITE_NOMEM;
109518   }
109519   return db->errCode & db->errMask;
109520 }
109521 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
109522   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
109523     return SQLITE_MISUSE_BKPT;
109524   }
109525   if( !db || db->mallocFailed ){
109526     return SQLITE_NOMEM;
109527   }
109528   return db->errCode;
109529 }
109530
109531 /*
109532 ** Create a new collating function for database "db".  The name is zName
109533 ** and the encoding is enc.
109534 */
109535 static int createCollation(
109536   sqlite3* db,
109537   const char *zName, 
109538   u8 enc,
109539   u8 collType,
109540   void* pCtx,
109541   int(*xCompare)(void*,int,const void*,int,const void*),
109542   void(*xDel)(void*)
109543 ){
109544   CollSeq *pColl;
109545   int enc2;
109546   int nName = sqlite3Strlen30(zName);
109547   
109548   assert( sqlite3_mutex_held(db->mutex) );
109549
109550   /* If SQLITE_UTF16 is specified as the encoding type, transform this
109551   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
109552   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
109553   */
109554   enc2 = enc;
109555   testcase( enc2==SQLITE_UTF16 );
109556   testcase( enc2==SQLITE_UTF16_ALIGNED );
109557   if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
109558     enc2 = SQLITE_UTF16NATIVE;
109559   }
109560   if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
109561     return SQLITE_MISUSE_BKPT;
109562   }
109563
109564   /* Check if this call is removing or replacing an existing collation 
109565   ** sequence. If so, and there are active VMs, return busy. If there
109566   ** are no active VMs, invalidate any pre-compiled statements.
109567   */
109568   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
109569   if( pColl && pColl->xCmp ){
109570     if( db->activeVdbeCnt ){
109571       sqlite3Error(db, SQLITE_BUSY, 
109572         "unable to delete/modify collation sequence due to active statements");
109573       return SQLITE_BUSY;
109574     }
109575     sqlite3ExpirePreparedStatements(db);
109576
109577     /* If collation sequence pColl was created directly by a call to
109578     ** sqlite3_create_collation, and not generated by synthCollSeq(),
109579     ** then any copies made by synthCollSeq() need to be invalidated.
109580     ** Also, collation destructor - CollSeq.xDel() - function may need
109581     ** to be called.
109582     */ 
109583     if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
109584       CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
109585       int j;
109586       for(j=0; j<3; j++){
109587         CollSeq *p = &aColl[j];
109588         if( p->enc==pColl->enc ){
109589           if( p->xDel ){
109590             p->xDel(p->pUser);
109591           }
109592           p->xCmp = 0;
109593         }
109594       }
109595     }
109596   }
109597
109598   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
109599   if( pColl==0 ) return SQLITE_NOMEM;
109600   pColl->xCmp = xCompare;
109601   pColl->pUser = pCtx;
109602   pColl->xDel = xDel;
109603   pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
109604   pColl->type = collType;
109605   sqlite3Error(db, SQLITE_OK, 0);
109606   return SQLITE_OK;
109607 }
109608
109609
109610 /*
109611 ** This array defines hard upper bounds on limit values.  The
109612 ** initializer must be kept in sync with the SQLITE_LIMIT_*
109613 ** #defines in sqlite3.h.
109614 */
109615 static const int aHardLimit[] = {
109616   SQLITE_MAX_LENGTH,
109617   SQLITE_MAX_SQL_LENGTH,
109618   SQLITE_MAX_COLUMN,
109619   SQLITE_MAX_EXPR_DEPTH,
109620   SQLITE_MAX_COMPOUND_SELECT,
109621   SQLITE_MAX_VDBE_OP,
109622   SQLITE_MAX_FUNCTION_ARG,
109623   SQLITE_MAX_ATTACHED,
109624   SQLITE_MAX_LIKE_PATTERN_LENGTH,
109625   SQLITE_MAX_VARIABLE_NUMBER,
109626   SQLITE_MAX_TRIGGER_DEPTH,
109627 };
109628
109629 /*
109630 ** Make sure the hard limits are set to reasonable values
109631 */
109632 #if SQLITE_MAX_LENGTH<100
109633 # error SQLITE_MAX_LENGTH must be at least 100
109634 #endif
109635 #if SQLITE_MAX_SQL_LENGTH<100
109636 # error SQLITE_MAX_SQL_LENGTH must be at least 100
109637 #endif
109638 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
109639 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
109640 #endif
109641 #if SQLITE_MAX_COMPOUND_SELECT<2
109642 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
109643 #endif
109644 #if SQLITE_MAX_VDBE_OP<40
109645 # error SQLITE_MAX_VDBE_OP must be at least 40
109646 #endif
109647 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
109648 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
109649 #endif
109650 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>62
109651 # error SQLITE_MAX_ATTACHED must be between 0 and 62
109652 #endif
109653 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
109654 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
109655 #endif
109656 #if SQLITE_MAX_COLUMN>32767
109657 # error SQLITE_MAX_COLUMN must not exceed 32767
109658 #endif
109659 #if SQLITE_MAX_TRIGGER_DEPTH<1
109660 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
109661 #endif
109662
109663
109664 /*
109665 ** Change the value of a limit.  Report the old value.
109666 ** If an invalid limit index is supplied, report -1.
109667 ** Make no changes but still report the old value if the
109668 ** new limit is negative.
109669 **
109670 ** A new lower limit does not shrink existing constructs.
109671 ** It merely prevents new constructs that exceed the limit
109672 ** from forming.
109673 */
109674 SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
109675   int oldLimit;
109676
109677
109678   /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
109679   ** there is a hard upper bound set at compile-time by a C preprocessor
109680   ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
109681   ** "_MAX_".)
109682   */
109683   assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
109684   assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
109685   assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
109686   assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
109687   assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
109688   assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
109689   assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
109690   assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
109691   assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
109692                                                SQLITE_MAX_LIKE_PATTERN_LENGTH );
109693   assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
109694   assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
109695   assert( SQLITE_LIMIT_TRIGGER_DEPTH==(SQLITE_N_LIMIT-1) );
109696
109697
109698   if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
109699     return -1;
109700   }
109701   oldLimit = db->aLimit[limitId];
109702   if( newLimit>=0 ){                   /* IMP: R-52476-28732 */
109703     if( newLimit>aHardLimit[limitId] ){
109704       newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */
109705     }
109706     db->aLimit[limitId] = newLimit;
109707   }
109708   return oldLimit;                     /* IMP: R-53341-35419 */
109709 }
109710
109711 /*
109712 ** This function is used to parse both URIs and non-URI filenames passed by the
109713 ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
109714 ** URIs specified as part of ATTACH statements.
109715 **
109716 ** The first argument to this function is the name of the VFS to use (or
109717 ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
109718 ** query parameter. The second argument contains the URI (or non-URI filename)
109719 ** itself. When this function is called the *pFlags variable should contain
109720 ** the default flags to open the database handle with. The value stored in
109721 ** *pFlags may be updated before returning if the URI filename contains 
109722 ** "cache=xxx" or "mode=xxx" query parameters.
109723 **
109724 ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
109725 ** the VFS that should be used to open the database file. *pzFile is set to
109726 ** point to a buffer containing the name of the file to open. It is the 
109727 ** responsibility of the caller to eventually call sqlite3_free() to release
109728 ** this buffer.
109729 **
109730 ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
109731 ** may be set to point to a buffer containing an English language error 
109732 ** message. It is the responsibility of the caller to eventually release
109733 ** this buffer by calling sqlite3_free().
109734 */
109735 SQLITE_PRIVATE int sqlite3ParseUri(
109736   const char *zDefaultVfs,        /* VFS to use if no "vfs=xxx" query option */
109737   const char *zUri,               /* Nul-terminated URI to parse */
109738   unsigned int *pFlags,           /* IN/OUT: SQLITE_OPEN_XXX flags */
109739   sqlite3_vfs **ppVfs,            /* OUT: VFS to use */ 
109740   char **pzFile,                  /* OUT: Filename component of URI */
109741   char **pzErrMsg                 /* OUT: Error message (if rc!=SQLITE_OK) */
109742 ){
109743   int rc = SQLITE_OK;
109744   unsigned int flags = *pFlags;
109745   const char *zVfs = zDefaultVfs;
109746   char *zFile;
109747   char c;
109748   int nUri = sqlite3Strlen30(zUri);
109749
109750   assert( *pzErrMsg==0 );
109751
109752   if( ((flags & SQLITE_OPEN_URI) || sqlite3GlobalConfig.bOpenUri) 
109753    && nUri>=5 && memcmp(zUri, "file:", 5)==0 
109754   ){
109755     char *zOpt;
109756     int eState;                   /* Parser state when parsing URI */
109757     int iIn;                      /* Input character index */
109758     int iOut = 0;                 /* Output character index */
109759     int nByte = nUri+2;           /* Bytes of space to allocate */
109760
109761     /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen 
109762     ** method that there may be extra parameters following the file-name.  */
109763     flags |= SQLITE_OPEN_URI;
109764
109765     for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
109766     zFile = sqlite3_malloc(nByte);
109767     if( !zFile ) return SQLITE_NOMEM;
109768
109769     /* Discard the scheme and authority segments of the URI. */
109770     if( zUri[5]=='/' && zUri[6]=='/' ){
109771       iIn = 7;
109772       while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
109773
109774       if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
109775         *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s", 
109776             iIn-7, &zUri[7]);
109777         rc = SQLITE_ERROR;
109778         goto parse_uri_out;
109779       }
109780     }else{
109781       iIn = 5;
109782     }
109783
109784     /* Copy the filename and any query parameters into the zFile buffer. 
109785     ** Decode %HH escape codes along the way. 
109786     **
109787     ** Within this loop, variable eState may be set to 0, 1 or 2, depending
109788     ** on the parsing context. As follows:
109789     **
109790     **   0: Parsing file-name.
109791     **   1: Parsing name section of a name=value query parameter.
109792     **   2: Parsing value section of a name=value query parameter.
109793     */
109794     eState = 0;
109795     while( (c = zUri[iIn])!=0 && c!='#' ){
109796       iIn++;
109797       if( c=='%' 
109798        && sqlite3Isxdigit(zUri[iIn]) 
109799        && sqlite3Isxdigit(zUri[iIn+1]) 
109800       ){
109801         int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
109802         octet += sqlite3HexToInt(zUri[iIn++]);
109803
109804         assert( octet>=0 && octet<256 );
109805         if( octet==0 ){
109806           /* This branch is taken when "%00" appears within the URI. In this
109807           ** case we ignore all text in the remainder of the path, name or
109808           ** value currently being parsed. So ignore the current character
109809           ** and skip to the next "?", "=" or "&", as appropriate. */
109810           while( (c = zUri[iIn])!=0 && c!='#' 
109811               && (eState!=0 || c!='?')
109812               && (eState!=1 || (c!='=' && c!='&'))
109813               && (eState!=2 || c!='&')
109814           ){
109815             iIn++;
109816           }
109817           continue;
109818         }
109819         c = octet;
109820       }else if( eState==1 && (c=='&' || c=='=') ){
109821         if( zFile[iOut-1]==0 ){
109822           /* An empty option name. Ignore this option altogether. */
109823           while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
109824           continue;
109825         }
109826         if( c=='&' ){
109827           zFile[iOut++] = '\0';
109828         }else{
109829           eState = 2;
109830         }
109831         c = 0;
109832       }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
109833         c = 0;
109834         eState = 1;
109835       }
109836       zFile[iOut++] = c;
109837     }
109838     if( eState==1 ) zFile[iOut++] = '\0';
109839     zFile[iOut++] = '\0';
109840     zFile[iOut++] = '\0';
109841
109842     /* Check if there were any options specified that should be interpreted 
109843     ** here. Options that are interpreted here include "vfs" and those that
109844     ** correspond to flags that may be passed to the sqlite3_open_v2()
109845     ** method. */
109846     zOpt = &zFile[sqlite3Strlen30(zFile)+1];
109847     while( zOpt[0] ){
109848       int nOpt = sqlite3Strlen30(zOpt);
109849       char *zVal = &zOpt[nOpt+1];
109850       int nVal = sqlite3Strlen30(zVal);
109851
109852       if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
109853         zVfs = zVal;
109854       }else{
109855         struct OpenMode {
109856           const char *z;
109857           int mode;
109858         } *aMode = 0;
109859         char *zModeType = 0;
109860         int mask = 0;
109861         int limit = 0;
109862
109863         if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
109864           static struct OpenMode aCacheMode[] = {
109865             { "shared",  SQLITE_OPEN_SHAREDCACHE },
109866             { "private", SQLITE_OPEN_PRIVATECACHE },
109867             { 0, 0 }
109868           };
109869
109870           mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
109871           aMode = aCacheMode;
109872           limit = mask;
109873           zModeType = "cache";
109874         }
109875         if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
109876           static struct OpenMode aOpenMode[] = {
109877             { "ro",  SQLITE_OPEN_READONLY },
109878             { "rw",  SQLITE_OPEN_READWRITE }, 
109879             { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
109880             { 0, 0 }
109881           };
109882
109883           mask = SQLITE_OPEN_READONLY|SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
109884           aMode = aOpenMode;
109885           limit = mask & flags;
109886           zModeType = "access";
109887         }
109888
109889         if( aMode ){
109890           int i;
109891           int mode = 0;
109892           for(i=0; aMode[i].z; i++){
109893             const char *z = aMode[i].z;
109894             if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
109895               mode = aMode[i].mode;
109896               break;
109897             }
109898           }
109899           if( mode==0 ){
109900             *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
109901             rc = SQLITE_ERROR;
109902             goto parse_uri_out;
109903           }
109904           if( mode>limit ){
109905             *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
109906                                         zModeType, zVal);
109907             rc = SQLITE_PERM;
109908             goto parse_uri_out;
109909           }
109910           flags = (flags & ~mask) | mode;
109911         }
109912       }
109913
109914       zOpt = &zVal[nVal+1];
109915     }
109916
109917   }else{
109918     zFile = sqlite3_malloc(nUri+2);
109919     if( !zFile ) return SQLITE_NOMEM;
109920     memcpy(zFile, zUri, nUri);
109921     zFile[nUri] = '\0';
109922     zFile[nUri+1] = '\0';
109923   }
109924
109925   *ppVfs = sqlite3_vfs_find(zVfs);
109926   if( *ppVfs==0 ){
109927     *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
109928     rc = SQLITE_ERROR;
109929   }
109930  parse_uri_out:
109931   if( rc!=SQLITE_OK ){
109932     sqlite3_free(zFile);
109933     zFile = 0;
109934   }
109935   *pFlags = flags;
109936   *pzFile = zFile;
109937   return rc;
109938 }
109939
109940
109941 /*
109942 ** This routine does the work of opening a database on behalf of
109943 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"  
109944 ** is UTF-8 encoded.
109945 */
109946 static int openDatabase(
109947   const char *zFilename, /* Database filename UTF-8 encoded */
109948   sqlite3 **ppDb,        /* OUT: Returned database handle */
109949   unsigned int flags,    /* Operational flags */
109950   const char *zVfs       /* Name of the VFS to use */
109951 ){
109952   sqlite3 *db;                    /* Store allocated handle here */
109953   int rc;                         /* Return code */
109954   int isThreadsafe;               /* True for threadsafe connections */
109955   char *zOpen = 0;                /* Filename argument to pass to BtreeOpen() */
109956   char *zErrMsg = 0;              /* Error message from sqlite3ParseUri() */
109957
109958   *ppDb = 0;
109959 #ifndef SQLITE_OMIT_AUTOINIT
109960   rc = sqlite3_initialize();
109961   if( rc ) return rc;
109962 #endif
109963
109964   /* Only allow sensible combinations of bits in the flags argument.  
109965   ** Throw an error if any non-sense combination is used.  If we
109966   ** do not block illegal combinations here, it could trigger
109967   ** assert() statements in deeper layers.  Sensible combinations
109968   ** are:
109969   **
109970   **  1:  SQLITE_OPEN_READONLY
109971   **  2:  SQLITE_OPEN_READWRITE
109972   **  6:  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
109973   */
109974   assert( SQLITE_OPEN_READONLY  == 0x01 );
109975   assert( SQLITE_OPEN_READWRITE == 0x02 );
109976   assert( SQLITE_OPEN_CREATE    == 0x04 );
109977   testcase( (1<<(flags&7))==0x02 ); /* READONLY */
109978   testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
109979   testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
109980   if( ((1<<(flags&7)) & 0x46)==0 ) return SQLITE_MISUSE_BKPT;
109981
109982   if( sqlite3GlobalConfig.bCoreMutex==0 ){
109983     isThreadsafe = 0;
109984   }else if( flags & SQLITE_OPEN_NOMUTEX ){
109985     isThreadsafe = 0;
109986   }else if( flags & SQLITE_OPEN_FULLMUTEX ){
109987     isThreadsafe = 1;
109988   }else{
109989     isThreadsafe = sqlite3GlobalConfig.bFullMutex;
109990   }
109991   if( flags & SQLITE_OPEN_PRIVATECACHE ){
109992     flags &= ~SQLITE_OPEN_SHAREDCACHE;
109993   }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
109994     flags |= SQLITE_OPEN_SHAREDCACHE;
109995   }
109996
109997   /* Remove harmful bits from the flags parameter
109998   **
109999   ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
110000   ** dealt with in the previous code block.  Besides these, the only
110001   ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
110002   ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
110003   ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits.  Silently mask
110004   ** off all other flags.
110005   */
110006   flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
110007                SQLITE_OPEN_EXCLUSIVE |
110008                SQLITE_OPEN_MAIN_DB |
110009                SQLITE_OPEN_TEMP_DB | 
110010                SQLITE_OPEN_TRANSIENT_DB | 
110011                SQLITE_OPEN_MAIN_JOURNAL | 
110012                SQLITE_OPEN_TEMP_JOURNAL | 
110013                SQLITE_OPEN_SUBJOURNAL | 
110014                SQLITE_OPEN_MASTER_JOURNAL |
110015                SQLITE_OPEN_NOMUTEX |
110016                SQLITE_OPEN_FULLMUTEX |
110017                SQLITE_OPEN_WAL
110018              );
110019
110020   /* Allocate the sqlite data structure */
110021   db = sqlite3MallocZero( sizeof(sqlite3) );
110022   if( db==0 ) goto opendb_out;
110023   if( isThreadsafe ){
110024     db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
110025     if( db->mutex==0 ){
110026       sqlite3_free(db);
110027       db = 0;
110028       goto opendb_out;
110029     }
110030   }
110031   sqlite3_mutex_enter(db->mutex);
110032   db->errMask = 0xff;
110033   db->nDb = 2;
110034   db->magic = SQLITE_MAGIC_BUSY;
110035   db->aDb = db->aDbStatic;
110036
110037   assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
110038   memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
110039   db->autoCommit = 1;
110040   db->nextAutovac = -1;
110041   db->nextPagesize = 0;
110042   db->flags |= SQLITE_ShortColNames | SQLITE_AutoIndex | SQLITE_EnableTrigger
110043 #if SQLITE_DEFAULT_FILE_FORMAT<4
110044                  | SQLITE_LegacyFileFmt
110045 #endif
110046 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
110047                  | SQLITE_LoadExtension
110048 #endif
110049 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
110050                  | SQLITE_RecTriggers
110051 #endif
110052 #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
110053                  | SQLITE_ForeignKeys
110054 #endif
110055       ;
110056   sqlite3HashInit(&db->aCollSeq);
110057 #ifndef SQLITE_OMIT_VIRTUALTABLE
110058   sqlite3HashInit(&db->aModule);
110059 #endif
110060
110061   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
110062   ** and UTF-16, so add a version for each to avoid any unnecessary
110063   ** conversions. The only error that can occur here is a malloc() failure.
110064   */
110065   createCollation(db, "BINARY", SQLITE_UTF8, SQLITE_COLL_BINARY, 0,
110066                   binCollFunc, 0);
110067   createCollation(db, "BINARY", SQLITE_UTF16BE, SQLITE_COLL_BINARY, 0,
110068                   binCollFunc, 0);
110069   createCollation(db, "BINARY", SQLITE_UTF16LE, SQLITE_COLL_BINARY, 0,
110070                   binCollFunc, 0);
110071   createCollation(db, "RTRIM", SQLITE_UTF8, SQLITE_COLL_USER, (void*)1,
110072                   binCollFunc, 0);
110073   if( db->mallocFailed ){
110074     goto opendb_out;
110075   }
110076   db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
110077   assert( db->pDfltColl!=0 );
110078
110079   /* Also add a UTF-8 case-insensitive collation sequence. */
110080   createCollation(db, "NOCASE", SQLITE_UTF8, SQLITE_COLL_NOCASE, 0,
110081                   nocaseCollatingFunc, 0);
110082
110083   /* Parse the filename/URI argument. */
110084   db->openFlags = flags;
110085   rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
110086   if( rc!=SQLITE_OK ){
110087     if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
110088     sqlite3Error(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
110089     sqlite3_free(zErrMsg);
110090     goto opendb_out;
110091   }
110092
110093   /* Open the backend database driver */
110094   rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
110095                         flags | SQLITE_OPEN_MAIN_DB);
110096   if( rc!=SQLITE_OK ){
110097     if( rc==SQLITE_IOERR_NOMEM ){
110098       rc = SQLITE_NOMEM;
110099     }
110100     sqlite3Error(db, rc, 0);
110101     goto opendb_out;
110102   }
110103   db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
110104   db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
110105
110106
110107   /* The default safety_level for the main database is 'full'; for the temp
110108   ** database it is 'NONE'. This matches the pager layer defaults.  
110109   */
110110   db->aDb[0].zName = "main";
110111   db->aDb[0].safety_level = 3;
110112   db->aDb[1].zName = "temp";
110113   db->aDb[1].safety_level = 1;
110114
110115   db->magic = SQLITE_MAGIC_OPEN;
110116   if( db->mallocFailed ){
110117     goto opendb_out;
110118   }
110119
110120   /* Register all built-in functions, but do not attempt to read the
110121   ** database schema yet. This is delayed until the first time the database
110122   ** is accessed.
110123   */
110124   sqlite3Error(db, SQLITE_OK, 0);
110125   sqlite3RegisterBuiltinFunctions(db);
110126
110127   /* Load automatic extensions - extensions that have been registered
110128   ** using the sqlite3_automatic_extension() API.
110129   */
110130   sqlite3AutoLoadExtensions(db);
110131   rc = sqlite3_errcode(db);
110132   if( rc!=SQLITE_OK ){
110133     goto opendb_out;
110134   }
110135
110136 #ifdef SQLITE_ENABLE_FTS1
110137   if( !db->mallocFailed ){
110138     extern int sqlite3Fts1Init(sqlite3*);
110139     rc = sqlite3Fts1Init(db);
110140   }
110141 #endif
110142
110143 #ifdef SQLITE_ENABLE_FTS2
110144   if( !db->mallocFailed && rc==SQLITE_OK ){
110145     extern int sqlite3Fts2Init(sqlite3*);
110146     rc = sqlite3Fts2Init(db);
110147   }
110148 #endif
110149
110150 #ifdef SQLITE_ENABLE_FTS3
110151   if( !db->mallocFailed && rc==SQLITE_OK ){
110152     rc = sqlite3Fts3Init(db);
110153   }
110154 #endif
110155
110156 #ifdef SQLITE_ENABLE_ICU
110157   if( !db->mallocFailed && rc==SQLITE_OK ){
110158     rc = sqlite3IcuInit(db);
110159   }
110160 #endif
110161
110162 #ifdef SQLITE_ENABLE_RTREE
110163   if( !db->mallocFailed && rc==SQLITE_OK){
110164     rc = sqlite3RtreeInit(db);
110165   }
110166 #endif
110167
110168   sqlite3Error(db, rc, 0);
110169
110170   /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
110171   ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
110172   ** mode.  Doing nothing at all also makes NORMAL the default.
110173   */
110174 #ifdef SQLITE_DEFAULT_LOCKING_MODE
110175   db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
110176   sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
110177                           SQLITE_DEFAULT_LOCKING_MODE);
110178 #endif
110179
110180   /* Enable the lookaside-malloc subsystem */
110181   setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
110182                         sqlite3GlobalConfig.nLookaside);
110183
110184   sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
110185
110186 opendb_out:
110187   sqlite3_free(zOpen);
110188   if( db ){
110189     assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
110190     sqlite3_mutex_leave(db->mutex);
110191   }
110192   rc = sqlite3_errcode(db);
110193   if( rc==SQLITE_NOMEM ){
110194     sqlite3_close(db);
110195     db = 0;
110196   }else if( rc!=SQLITE_OK ){
110197     db->magic = SQLITE_MAGIC_SICK;
110198   }
110199   *ppDb = db;
110200   return sqlite3ApiExit(0, rc);
110201 }
110202
110203 /*
110204 ** Open a new database handle.
110205 */
110206 SQLITE_API int sqlite3_open(
110207   const char *zFilename, 
110208   sqlite3 **ppDb 
110209 ){
110210   return openDatabase(zFilename, ppDb,
110211                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
110212 }
110213 SQLITE_API int sqlite3_open_v2(
110214   const char *filename,   /* Database filename (UTF-8) */
110215   sqlite3 **ppDb,         /* OUT: SQLite db handle */
110216   int flags,              /* Flags */
110217   const char *zVfs        /* Name of VFS module to use */
110218 ){
110219   return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
110220 }
110221
110222 #ifndef SQLITE_OMIT_UTF16
110223 /*
110224 ** Open a new database handle.
110225 */
110226 SQLITE_API int sqlite3_open16(
110227   const void *zFilename, 
110228   sqlite3 **ppDb
110229 ){
110230   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
110231   sqlite3_value *pVal;
110232   int rc;
110233
110234   assert( zFilename );
110235   assert( ppDb );
110236   *ppDb = 0;
110237 #ifndef SQLITE_OMIT_AUTOINIT
110238   rc = sqlite3_initialize();
110239   if( rc ) return rc;
110240 #endif
110241   pVal = sqlite3ValueNew(0);
110242   sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
110243   zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
110244   if( zFilename8 ){
110245     rc = openDatabase(zFilename8, ppDb,
110246                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
110247     assert( *ppDb || rc==SQLITE_NOMEM );
110248     if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
110249       ENC(*ppDb) = SQLITE_UTF16NATIVE;
110250     }
110251   }else{
110252     rc = SQLITE_NOMEM;
110253   }
110254   sqlite3ValueFree(pVal);
110255
110256   return sqlite3ApiExit(0, rc);
110257 }
110258 #endif /* SQLITE_OMIT_UTF16 */
110259
110260 /*
110261 ** Register a new collation sequence with the database handle db.
110262 */
110263 SQLITE_API int sqlite3_create_collation(
110264   sqlite3* db, 
110265   const char *zName, 
110266   int enc, 
110267   void* pCtx,
110268   int(*xCompare)(void*,int,const void*,int,const void*)
110269 ){
110270   int rc;
110271   sqlite3_mutex_enter(db->mutex);
110272   assert( !db->mallocFailed );
110273   rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
110274   rc = sqlite3ApiExit(db, rc);
110275   sqlite3_mutex_leave(db->mutex);
110276   return rc;
110277 }
110278
110279 /*
110280 ** Register a new collation sequence with the database handle db.
110281 */
110282 SQLITE_API int sqlite3_create_collation_v2(
110283   sqlite3* db, 
110284   const char *zName, 
110285   int enc, 
110286   void* pCtx,
110287   int(*xCompare)(void*,int,const void*,int,const void*),
110288   void(*xDel)(void*)
110289 ){
110290   int rc;
110291   sqlite3_mutex_enter(db->mutex);
110292   assert( !db->mallocFailed );
110293   rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, xDel);
110294   rc = sqlite3ApiExit(db, rc);
110295   sqlite3_mutex_leave(db->mutex);
110296   return rc;
110297 }
110298
110299 #ifndef SQLITE_OMIT_UTF16
110300 /*
110301 ** Register a new collation sequence with the database handle db.
110302 */
110303 SQLITE_API int sqlite3_create_collation16(
110304   sqlite3* db, 
110305   const void *zName,
110306   int enc, 
110307   void* pCtx,
110308   int(*xCompare)(void*,int,const void*,int,const void*)
110309 ){
110310   int rc = SQLITE_OK;
110311   char *zName8;
110312   sqlite3_mutex_enter(db->mutex);
110313   assert( !db->mallocFailed );
110314   zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
110315   if( zName8 ){
110316     rc = createCollation(db, zName8, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
110317     sqlite3DbFree(db, zName8);
110318   }
110319   rc = sqlite3ApiExit(db, rc);
110320   sqlite3_mutex_leave(db->mutex);
110321   return rc;
110322 }
110323 #endif /* SQLITE_OMIT_UTF16 */
110324
110325 /*
110326 ** Register a collation sequence factory callback with the database handle
110327 ** db. Replace any previously installed collation sequence factory.
110328 */
110329 SQLITE_API int sqlite3_collation_needed(
110330   sqlite3 *db, 
110331   void *pCollNeededArg, 
110332   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
110333 ){
110334   sqlite3_mutex_enter(db->mutex);
110335   db->xCollNeeded = xCollNeeded;
110336   db->xCollNeeded16 = 0;
110337   db->pCollNeededArg = pCollNeededArg;
110338   sqlite3_mutex_leave(db->mutex);
110339   return SQLITE_OK;
110340 }
110341
110342 #ifndef SQLITE_OMIT_UTF16
110343 /*
110344 ** Register a collation sequence factory callback with the database handle
110345 ** db. Replace any previously installed collation sequence factory.
110346 */
110347 SQLITE_API int sqlite3_collation_needed16(
110348   sqlite3 *db, 
110349   void *pCollNeededArg, 
110350   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
110351 ){
110352   sqlite3_mutex_enter(db->mutex);
110353   db->xCollNeeded = 0;
110354   db->xCollNeeded16 = xCollNeeded16;
110355   db->pCollNeededArg = pCollNeededArg;
110356   sqlite3_mutex_leave(db->mutex);
110357   return SQLITE_OK;
110358 }
110359 #endif /* SQLITE_OMIT_UTF16 */
110360
110361 #ifndef SQLITE_OMIT_DEPRECATED
110362 /*
110363 ** This function is now an anachronism. It used to be used to recover from a
110364 ** malloc() failure, but SQLite now does this automatically.
110365 */
110366 SQLITE_API int sqlite3_global_recover(void){
110367   return SQLITE_OK;
110368 }
110369 #endif
110370
110371 /*
110372 ** Test to see whether or not the database connection is in autocommit
110373 ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
110374 ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
110375 ** by the next COMMIT or ROLLBACK.
110376 **
110377 ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
110378 */
110379 SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
110380   return db->autoCommit;
110381 }
110382
110383 /*
110384 ** The following routines are subtitutes for constants SQLITE_CORRUPT,
110385 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
110386 ** constants.  They server two purposes:
110387 **
110388 **   1.  Serve as a convenient place to set a breakpoint in a debugger
110389 **       to detect when version error conditions occurs.
110390 **
110391 **   2.  Invoke sqlite3_log() to provide the source code location where
110392 **       a low-level error is first detected.
110393 */
110394 SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
110395   testcase( sqlite3GlobalConfig.xLog!=0 );
110396   sqlite3_log(SQLITE_CORRUPT,
110397               "database corruption at line %d of [%.10s]",
110398               lineno, 20+sqlite3_sourceid());
110399   return SQLITE_CORRUPT;
110400 }
110401 SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
110402   testcase( sqlite3GlobalConfig.xLog!=0 );
110403   sqlite3_log(SQLITE_MISUSE, 
110404               "misuse at line %d of [%.10s]",
110405               lineno, 20+sqlite3_sourceid());
110406   return SQLITE_MISUSE;
110407 }
110408 SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
110409   testcase( sqlite3GlobalConfig.xLog!=0 );
110410   sqlite3_log(SQLITE_CANTOPEN, 
110411               "cannot open file at line %d of [%.10s]",
110412               lineno, 20+sqlite3_sourceid());
110413   return SQLITE_CANTOPEN;
110414 }
110415
110416
110417 #ifndef SQLITE_OMIT_DEPRECATED
110418 /*
110419 ** This is a convenience routine that makes sure that all thread-specific
110420 ** data for this thread has been deallocated.
110421 **
110422 ** SQLite no longer uses thread-specific data so this routine is now a
110423 ** no-op.  It is retained for historical compatibility.
110424 */
110425 SQLITE_API void sqlite3_thread_cleanup(void){
110426 }
110427 #endif
110428
110429 /*
110430 ** Return meta information about a specific column of a database table.
110431 ** See comment in sqlite3.h (sqlite.h.in) for details.
110432 */
110433 #ifdef SQLITE_ENABLE_COLUMN_METADATA
110434 SQLITE_API int sqlite3_table_column_metadata(
110435   sqlite3 *db,                /* Connection handle */
110436   const char *zDbName,        /* Database name or NULL */
110437   const char *zTableName,     /* Table name */
110438   const char *zColumnName,    /* Column name */
110439   char const **pzDataType,    /* OUTPUT: Declared data type */
110440   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
110441   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
110442   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
110443   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
110444 ){
110445   int rc;
110446   char *zErrMsg = 0;
110447   Table *pTab = 0;
110448   Column *pCol = 0;
110449   int iCol;
110450
110451   char const *zDataType = 0;
110452   char const *zCollSeq = 0;
110453   int notnull = 0;
110454   int primarykey = 0;
110455   int autoinc = 0;
110456
110457   /* Ensure the database schema has been loaded */
110458   sqlite3_mutex_enter(db->mutex);
110459   sqlite3BtreeEnterAll(db);
110460   rc = sqlite3Init(db, &zErrMsg);
110461   if( SQLITE_OK!=rc ){
110462     goto error_out;
110463   }
110464
110465   /* Locate the table in question */
110466   pTab = sqlite3FindTable(db, zTableName, zDbName);
110467   if( !pTab || pTab->pSelect ){
110468     pTab = 0;
110469     goto error_out;
110470   }
110471
110472   /* Find the column for which info is requested */
110473   if( sqlite3IsRowid(zColumnName) ){
110474     iCol = pTab->iPKey;
110475     if( iCol>=0 ){
110476       pCol = &pTab->aCol[iCol];
110477     }
110478   }else{
110479     for(iCol=0; iCol<pTab->nCol; iCol++){
110480       pCol = &pTab->aCol[iCol];
110481       if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
110482         break;
110483       }
110484     }
110485     if( iCol==pTab->nCol ){
110486       pTab = 0;
110487       goto error_out;
110488     }
110489   }
110490
110491   /* The following block stores the meta information that will be returned
110492   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
110493   ** and autoinc. At this point there are two possibilities:
110494   ** 
110495   **     1. The specified column name was rowid", "oid" or "_rowid_" 
110496   **        and there is no explicitly declared IPK column. 
110497   **
110498   **     2. The table is not a view and the column name identified an 
110499   **        explicitly declared column. Copy meta information from *pCol.
110500   */ 
110501   if( pCol ){
110502     zDataType = pCol->zType;
110503     zCollSeq = pCol->zColl;
110504     notnull = pCol->notNull!=0;
110505     primarykey  = pCol->isPrimKey!=0;
110506     autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
110507   }else{
110508     zDataType = "INTEGER";
110509     primarykey = 1;
110510   }
110511   if( !zCollSeq ){
110512     zCollSeq = "BINARY";
110513   }
110514
110515 error_out:
110516   sqlite3BtreeLeaveAll(db);
110517
110518   /* Whether the function call succeeded or failed, set the output parameters
110519   ** to whatever their local counterparts contain. If an error did occur,
110520   ** this has the effect of zeroing all output parameters.
110521   */
110522   if( pzDataType ) *pzDataType = zDataType;
110523   if( pzCollSeq ) *pzCollSeq = zCollSeq;
110524   if( pNotNull ) *pNotNull = notnull;
110525   if( pPrimaryKey ) *pPrimaryKey = primarykey;
110526   if( pAutoinc ) *pAutoinc = autoinc;
110527
110528   if( SQLITE_OK==rc && !pTab ){
110529     sqlite3DbFree(db, zErrMsg);
110530     zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
110531         zColumnName);
110532     rc = SQLITE_ERROR;
110533   }
110534   sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
110535   sqlite3DbFree(db, zErrMsg);
110536   rc = sqlite3ApiExit(db, rc);
110537   sqlite3_mutex_leave(db->mutex);
110538   return rc;
110539 }
110540 #endif
110541
110542 /*
110543 ** Sleep for a little while.  Return the amount of time slept.
110544 */
110545 SQLITE_API int sqlite3_sleep(int ms){
110546   sqlite3_vfs *pVfs;
110547   int rc;
110548   pVfs = sqlite3_vfs_find(0);
110549   if( pVfs==0 ) return 0;
110550
110551   /* This function works in milliseconds, but the underlying OsSleep() 
110552   ** API uses microseconds. Hence the 1000's.
110553   */
110554   rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
110555   return rc;
110556 }
110557
110558 /*
110559 ** Enable or disable the extended result codes.
110560 */
110561 SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
110562   sqlite3_mutex_enter(db->mutex);
110563   db->errMask = onoff ? 0xffffffff : 0xff;
110564   sqlite3_mutex_leave(db->mutex);
110565   return SQLITE_OK;
110566 }
110567
110568 /*
110569 ** Invoke the xFileControl method on a particular database.
110570 */
110571 SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
110572   int rc = SQLITE_ERROR;
110573   int iDb;
110574   sqlite3_mutex_enter(db->mutex);
110575   if( zDbName==0 ){
110576     iDb = 0;
110577   }else{
110578     for(iDb=0; iDb<db->nDb; iDb++){
110579       if( strcmp(db->aDb[iDb].zName, zDbName)==0 ) break;
110580     }
110581   }
110582   if( iDb<db->nDb ){
110583     Btree *pBtree = db->aDb[iDb].pBt;
110584     if( pBtree ){
110585       Pager *pPager;
110586       sqlite3_file *fd;
110587       sqlite3BtreeEnter(pBtree);
110588       pPager = sqlite3BtreePager(pBtree);
110589       assert( pPager!=0 );
110590       fd = sqlite3PagerFile(pPager);
110591       assert( fd!=0 );
110592       if( op==SQLITE_FCNTL_FILE_POINTER ){
110593         *(sqlite3_file**)pArg = fd;
110594         rc = SQLITE_OK;
110595       }else if( fd->pMethods ){
110596         rc = sqlite3OsFileControl(fd, op, pArg);
110597       }else{
110598         rc = SQLITE_NOTFOUND;
110599       }
110600       sqlite3BtreeLeave(pBtree);
110601     }
110602   }
110603   sqlite3_mutex_leave(db->mutex);
110604   return rc;   
110605 }
110606
110607 /*
110608 ** Interface to the testing logic.
110609 */
110610 SQLITE_API int sqlite3_test_control(int op, ...){
110611   int rc = 0;
110612 #ifndef SQLITE_OMIT_BUILTIN_TEST
110613   va_list ap;
110614   va_start(ap, op);
110615   switch( op ){
110616
110617     /*
110618     ** Save the current state of the PRNG.
110619     */
110620     case SQLITE_TESTCTRL_PRNG_SAVE: {
110621       sqlite3PrngSaveState();
110622       break;
110623     }
110624
110625     /*
110626     ** Restore the state of the PRNG to the last state saved using
110627     ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
110628     ** this verb acts like PRNG_RESET.
110629     */
110630     case SQLITE_TESTCTRL_PRNG_RESTORE: {
110631       sqlite3PrngRestoreState();
110632       break;
110633     }
110634
110635     /*
110636     ** Reset the PRNG back to its uninitialized state.  The next call
110637     ** to sqlite3_randomness() will reseed the PRNG using a single call
110638     ** to the xRandomness method of the default VFS.
110639     */
110640     case SQLITE_TESTCTRL_PRNG_RESET: {
110641       sqlite3PrngResetState();
110642       break;
110643     }
110644
110645     /*
110646     **  sqlite3_test_control(BITVEC_TEST, size, program)
110647     **
110648     ** Run a test against a Bitvec object of size.  The program argument
110649     ** is an array of integers that defines the test.  Return -1 on a
110650     ** memory allocation error, 0 on success, or non-zero for an error.
110651     ** See the sqlite3BitvecBuiltinTest() for additional information.
110652     */
110653     case SQLITE_TESTCTRL_BITVEC_TEST: {
110654       int sz = va_arg(ap, int);
110655       int *aProg = va_arg(ap, int*);
110656       rc = sqlite3BitvecBuiltinTest(sz, aProg);
110657       break;
110658     }
110659
110660     /*
110661     **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
110662     **
110663     ** Register hooks to call to indicate which malloc() failures 
110664     ** are benign.
110665     */
110666     case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
110667       typedef void (*void_function)(void);
110668       void_function xBenignBegin;
110669       void_function xBenignEnd;
110670       xBenignBegin = va_arg(ap, void_function);
110671       xBenignEnd = va_arg(ap, void_function);
110672       sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
110673       break;
110674     }
110675
110676     /*
110677     **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
110678     **
110679     ** Set the PENDING byte to the value in the argument, if X>0.
110680     ** Make no changes if X==0.  Return the value of the pending byte
110681     ** as it existing before this routine was called.
110682     **
110683     ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
110684     ** an incompatible database file format.  Changing the PENDING byte
110685     ** while any database connection is open results in undefined and
110686     ** dileterious behavior.
110687     */
110688     case SQLITE_TESTCTRL_PENDING_BYTE: {
110689       rc = PENDING_BYTE;
110690 #ifndef SQLITE_OMIT_WSD
110691       {
110692         unsigned int newVal = va_arg(ap, unsigned int);
110693         if( newVal ) sqlite3PendingByte = newVal;
110694       }
110695 #endif
110696       break;
110697     }
110698
110699     /*
110700     **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
110701     **
110702     ** This action provides a run-time test to see whether or not
110703     ** assert() was enabled at compile-time.  If X is true and assert()
110704     ** is enabled, then the return value is true.  If X is true and
110705     ** assert() is disabled, then the return value is zero.  If X is
110706     ** false and assert() is enabled, then the assertion fires and the
110707     ** process aborts.  If X is false and assert() is disabled, then the
110708     ** return value is zero.
110709     */
110710     case SQLITE_TESTCTRL_ASSERT: {
110711       volatile int x = 0;
110712       assert( (x = va_arg(ap,int))!=0 );
110713       rc = x;
110714       break;
110715     }
110716
110717
110718     /*
110719     **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
110720     **
110721     ** This action provides a run-time test to see how the ALWAYS and
110722     ** NEVER macros were defined at compile-time.
110723     **
110724     ** The return value is ALWAYS(X).  
110725     **
110726     ** The recommended test is X==2.  If the return value is 2, that means
110727     ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
110728     ** default setting.  If the return value is 1, then ALWAYS() is either
110729     ** hard-coded to true or else it asserts if its argument is false.
110730     ** The first behavior (hard-coded to true) is the case if
110731     ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
110732     ** behavior (assert if the argument to ALWAYS() is false) is the case if
110733     ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
110734     **
110735     ** The run-time test procedure might look something like this:
110736     **
110737     **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
110738     **      // ALWAYS() and NEVER() are no-op pass-through macros
110739     **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
110740     **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
110741     **    }else{
110742     **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
110743     **    }
110744     */
110745     case SQLITE_TESTCTRL_ALWAYS: {
110746       int x = va_arg(ap,int);
110747       rc = ALWAYS(x);
110748       break;
110749     }
110750
110751     /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
110752     **
110753     ** Set the nReserve size to N for the main database on the database
110754     ** connection db.
110755     */
110756     case SQLITE_TESTCTRL_RESERVE: {
110757       sqlite3 *db = va_arg(ap, sqlite3*);
110758       int x = va_arg(ap,int);
110759       sqlite3_mutex_enter(db->mutex);
110760       sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
110761       sqlite3_mutex_leave(db->mutex);
110762       break;
110763     }
110764
110765     /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
110766     **
110767     ** Enable or disable various optimizations for testing purposes.  The 
110768     ** argument N is a bitmask of optimizations to be disabled.  For normal
110769     ** operation N should be 0.  The idea is that a test program (like the
110770     ** SQL Logic Test or SLT test module) can run the same SQL multiple times
110771     ** with various optimizations disabled to verify that the same answer
110772     ** is obtained in every case.
110773     */
110774     case SQLITE_TESTCTRL_OPTIMIZATIONS: {
110775       sqlite3 *db = va_arg(ap, sqlite3*);
110776       int x = va_arg(ap,int);
110777       db->flags = (x & SQLITE_OptMask) | (db->flags & ~SQLITE_OptMask);
110778       break;
110779     }
110780
110781 #ifdef SQLITE_N_KEYWORD
110782     /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
110783     **
110784     ** If zWord is a keyword recognized by the parser, then return the
110785     ** number of keywords.  Or if zWord is not a keyword, return 0.
110786     ** 
110787     ** This test feature is only available in the amalgamation since
110788     ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
110789     ** is built using separate source files.
110790     */
110791     case SQLITE_TESTCTRL_ISKEYWORD: {
110792       const char *zWord = va_arg(ap, const char*);
110793       int n = sqlite3Strlen30(zWord);
110794       rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
110795       break;
110796     }
110797 #endif 
110798
110799     /* sqlite3_test_control(SQLITE_TESTCTRL_PGHDRSZ)
110800     **
110801     ** Return the size of a pcache header in bytes.
110802     */
110803     case SQLITE_TESTCTRL_PGHDRSZ: {
110804       rc = sizeof(PgHdr);
110805       break;
110806     }
110807
110808     /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
110809     **
110810     ** Pass pFree into sqlite3ScratchFree(). 
110811     ** If sz>0 then allocate a scratch buffer into pNew.  
110812     */
110813     case SQLITE_TESTCTRL_SCRATCHMALLOC: {
110814       void *pFree, **ppNew;
110815       int sz;
110816       sz = va_arg(ap, int);
110817       ppNew = va_arg(ap, void**);
110818       pFree = va_arg(ap, void*);
110819       if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
110820       sqlite3ScratchFree(pFree);
110821       break;
110822     }
110823
110824     /*   sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
110825     **
110826     ** If parameter onoff is non-zero, configure the wrappers so that all
110827     ** subsequent calls to localtime() and variants fail. If onoff is zero,
110828     ** undo this setting.
110829     */
110830     case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
110831       sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
110832       break;
110833     }
110834
110835   }
110836   va_end(ap);
110837 #endif /* SQLITE_OMIT_BUILTIN_TEST */
110838   return rc;
110839 }
110840
110841 /*
110842 ** This is a utility routine, useful to VFS implementations, that checks
110843 ** to see if a database file was a URI that contained a specific query 
110844 ** parameter, and if so obtains the value of the query parameter.
110845 **
110846 ** The zFilename argument is the filename pointer passed into the xOpen()
110847 ** method of a VFS implementation.  The zParam argument is the name of the
110848 ** query parameter we seek.  This routine returns the value of the zParam
110849 ** parameter if it exists.  If the parameter does not exist, this routine
110850 ** returns a NULL pointer.
110851 */
110852 SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
110853   zFilename += sqlite3Strlen30(zFilename) + 1;
110854   while( zFilename[0] ){
110855     int x = strcmp(zFilename, zParam);
110856     zFilename += sqlite3Strlen30(zFilename) + 1;
110857     if( x==0 ) return zFilename;
110858     zFilename += sqlite3Strlen30(zFilename) + 1;
110859   }
110860   return 0;
110861 }
110862
110863 /************** End of main.c ************************************************/
110864 /************** Begin file notify.c ******************************************/
110865 /*
110866 ** 2009 March 3
110867 **
110868 ** The author disclaims copyright to this source code.  In place of
110869 ** a legal notice, here is a blessing:
110870 **
110871 **    May you do good and not evil.
110872 **    May you find forgiveness for yourself and forgive others.
110873 **    May you share freely, never taking more than you give.
110874 **
110875 *************************************************************************
110876 **
110877 ** This file contains the implementation of the sqlite3_unlock_notify()
110878 ** API method and its associated functionality.
110879 */
110880
110881 /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
110882 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
110883
110884 /*
110885 ** Public interfaces:
110886 **
110887 **   sqlite3ConnectionBlocked()
110888 **   sqlite3ConnectionUnlocked()
110889 **   sqlite3ConnectionClosed()
110890 **   sqlite3_unlock_notify()
110891 */
110892
110893 #define assertMutexHeld() \
110894   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
110895
110896 /*
110897 ** Head of a linked list of all sqlite3 objects created by this process
110898 ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
110899 ** is not NULL. This variable may only accessed while the STATIC_MASTER
110900 ** mutex is held.
110901 */
110902 static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
110903
110904 #ifndef NDEBUG
110905 /*
110906 ** This function is a complex assert() that verifies the following 
110907 ** properties of the blocked connections list:
110908 **
110909 **   1) Each entry in the list has a non-NULL value for either 
110910 **      pUnlockConnection or pBlockingConnection, or both.
110911 **
110912 **   2) All entries in the list that share a common value for 
110913 **      xUnlockNotify are grouped together.
110914 **
110915 **   3) If the argument db is not NULL, then none of the entries in the
110916 **      blocked connections list have pUnlockConnection or pBlockingConnection
110917 **      set to db. This is used when closing connection db.
110918 */
110919 static void checkListProperties(sqlite3 *db){
110920   sqlite3 *p;
110921   for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
110922     int seen = 0;
110923     sqlite3 *p2;
110924
110925     /* Verify property (1) */
110926     assert( p->pUnlockConnection || p->pBlockingConnection );
110927
110928     /* Verify property (2) */
110929     for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
110930       if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
110931       assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
110932       assert( db==0 || p->pUnlockConnection!=db );
110933       assert( db==0 || p->pBlockingConnection!=db );
110934     }
110935   }
110936 }
110937 #else
110938 # define checkListProperties(x)
110939 #endif
110940
110941 /*
110942 ** Remove connection db from the blocked connections list. If connection
110943 ** db is not currently a part of the list, this function is a no-op.
110944 */
110945 static void removeFromBlockedList(sqlite3 *db){
110946   sqlite3 **pp;
110947   assertMutexHeld();
110948   for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
110949     if( *pp==db ){
110950       *pp = (*pp)->pNextBlocked;
110951       break;
110952     }
110953   }
110954 }
110955
110956 /*
110957 ** Add connection db to the blocked connections list. It is assumed
110958 ** that it is not already a part of the list.
110959 */
110960 static void addToBlockedList(sqlite3 *db){
110961   sqlite3 **pp;
110962   assertMutexHeld();
110963   for(
110964     pp=&sqlite3BlockedList; 
110965     *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify; 
110966     pp=&(*pp)->pNextBlocked
110967   );
110968   db->pNextBlocked = *pp;
110969   *pp = db;
110970 }
110971
110972 /*
110973 ** Obtain the STATIC_MASTER mutex.
110974 */
110975 static void enterMutex(void){
110976   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
110977   checkListProperties(0);
110978 }
110979
110980 /*
110981 ** Release the STATIC_MASTER mutex.
110982 */
110983 static void leaveMutex(void){
110984   assertMutexHeld();
110985   checkListProperties(0);
110986   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
110987 }
110988
110989 /*
110990 ** Register an unlock-notify callback.
110991 **
110992 ** This is called after connection "db" has attempted some operation
110993 ** but has received an SQLITE_LOCKED error because another connection
110994 ** (call it pOther) in the same process was busy using the same shared
110995 ** cache.  pOther is found by looking at db->pBlockingConnection.
110996 **
110997 ** If there is no blocking connection, the callback is invoked immediately,
110998 ** before this routine returns.
110999 **
111000 ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
111001 ** a deadlock.
111002 **
111003 ** Otherwise, make arrangements to invoke xNotify when pOther drops
111004 ** its locks.
111005 **
111006 ** Each call to this routine overrides any prior callbacks registered
111007 ** on the same "db".  If xNotify==0 then any prior callbacks are immediately
111008 ** cancelled.
111009 */
111010 SQLITE_API int sqlite3_unlock_notify(
111011   sqlite3 *db,
111012   void (*xNotify)(void **, int),
111013   void *pArg
111014 ){
111015   int rc = SQLITE_OK;
111016
111017   sqlite3_mutex_enter(db->mutex);
111018   enterMutex();
111019
111020   if( xNotify==0 ){
111021     removeFromBlockedList(db);
111022     db->pBlockingConnection = 0;
111023     db->pUnlockConnection = 0;
111024     db->xUnlockNotify = 0;
111025     db->pUnlockArg = 0;
111026   }else if( 0==db->pBlockingConnection ){
111027     /* The blocking transaction has been concluded. Or there never was a 
111028     ** blocking transaction. In either case, invoke the notify callback
111029     ** immediately. 
111030     */
111031     xNotify(&pArg, 1);
111032   }else{
111033     sqlite3 *p;
111034
111035     for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
111036     if( p ){
111037       rc = SQLITE_LOCKED;              /* Deadlock detected. */
111038     }else{
111039       db->pUnlockConnection = db->pBlockingConnection;
111040       db->xUnlockNotify = xNotify;
111041       db->pUnlockArg = pArg;
111042       removeFromBlockedList(db);
111043       addToBlockedList(db);
111044     }
111045   }
111046
111047   leaveMutex();
111048   assert( !db->mallocFailed );
111049   sqlite3Error(db, rc, (rc?"database is deadlocked":0));
111050   sqlite3_mutex_leave(db->mutex);
111051   return rc;
111052 }
111053
111054 /*
111055 ** This function is called while stepping or preparing a statement 
111056 ** associated with connection db. The operation will return SQLITE_LOCKED
111057 ** to the user because it requires a lock that will not be available
111058 ** until connection pBlocker concludes its current transaction.
111059 */
111060 SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
111061   enterMutex();
111062   if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
111063     addToBlockedList(db);
111064   }
111065   db->pBlockingConnection = pBlocker;
111066   leaveMutex();
111067 }
111068
111069 /*
111070 ** This function is called when
111071 ** the transaction opened by database db has just finished. Locks held 
111072 ** by database connection db have been released.
111073 **
111074 ** This function loops through each entry in the blocked connections
111075 ** list and does the following:
111076 **
111077 **   1) If the sqlite3.pBlockingConnection member of a list entry is
111078 **      set to db, then set pBlockingConnection=0.
111079 **
111080 **   2) If the sqlite3.pUnlockConnection member of a list entry is
111081 **      set to db, then invoke the configured unlock-notify callback and
111082 **      set pUnlockConnection=0.
111083 **
111084 **   3) If the two steps above mean that pBlockingConnection==0 and
111085 **      pUnlockConnection==0, remove the entry from the blocked connections
111086 **      list.
111087 */
111088 SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
111089   void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
111090   int nArg = 0;                            /* Number of entries in aArg[] */
111091   sqlite3 **pp;                            /* Iterator variable */
111092   void **aArg;               /* Arguments to the unlock callback */
111093   void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
111094   void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
111095
111096   aArg = aStatic;
111097   enterMutex();         /* Enter STATIC_MASTER mutex */
111098
111099   /* This loop runs once for each entry in the blocked-connections list. */
111100   for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
111101     sqlite3 *p = *pp;
111102
111103     /* Step 1. */
111104     if( p->pBlockingConnection==db ){
111105       p->pBlockingConnection = 0;
111106     }
111107
111108     /* Step 2. */
111109     if( p->pUnlockConnection==db ){
111110       assert( p->xUnlockNotify );
111111       if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
111112         xUnlockNotify(aArg, nArg);
111113         nArg = 0;
111114       }
111115
111116       sqlite3BeginBenignMalloc();
111117       assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
111118       assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
111119       if( (!aDyn && nArg==(int)ArraySize(aStatic))
111120        || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
111121       ){
111122         /* The aArg[] array needs to grow. */
111123         void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
111124         if( pNew ){
111125           memcpy(pNew, aArg, nArg*sizeof(void *));
111126           sqlite3_free(aDyn);
111127           aDyn = aArg = pNew;
111128         }else{
111129           /* This occurs when the array of context pointers that need to
111130           ** be passed to the unlock-notify callback is larger than the
111131           ** aStatic[] array allocated on the stack and the attempt to 
111132           ** allocate a larger array from the heap has failed.
111133           **
111134           ** This is a difficult situation to handle. Returning an error
111135           ** code to the caller is insufficient, as even if an error code
111136           ** is returned the transaction on connection db will still be
111137           ** closed and the unlock-notify callbacks on blocked connections
111138           ** will go unissued. This might cause the application to wait
111139           ** indefinitely for an unlock-notify callback that will never 
111140           ** arrive.
111141           **
111142           ** Instead, invoke the unlock-notify callback with the context
111143           ** array already accumulated. We can then clear the array and
111144           ** begin accumulating any further context pointers without 
111145           ** requiring any dynamic allocation. This is sub-optimal because
111146           ** it means that instead of one callback with a large array of
111147           ** context pointers the application will receive two or more
111148           ** callbacks with smaller arrays of context pointers, which will
111149           ** reduce the applications ability to prioritize multiple 
111150           ** connections. But it is the best that can be done under the
111151           ** circumstances.
111152           */
111153           xUnlockNotify(aArg, nArg);
111154           nArg = 0;
111155         }
111156       }
111157       sqlite3EndBenignMalloc();
111158
111159       aArg[nArg++] = p->pUnlockArg;
111160       xUnlockNotify = p->xUnlockNotify;
111161       p->pUnlockConnection = 0;
111162       p->xUnlockNotify = 0;
111163       p->pUnlockArg = 0;
111164     }
111165
111166     /* Step 3. */
111167     if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
111168       /* Remove connection p from the blocked connections list. */
111169       *pp = p->pNextBlocked;
111170       p->pNextBlocked = 0;
111171     }else{
111172       pp = &p->pNextBlocked;
111173     }
111174   }
111175
111176   if( nArg!=0 ){
111177     xUnlockNotify(aArg, nArg);
111178   }
111179   sqlite3_free(aDyn);
111180   leaveMutex();         /* Leave STATIC_MASTER mutex */
111181 }
111182
111183 /*
111184 ** This is called when the database connection passed as an argument is 
111185 ** being closed. The connection is removed from the blocked list.
111186 */
111187 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
111188   sqlite3ConnectionUnlocked(db);
111189   enterMutex();
111190   removeFromBlockedList(db);
111191   checkListProperties(db);
111192   leaveMutex();
111193 }
111194 #endif
111195
111196 /************** End of notify.c **********************************************/
111197 /************** Begin file fts3.c ********************************************/
111198 /*
111199 ** 2006 Oct 10
111200 **
111201 ** The author disclaims copyright to this source code.  In place of
111202 ** a legal notice, here is a blessing:
111203 **
111204 **    May you do good and not evil.
111205 **    May you find forgiveness for yourself and forgive others.
111206 **    May you share freely, never taking more than you give.
111207 **
111208 ******************************************************************************
111209 **
111210 ** This is an SQLite module implementing full-text search.
111211 */
111212
111213 /*
111214 ** The code in this file is only compiled if:
111215 **
111216 **     * The FTS3 module is being built as an extension
111217 **       (in which case SQLITE_CORE is not defined), or
111218 **
111219 **     * The FTS3 module is being built into the core of
111220 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
111221 */
111222
111223 /* The full-text index is stored in a series of b+tree (-like)
111224 ** structures called segments which map terms to doclists.  The
111225 ** structures are like b+trees in layout, but are constructed from the
111226 ** bottom up in optimal fashion and are not updatable.  Since trees
111227 ** are built from the bottom up, things will be described from the
111228 ** bottom up.
111229 **
111230 **
111231 **** Varints ****
111232 ** The basic unit of encoding is a variable-length integer called a
111233 ** varint.  We encode variable-length integers in little-endian order
111234 ** using seven bits * per byte as follows:
111235 **
111236 ** KEY:
111237 **         A = 0xxxxxxx    7 bits of data and one flag bit
111238 **         B = 1xxxxxxx    7 bits of data and one flag bit
111239 **
111240 **  7 bits - A
111241 ** 14 bits - BA
111242 ** 21 bits - BBA
111243 ** and so on.
111244 **
111245 ** This is similar in concept to how sqlite encodes "varints" but
111246 ** the encoding is not the same.  SQLite varints are big-endian
111247 ** are are limited to 9 bytes in length whereas FTS3 varints are
111248 ** little-endian and can be up to 10 bytes in length (in theory).
111249 **
111250 ** Example encodings:
111251 **
111252 **     1:    0x01
111253 **   127:    0x7f
111254 **   128:    0x81 0x00
111255 **
111256 **
111257 **** Document lists ****
111258 ** A doclist (document list) holds a docid-sorted list of hits for a
111259 ** given term.  Doclists hold docids and associated token positions.
111260 ** A docid is the unique integer identifier for a single document.
111261 ** A position is the index of a word within the document.  The first 
111262 ** word of the document has a position of 0.
111263 **
111264 ** FTS3 used to optionally store character offsets using a compile-time
111265 ** option.  But that functionality is no longer supported.
111266 **
111267 ** A doclist is stored like this:
111268 **
111269 ** array {
111270 **   varint docid;
111271 **   array {                (position list for column 0)
111272 **     varint position;     (2 more than the delta from previous position)
111273 **   }
111274 **   array {
111275 **     varint POS_COLUMN;   (marks start of position list for new column)
111276 **     varint column;       (index of new column)
111277 **     array {
111278 **       varint position;   (2 more than the delta from previous position)
111279 **     }
111280 **   }
111281 **   varint POS_END;        (marks end of positions for this document.
111282 ** }
111283 **
111284 ** Here, array { X } means zero or more occurrences of X, adjacent in
111285 ** memory.  A "position" is an index of a token in the token stream
111286 ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur 
111287 ** in the same logical place as the position element, and act as sentinals
111288 ** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.
111289 ** The positions numbers are not stored literally but rather as two more
111290 ** than the difference from the prior position, or the just the position plus
111291 ** 2 for the first position.  Example:
111292 **
111293 **   label:       A B C D E  F  G H   I  J K
111294 **   value:     123 5 9 1 1 14 35 0 234 72 0
111295 **
111296 ** The 123 value is the first docid.  For column zero in this document
111297 ** there are two matches at positions 3 and 10 (5-2 and 9-2+3).  The 1
111298 ** at D signals the start of a new column; the 1 at E indicates that the
111299 ** new column is column number 1.  There are two positions at 12 and 45
111300 ** (14-2 and 35-2+12).  The 0 at H indicate the end-of-document.  The
111301 ** 234 at I is the next docid.  It has one position 72 (72-2) and then
111302 ** terminates with the 0 at K.
111303 **
111304 ** A "position-list" is the list of positions for multiple columns for
111305 ** a single docid.  A "column-list" is the set of positions for a single
111306 ** column.  Hence, a position-list consists of one or more column-lists,
111307 ** a document record consists of a docid followed by a position-list and
111308 ** a doclist consists of one or more document records.
111309 **
111310 ** A bare doclist omits the position information, becoming an 
111311 ** array of varint-encoded docids.
111312 **
111313 **** Segment leaf nodes ****
111314 ** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
111315 ** nodes are written using LeafWriter, and read using LeafReader (to
111316 ** iterate through a single leaf node's data) and LeavesReader (to
111317 ** iterate through a segment's entire leaf layer).  Leaf nodes have
111318 ** the format:
111319 **
111320 ** varint iHeight;             (height from leaf level, always 0)
111321 ** varint nTerm;               (length of first term)
111322 ** char pTerm[nTerm];          (content of first term)
111323 ** varint nDoclist;            (length of term's associated doclist)
111324 ** char pDoclist[nDoclist];    (content of doclist)
111325 ** array {
111326 **                             (further terms are delta-encoded)
111327 **   varint nPrefix;           (length of prefix shared with previous term)
111328 **   varint nSuffix;           (length of unshared suffix)
111329 **   char pTermSuffix[nSuffix];(unshared suffix of next term)
111330 **   varint nDoclist;          (length of term's associated doclist)
111331 **   char pDoclist[nDoclist];  (content of doclist)
111332 ** }
111333 **
111334 ** Here, array { X } means zero or more occurrences of X, adjacent in
111335 ** memory.
111336 **
111337 ** Leaf nodes are broken into blocks which are stored contiguously in
111338 ** the %_segments table in sorted order.  This means that when the end
111339 ** of a node is reached, the next term is in the node with the next
111340 ** greater node id.
111341 **
111342 ** New data is spilled to a new leaf node when the current node
111343 ** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
111344 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
111345 ** node (a leaf node with a single term and doclist).  The goal of
111346 ** these settings is to pack together groups of small doclists while
111347 ** making it efficient to directly access large doclists.  The
111348 ** assumption is that large doclists represent terms which are more
111349 ** likely to be query targets.
111350 **
111351 ** TODO(shess) It may be useful for blocking decisions to be more
111352 ** dynamic.  For instance, it may make more sense to have a 2.5k leaf
111353 ** node rather than splitting into 2k and .5k nodes.  My intuition is
111354 ** that this might extend through 2x or 4x the pagesize.
111355 **
111356 **
111357 **** Segment interior nodes ****
111358 ** Segment interior nodes store blockids for subtree nodes and terms
111359 ** to describe what data is stored by the each subtree.  Interior
111360 ** nodes are written using InteriorWriter, and read using
111361 ** InteriorReader.  InteriorWriters are created as needed when
111362 ** SegmentWriter creates new leaf nodes, or when an interior node
111363 ** itself grows too big and must be split.  The format of interior
111364 ** nodes:
111365 **
111366 ** varint iHeight;           (height from leaf level, always >0)
111367 ** varint iBlockid;          (block id of node's leftmost subtree)
111368 ** optional {
111369 **   varint nTerm;           (length of first term)
111370 **   char pTerm[nTerm];      (content of first term)
111371 **   array {
111372 **                                (further terms are delta-encoded)
111373 **     varint nPrefix;            (length of shared prefix with previous term)
111374 **     varint nSuffix;            (length of unshared suffix)
111375 **     char pTermSuffix[nSuffix]; (unshared suffix of next term)
111376 **   }
111377 ** }
111378 **
111379 ** Here, optional { X } means an optional element, while array { X }
111380 ** means zero or more occurrences of X, adjacent in memory.
111381 **
111382 ** An interior node encodes n terms separating n+1 subtrees.  The
111383 ** subtree blocks are contiguous, so only the first subtree's blockid
111384 ** is encoded.  The subtree at iBlockid will contain all terms less
111385 ** than the first term encoded (or all terms if no term is encoded).
111386 ** Otherwise, for terms greater than or equal to pTerm[i] but less
111387 ** than pTerm[i+1], the subtree for that term will be rooted at
111388 ** iBlockid+i.  Interior nodes only store enough term data to
111389 ** distinguish adjacent children (if the rightmost term of the left
111390 ** child is "something", and the leftmost term of the right child is
111391 ** "wicked", only "w" is stored).
111392 **
111393 ** New data is spilled to a new interior node at the same height when
111394 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
111395 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
111396 ** interior nodes and making the tree too skinny.  The interior nodes
111397 ** at a given height are naturally tracked by interior nodes at
111398 ** height+1, and so on.
111399 **
111400 **
111401 **** Segment directory ****
111402 ** The segment directory in table %_segdir stores meta-information for
111403 ** merging and deleting segments, and also the root node of the
111404 ** segment's tree.
111405 **
111406 ** The root node is the top node of the segment's tree after encoding
111407 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
111408 ** This could be either a leaf node or an interior node.  If the top
111409 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
111410 ** and a new root interior node is generated (which should always fit
111411 ** within ROOT_MAX because it only needs space for 2 varints, the
111412 ** height and the blockid of the previous root).
111413 **
111414 ** The meta-information in the segment directory is:
111415 **   level               - segment level (see below)
111416 **   idx                 - index within level
111417 **                       - (level,idx uniquely identify a segment)
111418 **   start_block         - first leaf node
111419 **   leaves_end_block    - last leaf node
111420 **   end_block           - last block (including interior nodes)
111421 **   root                - contents of root node
111422 **
111423 ** If the root node is a leaf node, then start_block,
111424 ** leaves_end_block, and end_block are all 0.
111425 **
111426 **
111427 **** Segment merging ****
111428 ** To amortize update costs, segments are grouped into levels and
111429 ** merged in batches.  Each increase in level represents exponentially
111430 ** more documents.
111431 **
111432 ** New documents (actually, document updates) are tokenized and
111433 ** written individually (using LeafWriter) to a level 0 segment, with
111434 ** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
111435 ** level 0 segments are merged into a single level 1 segment.  Level 1
111436 ** is populated like level 0, and eventually MERGE_COUNT level 1
111437 ** segments are merged to a single level 2 segment (representing
111438 ** MERGE_COUNT^2 updates), and so on.
111439 **
111440 ** A segment merge traverses all segments at a given level in
111441 ** parallel, performing a straightforward sorted merge.  Since segment
111442 ** leaf nodes are written in to the %_segments table in order, this
111443 ** merge traverses the underlying sqlite disk structures efficiently.
111444 ** After the merge, all segment blocks from the merged level are
111445 ** deleted.
111446 **
111447 ** MERGE_COUNT controls how often we merge segments.  16 seems to be
111448 ** somewhat of a sweet spot for insertion performance.  32 and 64 show
111449 ** very similar performance numbers to 16 on insertion, though they're
111450 ** a tiny bit slower (perhaps due to more overhead in merge-time
111451 ** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
111452 ** 16, 2 about 66% slower than 16.
111453 **
111454 ** At query time, high MERGE_COUNT increases the number of segments
111455 ** which need to be scanned and merged.  For instance, with 100k docs
111456 ** inserted:
111457 **
111458 **    MERGE_COUNT   segments
111459 **       16           25
111460 **        8           12
111461 **        4           10
111462 **        2            6
111463 **
111464 ** This appears to have only a moderate impact on queries for very
111465 ** frequent terms (which are somewhat dominated by segment merge
111466 ** costs), and infrequent and non-existent terms still seem to be fast
111467 ** even with many segments.
111468 **
111469 ** TODO(shess) That said, it would be nice to have a better query-side
111470 ** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
111471 ** optimizations to things like doclist merging will swing the sweet
111472 ** spot around.
111473 **
111474 **
111475 **
111476 **** Handling of deletions and updates ****
111477 ** Since we're using a segmented structure, with no docid-oriented
111478 ** index into the term index, we clearly cannot simply update the term
111479 ** index when a document is deleted or updated.  For deletions, we
111480 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
111481 ** we simply write the new doclist.  Segment merges overwrite older
111482 ** data for a particular docid with newer data, so deletes or updates
111483 ** will eventually overtake the earlier data and knock it out.  The
111484 ** query logic likewise merges doclists so that newer data knocks out
111485 ** older data.
111486 **
111487 ** TODO(shess) Provide a VACUUM type operation to clear out all
111488 ** deletions and duplications.  This would basically be a forced merge
111489 ** into a single segment.
111490 */
111491
111492 /************** Include fts3Int.h in the middle of fts3.c ********************/
111493 /************** Begin file fts3Int.h *****************************************/
111494 /*
111495 ** 2009 Nov 12
111496 **
111497 ** The author disclaims copyright to this source code.  In place of
111498 ** a legal notice, here is a blessing:
111499 **
111500 **    May you do good and not evil.
111501 **    May you find forgiveness for yourself and forgive others.
111502 **    May you share freely, never taking more than you give.
111503 **
111504 ******************************************************************************
111505 **
111506 */
111507 #ifndef _FTSINT_H
111508 #define _FTSINT_H
111509
111510 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
111511 # define NDEBUG 1
111512 #endif
111513
111514 /*
111515 ** FTS4 is really an extension for FTS3.  It is enabled using the
111516 ** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
111517 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
111518 */
111519 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
111520 # define SQLITE_ENABLE_FTS3
111521 #endif
111522
111523 #ifdef SQLITE_ENABLE_FTS3
111524 /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
111525 /************** Begin file fts3_tokenizer.h **********************************/
111526 /*
111527 ** 2006 July 10
111528 **
111529 ** The author disclaims copyright to this source code.
111530 **
111531 *************************************************************************
111532 ** Defines the interface to tokenizers used by fulltext-search.  There
111533 ** are three basic components:
111534 **
111535 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
111536 ** interface functions.  This is essentially the class structure for
111537 ** tokenizers.
111538 **
111539 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
111540 ** including customization information defined at creation time.
111541 **
111542 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
111543 ** tokens from a particular input.
111544 */
111545 #ifndef _FTS3_TOKENIZER_H_
111546 #define _FTS3_TOKENIZER_H_
111547
111548 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
111549 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
111550 ** we will need a way to register the API consistently.
111551 */
111552
111553 /*
111554 ** Structures used by the tokenizer interface. When a new tokenizer
111555 ** implementation is registered, the caller provides a pointer to
111556 ** an sqlite3_tokenizer_module containing pointers to the callback
111557 ** functions that make up an implementation.
111558 **
111559 ** When an fts3 table is created, it passes any arguments passed to
111560 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
111561 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
111562 ** implementation. The xCreate() function in turn returns an 
111563 ** sqlite3_tokenizer structure representing the specific tokenizer to
111564 ** be used for the fts3 table (customized by the tokenizer clause arguments).
111565 **
111566 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
111567 ** method is called. It returns an sqlite3_tokenizer_cursor object
111568 ** that may be used to tokenize a specific input buffer based on
111569 ** the tokenization rules supplied by a specific sqlite3_tokenizer
111570 ** object.
111571 */
111572 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
111573 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
111574 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
111575
111576 struct sqlite3_tokenizer_module {
111577
111578   /*
111579   ** Structure version. Should always be set to 0.
111580   */
111581   int iVersion;
111582
111583   /*
111584   ** Create a new tokenizer. The values in the argv[] array are the
111585   ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
111586   ** TABLE statement that created the fts3 table. For example, if
111587   ** the following SQL is executed:
111588   **
111589   **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
111590   **
111591   ** then argc is set to 2, and the argv[] array contains pointers
111592   ** to the strings "arg1" and "arg2".
111593   **
111594   ** This method should return either SQLITE_OK (0), or an SQLite error 
111595   ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
111596   ** to point at the newly created tokenizer structure. The generic
111597   ** sqlite3_tokenizer.pModule variable should not be initialised by
111598   ** this callback. The caller will do so.
111599   */
111600   int (*xCreate)(
111601     int argc,                           /* Size of argv array */
111602     const char *const*argv,             /* Tokenizer argument strings */
111603     sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
111604   );
111605
111606   /*
111607   ** Destroy an existing tokenizer. The fts3 module calls this method
111608   ** exactly once for each successful call to xCreate().
111609   */
111610   int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
111611
111612   /*
111613   ** Create a tokenizer cursor to tokenize an input buffer. The caller
111614   ** is responsible for ensuring that the input buffer remains valid
111615   ** until the cursor is closed (using the xClose() method). 
111616   */
111617   int (*xOpen)(
111618     sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
111619     const char *pInput, int nBytes,      /* Input buffer */
111620     sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
111621   );
111622
111623   /*
111624   ** Destroy an existing tokenizer cursor. The fts3 module calls this 
111625   ** method exactly once for each successful call to xOpen().
111626   */
111627   int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
111628
111629   /*
111630   ** Retrieve the next token from the tokenizer cursor pCursor. This
111631   ** method should either return SQLITE_OK and set the values of the
111632   ** "OUT" variables identified below, or SQLITE_DONE to indicate that
111633   ** the end of the buffer has been reached, or an SQLite error code.
111634   **
111635   ** *ppToken should be set to point at a buffer containing the 
111636   ** normalized version of the token (i.e. after any case-folding and/or
111637   ** stemming has been performed). *pnBytes should be set to the length
111638   ** of this buffer in bytes. The input text that generated the token is
111639   ** identified by the byte offsets returned in *piStartOffset and
111640   ** *piEndOffset. *piStartOffset should be set to the index of the first
111641   ** byte of the token in the input buffer. *piEndOffset should be set
111642   ** to the index of the first byte just past the end of the token in
111643   ** the input buffer.
111644   **
111645   ** The buffer *ppToken is set to point at is managed by the tokenizer
111646   ** implementation. It is only required to be valid until the next call
111647   ** to xNext() or xClose(). 
111648   */
111649   /* TODO(shess) current implementation requires pInput to be
111650   ** nul-terminated.  This should either be fixed, or pInput/nBytes
111651   ** should be converted to zInput.
111652   */
111653   int (*xNext)(
111654     sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
111655     const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
111656     int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
111657     int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
111658     int *piPosition      /* OUT: Number of tokens returned before this one */
111659   );
111660 };
111661
111662 struct sqlite3_tokenizer {
111663   const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
111664   /* Tokenizer implementations will typically add additional fields */
111665 };
111666
111667 struct sqlite3_tokenizer_cursor {
111668   sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
111669   /* Tokenizer implementations will typically add additional fields */
111670 };
111671
111672 int fts3_global_term_cnt(int iTerm, int iCol);
111673 int fts3_term_cnt(int iTerm, int iCol);
111674
111675
111676 #endif /* _FTS3_TOKENIZER_H_ */
111677
111678 /************** End of fts3_tokenizer.h **************************************/
111679 /************** Continuing where we left off in fts3Int.h ********************/
111680 /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
111681 /************** Begin file fts3_hash.h ***************************************/
111682 /*
111683 ** 2001 September 22
111684 **
111685 ** The author disclaims copyright to this source code.  In place of
111686 ** a legal notice, here is a blessing:
111687 **
111688 **    May you do good and not evil.
111689 **    May you find forgiveness for yourself and forgive others.
111690 **    May you share freely, never taking more than you give.
111691 **
111692 *************************************************************************
111693 ** This is the header file for the generic hash-table implemenation
111694 ** used in SQLite.  We've modified it slightly to serve as a standalone
111695 ** hash table implementation for the full-text indexing module.
111696 **
111697 */
111698 #ifndef _FTS3_HASH_H_
111699 #define _FTS3_HASH_H_
111700
111701 /* Forward declarations of structures. */
111702 typedef struct Fts3Hash Fts3Hash;
111703 typedef struct Fts3HashElem Fts3HashElem;
111704
111705 /* A complete hash table is an instance of the following structure.
111706 ** The internals of this structure are intended to be opaque -- client
111707 ** code should not attempt to access or modify the fields of this structure
111708 ** directly.  Change this structure only by using the routines below.
111709 ** However, many of the "procedures" and "functions" for modifying and
111710 ** accessing this structure are really macros, so we can't really make
111711 ** this structure opaque.
111712 */
111713 struct Fts3Hash {
111714   char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
111715   char copyKey;           /* True if copy of key made on insert */
111716   int count;              /* Number of entries in this table */
111717   Fts3HashElem *first;    /* The first element of the array */
111718   int htsize;             /* Number of buckets in the hash table */
111719   struct _fts3ht {        /* the hash table */
111720     int count;               /* Number of entries with this hash */
111721     Fts3HashElem *chain;     /* Pointer to first entry with this hash */
111722   } *ht;
111723 };
111724
111725 /* Each element in the hash table is an instance of the following 
111726 ** structure.  All elements are stored on a single doubly-linked list.
111727 **
111728 ** Again, this structure is intended to be opaque, but it can't really
111729 ** be opaque because it is used by macros.
111730 */
111731 struct Fts3HashElem {
111732   Fts3HashElem *next, *prev; /* Next and previous elements in the table */
111733   void *data;                /* Data associated with this element */
111734   void *pKey; int nKey;      /* Key associated with this element */
111735 };
111736
111737 /*
111738 ** There are 2 different modes of operation for a hash table:
111739 **
111740 **   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
111741 **                           (including the null-terminator, if any).  Case
111742 **                           is respected in comparisons.
111743 **
111744 **   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long. 
111745 **                           memcmp() is used to compare keys.
111746 **
111747 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.  
111748 */
111749 #define FTS3_HASH_STRING    1
111750 #define FTS3_HASH_BINARY    2
111751
111752 /*
111753 ** Access routines.  To delete, insert a NULL pointer.
111754 */
111755 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
111756 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
111757 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
111758 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
111759 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
111760
111761 /*
111762 ** Shorthand for the functions above
111763 */
111764 #define fts3HashInit     sqlite3Fts3HashInit
111765 #define fts3HashInsert   sqlite3Fts3HashInsert
111766 #define fts3HashFind     sqlite3Fts3HashFind
111767 #define fts3HashClear    sqlite3Fts3HashClear
111768 #define fts3HashFindElem sqlite3Fts3HashFindElem
111769
111770 /*
111771 ** Macros for looping over all elements of a hash table.  The idiom is
111772 ** like this:
111773 **
111774 **   Fts3Hash h;
111775 **   Fts3HashElem *p;
111776 **   ...
111777 **   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
111778 **     SomeStructure *pData = fts3HashData(p);
111779 **     // do something with pData
111780 **   }
111781 */
111782 #define fts3HashFirst(H)  ((H)->first)
111783 #define fts3HashNext(E)   ((E)->next)
111784 #define fts3HashData(E)   ((E)->data)
111785 #define fts3HashKey(E)    ((E)->pKey)
111786 #define fts3HashKeysize(E) ((E)->nKey)
111787
111788 /*
111789 ** Number of entries in a hash table
111790 */
111791 #define fts3HashCount(H)  ((H)->count)
111792
111793 #endif /* _FTS3_HASH_H_ */
111794
111795 /************** End of fts3_hash.h *******************************************/
111796 /************** Continuing where we left off in fts3Int.h ********************/
111797
111798 /*
111799 ** This constant controls how often segments are merged. Once there are
111800 ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
111801 ** segment of level N+1.
111802 */
111803 #define FTS3_MERGE_COUNT 16
111804
111805 /*
111806 ** This is the maximum amount of data (in bytes) to store in the 
111807 ** Fts3Table.pendingTerms hash table. Normally, the hash table is
111808 ** populated as documents are inserted/updated/deleted in a transaction
111809 ** and used to create a new segment when the transaction is committed.
111810 ** However if this limit is reached midway through a transaction, a new 
111811 ** segment is created and the hash table cleared immediately.
111812 */
111813 #define FTS3_MAX_PENDING_DATA (1*1024*1024)
111814
111815 /*
111816 ** Macro to return the number of elements in an array. SQLite has a
111817 ** similar macro called ArraySize(). Use a different name to avoid
111818 ** a collision when building an amalgamation with built-in FTS3.
111819 */
111820 #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
111821
111822
111823 #ifndef MIN
111824 # define MIN(x,y) ((x)<(y)?(x):(y))
111825 #endif
111826
111827 /*
111828 ** Maximum length of a varint encoded integer. The varint format is different
111829 ** from that used by SQLite, so the maximum length is 10, not 9.
111830 */
111831 #define FTS3_VARINT_MAX 10
111832
111833 /*
111834 ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
111835 ** in the document set and zero or more prefix indexes. All indexes are stored
111836 ** as one or more b+-trees in the %_segments and %_segdir tables. 
111837 **
111838 ** It is possible to determine which index a b+-tree belongs to based on the
111839 ** value stored in the "%_segdir.level" column. Given this value L, the index
111840 ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
111841 ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
111842 ** between 1024 and 2047 to index 1, and so on.
111843 **
111844 ** It is considered impossible for an index to use more than 1024 levels. In 
111845 ** theory though this may happen, but only after at least 
111846 ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
111847 */
111848 #define FTS3_SEGDIR_MAXLEVEL      1024
111849 #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
111850
111851 /*
111852 ** The testcase() macro is only used by the amalgamation.  If undefined,
111853 ** make it a no-op.
111854 */
111855 #ifndef testcase
111856 # define testcase(X)
111857 #endif
111858
111859 /*
111860 ** Terminator values for position-lists and column-lists.
111861 */
111862 #define POS_COLUMN  (1)     /* Column-list terminator */
111863 #define POS_END     (0)     /* Position-list terminator */ 
111864
111865 /*
111866 ** This section provides definitions to allow the
111867 ** FTS3 extension to be compiled outside of the 
111868 ** amalgamation.
111869 */
111870 #ifndef SQLITE_AMALGAMATION
111871 /*
111872 ** Macros indicating that conditional expressions are always true or
111873 ** false.
111874 */
111875 #ifdef SQLITE_COVERAGE_TEST
111876 # define ALWAYS(x) (1)
111877 # define NEVER(X)  (0)
111878 #else
111879 # define ALWAYS(x) (x)
111880 # define NEVER(X)  (x)
111881 #endif
111882
111883 /*
111884 ** Internal types used by SQLite.
111885 */
111886 typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
111887 typedef short int i16;            /* 2-byte (or larger) signed integer */
111888 typedef unsigned int u32;         /* 4-byte unsigned integer */
111889 typedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */
111890
111891 /*
111892 ** Macro used to suppress compiler warnings for unused parameters.
111893 */
111894 #define UNUSED_PARAMETER(x) (void)(x)
111895
111896 /*
111897 ** Activate assert() only if SQLITE_TEST is enabled.
111898 */
111899 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
111900 # define NDEBUG 1
111901 #endif
111902
111903 /*
111904 ** The TESTONLY macro is used to enclose variable declarations or
111905 ** other bits of code that are needed to support the arguments
111906 ** within testcase() and assert() macros.
111907 */
111908 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
111909 # define TESTONLY(X)  X
111910 #else
111911 # define TESTONLY(X)
111912 #endif
111913
111914 #endif /* SQLITE_AMALGAMATION */
111915
111916 typedef struct Fts3Table Fts3Table;
111917 typedef struct Fts3Cursor Fts3Cursor;
111918 typedef struct Fts3Expr Fts3Expr;
111919 typedef struct Fts3Phrase Fts3Phrase;
111920 typedef struct Fts3PhraseToken Fts3PhraseToken;
111921
111922 typedef struct Fts3Doclist Fts3Doclist;
111923 typedef struct Fts3SegFilter Fts3SegFilter;
111924 typedef struct Fts3DeferredToken Fts3DeferredToken;
111925 typedef struct Fts3SegReader Fts3SegReader;
111926 typedef struct Fts3MultiSegReader Fts3MultiSegReader;
111927
111928 /*
111929 ** A connection to a fulltext index is an instance of the following
111930 ** structure. The xCreate and xConnect methods create an instance
111931 ** of this structure and xDestroy and xDisconnect free that instance.
111932 ** All other methods receive a pointer to the structure as one of their
111933 ** arguments.
111934 */
111935 struct Fts3Table {
111936   sqlite3_vtab base;              /* Base class used by SQLite core */
111937   sqlite3 *db;                    /* The database connection */
111938   const char *zDb;                /* logical database name */
111939   const char *zName;              /* virtual table name */
111940   int nColumn;                    /* number of named columns in virtual table */
111941   char **azColumn;                /* column names.  malloced */
111942   sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
111943
111944   /* Precompiled statements used by the implementation. Each of these 
111945   ** statements is run and reset within a single virtual table API call. 
111946   */
111947   sqlite3_stmt *aStmt[27];
111948
111949   char *zReadExprlist;
111950   char *zWriteExprlist;
111951
111952   int nNodeSize;                  /* Soft limit for node size */
111953   u8 bHasStat;                    /* True if %_stat table exists */
111954   u8 bHasDocsize;                 /* True if %_docsize table exists */
111955   u8 bDescIdx;                    /* True if doclists are in reverse order */
111956   int nPgsz;                      /* Page size for host database */
111957   char *zSegmentsTbl;             /* Name of %_segments table */
111958   sqlite3_blob *pSegments;        /* Blob handle open on %_segments table */
111959
111960   /* TODO: Fix the first paragraph of this comment.
111961   **
111962   ** The following hash table is used to buffer pending index updates during
111963   ** transactions. Variable nPendingData estimates the memory size of the 
111964   ** pending data, including hash table overhead, but not malloc overhead. 
111965   ** When nPendingData exceeds nMaxPendingData, the buffer is flushed 
111966   ** automatically. Variable iPrevDocid is the docid of the most recently
111967   ** inserted record.
111968   **
111969   ** A single FTS4 table may have multiple full-text indexes. For each index
111970   ** there is an entry in the aIndex[] array. Index 0 is an index of all the
111971   ** terms that appear in the document set. Each subsequent index in aIndex[]
111972   ** is an index of prefixes of a specific length.
111973   */
111974   int nIndex;                     /* Size of aIndex[] */
111975   struct Fts3Index {
111976     int nPrefix;                  /* Prefix length (0 for main terms index) */
111977     Fts3Hash hPending;            /* Pending terms table for this index */
111978   } *aIndex;
111979   int nMaxPendingData;            /* Max pending data before flush to disk */
111980   int nPendingData;               /* Current bytes of pending data */
111981   sqlite_int64 iPrevDocid;        /* Docid of most recently inserted document */
111982
111983 #if defined(SQLITE_DEBUG)
111984   /* State variables used for validating that the transaction control
111985   ** methods of the virtual table are called at appropriate times.  These
111986   ** values do not contribution to the FTS computation; they are used for
111987   ** verifying the SQLite core.
111988   */
111989   int inTransaction;     /* True after xBegin but before xCommit/xRollback */
111990   int mxSavepoint;       /* Largest valid xSavepoint integer */
111991 #endif
111992 };
111993
111994 /*
111995 ** When the core wants to read from the virtual table, it creates a
111996 ** virtual table cursor (an instance of the following structure) using
111997 ** the xOpen method. Cursors are destroyed using the xClose method.
111998 */
111999 struct Fts3Cursor {
112000   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
112001   i16 eSearch;                    /* Search strategy (see below) */
112002   u8 isEof;                       /* True if at End Of Results */
112003   u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
112004   sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */
112005   Fts3Expr *pExpr;                /* Parsed MATCH query string */
112006   int nPhrase;                    /* Number of matchable phrases in query */
112007   Fts3DeferredToken *pDeferred;   /* Deferred search tokens, if any */
112008   sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */
112009   char *pNextId;                  /* Pointer into the body of aDoclist */
112010   char *aDoclist;                 /* List of docids for full-text queries */
112011   int nDoclist;                   /* Size of buffer at aDoclist */
112012   u8 bDesc;                       /* True to sort in descending order */
112013   int eEvalmode;                  /* An FTS3_EVAL_XX constant */
112014   int nRowAvg;                    /* Average size of database rows, in pages */
112015   sqlite3_int64 nDoc;             /* Documents in table */
112016
112017   int isMatchinfoNeeded;          /* True when aMatchinfo[] needs filling in */
112018   u32 *aMatchinfo;                /* Information about most recent match */
112019   int nMatchinfo;                 /* Number of elements in aMatchinfo[] */
112020   char *zMatchinfo;               /* Matchinfo specification */
112021 };
112022
112023 #define FTS3_EVAL_FILTER    0
112024 #define FTS3_EVAL_NEXT      1
112025 #define FTS3_EVAL_MATCHINFO 2
112026
112027 /*
112028 ** The Fts3Cursor.eSearch member is always set to one of the following.
112029 ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
112030 ** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
112031 ** of the column to be searched.  For example, in
112032 **
112033 **     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
112034 **     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
112035 ** 
112036 ** Because the LHS of the MATCH operator is 2nd column "b",
112037 ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
112038 ** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1" 
112039 ** indicating that all columns should be searched,
112040 ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
112041 */
112042 #define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
112043 #define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
112044 #define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
112045
112046
112047 struct Fts3Doclist {
112048   char *aAll;                    /* Array containing doclist (or NULL) */
112049   int nAll;                      /* Size of a[] in bytes */
112050   char *pNextDocid;              /* Pointer to next docid */
112051
112052   sqlite3_int64 iDocid;          /* Current docid (if pList!=0) */
112053   int bFreeList;                 /* True if pList should be sqlite3_free()d */
112054   char *pList;                   /* Pointer to position list following iDocid */
112055   int nList;                     /* Length of position list */
112056 } doclist;
112057
112058 /*
112059 ** A "phrase" is a sequence of one or more tokens that must match in
112060 ** sequence.  A single token is the base case and the most common case.
112061 ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
112062 ** nToken will be the number of tokens in the string.
112063 */
112064 struct Fts3PhraseToken {
112065   char *z;                        /* Text of the token */
112066   int n;                          /* Number of bytes in buffer z */
112067   int isPrefix;                   /* True if token ends with a "*" character */
112068
112069   /* Variables above this point are populated when the expression is
112070   ** parsed (by code in fts3_expr.c). Below this point the variables are
112071   ** used when evaluating the expression. */
112072   Fts3DeferredToken *pDeferred;   /* Deferred token object for this token */
112073   Fts3MultiSegReader *pSegcsr;    /* Segment-reader for this token */
112074 };
112075
112076 struct Fts3Phrase {
112077   /* Cache of doclist for this phrase. */
112078   Fts3Doclist doclist;
112079   int bIncr;                 /* True if doclist is loaded incrementally */
112080   int iDoclistToken;
112081
112082   /* Variables below this point are populated by fts3_expr.c when parsing 
112083   ** a MATCH expression. Everything above is part of the evaluation phase. 
112084   */
112085   int nToken;                /* Number of tokens in the phrase */
112086   int iColumn;               /* Index of column this phrase must match */
112087   Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
112088 };
112089
112090 /*
112091 ** A tree of these objects forms the RHS of a MATCH operator.
112092 **
112093 ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist 
112094 ** points to a malloced buffer, size nDoclist bytes, containing the results 
112095 ** of this phrase query in FTS3 doclist format. As usual, the initial 
112096 ** "Length" field found in doclists stored on disk is omitted from this 
112097 ** buffer.
112098 **
112099 ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
112100 ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
112101 ** where nCol is the number of columns in the queried FTS table. The array
112102 ** is populated as follows:
112103 **
112104 **   aMI[iCol*3 + 0] = Undefined
112105 **   aMI[iCol*3 + 1] = Number of occurrences
112106 **   aMI[iCol*3 + 2] = Number of rows containing at least one instance
112107 **
112108 ** The aMI array is allocated using sqlite3_malloc(). It should be freed 
112109 ** when the expression node is.
112110 */
112111 struct Fts3Expr {
112112   int eType;                 /* One of the FTSQUERY_XXX values defined below */
112113   int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
112114   Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
112115   Fts3Expr *pLeft;           /* Left operand */
112116   Fts3Expr *pRight;          /* Right operand */
112117   Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
112118
112119   /* The following are used by the fts3_eval.c module. */
112120   sqlite3_int64 iDocid;      /* Current docid */
112121   u8 bEof;                   /* True this expression is at EOF already */
112122   u8 bStart;                 /* True if iDocid is valid */
112123   u8 bDeferred;              /* True if this expression is entirely deferred */
112124
112125   u32 *aMI;
112126 };
112127
112128 /*
112129 ** Candidate values for Fts3Query.eType. Note that the order of the first
112130 ** four values is in order of precedence when parsing expressions. For 
112131 ** example, the following:
112132 **
112133 **   "a OR b AND c NOT d NEAR e"
112134 **
112135 ** is equivalent to:
112136 **
112137 **   "a OR (b AND (c NOT (d NEAR e)))"
112138 */
112139 #define FTSQUERY_NEAR   1
112140 #define FTSQUERY_NOT    2
112141 #define FTSQUERY_AND    3
112142 #define FTSQUERY_OR     4
112143 #define FTSQUERY_PHRASE 5
112144
112145
112146 /* fts3_write.c */
112147 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
112148 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
112149 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
112150 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
112151 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, sqlite3_int64,
112152   sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
112153 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
112154   Fts3Table*,int,const char*,int,int,Fts3SegReader**);
112155 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
112156 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, sqlite3_stmt **);
112157 SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *);
112158 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
112159
112160 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
112161 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
112162
112163 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
112164 SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
112165 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
112166 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
112167 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
112168
112169 /* Special values interpreted by sqlite3SegReaderCursor() */
112170 #define FTS3_SEGCURSOR_PENDING        -1
112171 #define FTS3_SEGCURSOR_ALL            -2
112172
112173 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
112174 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
112175 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
112176
112177 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
112178     Fts3Table *, int, int, const char *, int, int, int, Fts3MultiSegReader *);
112179
112180 /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
112181 #define FTS3_SEGMENT_REQUIRE_POS   0x00000001
112182 #define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
112183 #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
112184 #define FTS3_SEGMENT_PREFIX        0x00000008
112185 #define FTS3_SEGMENT_SCAN          0x00000010
112186
112187 /* Type passed as 4th argument to SegmentReaderIterate() */
112188 struct Fts3SegFilter {
112189   const char *zTerm;
112190   int nTerm;
112191   int iCol;
112192   int flags;
112193 };
112194
112195 struct Fts3MultiSegReader {
112196   /* Used internally by sqlite3Fts3SegReaderXXX() calls */
112197   Fts3SegReader **apSegment;      /* Array of Fts3SegReader objects */
112198   int nSegment;                   /* Size of apSegment array */
112199   int nAdvance;                   /* How many seg-readers to advance */
112200   Fts3SegFilter *pFilter;         /* Pointer to filter object */
112201   char *aBuffer;                  /* Buffer to merge doclists in */
112202   int nBuffer;                    /* Allocated size of aBuffer[] in bytes */
112203
112204   int iColFilter;                 /* If >=0, filter for this column */
112205   int bRestart;
112206
112207   /* Used by fts3.c only. */
112208   int nCost;                      /* Cost of running iterator */
112209   int bLookup;                    /* True if a lookup of a single entry. */
112210
112211   /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
112212   char *zTerm;                    /* Pointer to term buffer */
112213   int nTerm;                      /* Size of zTerm in bytes */
112214   char *aDoclist;                 /* Pointer to doclist buffer */
112215   int nDoclist;                   /* Size of aDoclist[] in bytes */
112216 };
112217
112218 /* fts3.c */
112219 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
112220 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
112221 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
112222 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
112223 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
112224 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
112225
112226 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
112227
112228 /* fts3_tokenizer.c */
112229 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
112230 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
112231 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *, 
112232     sqlite3_tokenizer **, char **
112233 );
112234 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
112235
112236 /* fts3_snippet.c */
112237 SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
112238 SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
112239   const char *, const char *, int, int
112240 );
112241 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
112242
112243 /* fts3_expr.c */
112244 SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, 
112245   char **, int, int, const char *, int, Fts3Expr **
112246 );
112247 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
112248 #ifdef SQLITE_TEST
112249 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
112250 SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
112251 #endif
112252
112253 /* fts3_aux.c */
112254 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
112255
112256 SQLITE_PRIVATE int sqlite3Fts3TermSegReaderCursor(
112257   Fts3Cursor *pCsr,               /* Virtual table cursor handle */
112258   const char *zTerm,              /* Term to query for */
112259   int nTerm,                      /* Size of zTerm in bytes */
112260   int isPrefix,                   /* True for a prefix search */
112261   Fts3MultiSegReader **ppSegcsr   /* OUT: Allocated seg-reader cursor */
112262 );
112263
112264 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
112265
112266 SQLITE_PRIVATE int sqlite3Fts3EvalStart(Fts3Cursor *, Fts3Expr *, int);
112267 SQLITE_PRIVATE int sqlite3Fts3EvalNext(Fts3Cursor *pCsr);
112268
112269 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
112270     Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
112271 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
112272     Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
112273 SQLITE_PRIVATE char *sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol); 
112274 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
112275 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
112276
112277 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
112278
112279 #endif /* SQLITE_ENABLE_FTS3 */
112280 #endif /* _FTSINT_H */
112281
112282 /************** End of fts3Int.h *********************************************/
112283 /************** Continuing where we left off in fts3.c ***********************/
112284 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
112285
112286 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
112287 # define SQLITE_CORE 1
112288 #endif
112289
112290
112291 #ifndef SQLITE_CORE 
112292   SQLITE_EXTENSION_INIT1
112293 #endif
112294
112295 /* 
112296 ** Write a 64-bit variable-length integer to memory starting at p[0].
112297 ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
112298 ** The number of bytes written is returned.
112299 */
112300 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
112301   unsigned char *q = (unsigned char *) p;
112302   sqlite_uint64 vu = v;
112303   do{
112304     *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
112305     vu >>= 7;
112306   }while( vu!=0 );
112307   q[-1] &= 0x7f;  /* turn off high bit in final byte */
112308   assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
112309   return (int) (q - (unsigned char *)p);
112310 }
112311
112312 /* 
112313 ** Read a 64-bit variable-length integer from memory starting at p[0].
112314 ** Return the number of bytes read, or 0 on error.
112315 ** The value is stored in *v.
112316 */
112317 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
112318   const unsigned char *q = (const unsigned char *) p;
112319   sqlite_uint64 x = 0, y = 1;
112320   while( (*q&0x80)==0x80 && q-(unsigned char *)p<FTS3_VARINT_MAX ){
112321     x += y * (*q++ & 0x7f);
112322     y <<= 7;
112323   }
112324   x += y * (*q++);
112325   *v = (sqlite_int64) x;
112326   return (int) (q - (unsigned char *)p);
112327 }
112328
112329 /*
112330 ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
112331 ** 32-bit integer before it is returned.
112332 */
112333 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
112334  sqlite_int64 i;
112335  int ret = sqlite3Fts3GetVarint(p, &i);
112336  *pi = (int) i;
112337  return ret;
112338 }
112339
112340 /*
112341 ** Return the number of bytes required to encode v as a varint
112342 */
112343 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
112344   int i = 0;
112345   do{
112346     i++;
112347     v >>= 7;
112348   }while( v!=0 );
112349   return i;
112350 }
112351
112352 /*
112353 ** Convert an SQL-style quoted string into a normal string by removing
112354 ** the quote characters.  The conversion is done in-place.  If the
112355 ** input does not begin with a quote character, then this routine
112356 ** is a no-op.
112357 **
112358 ** Examples:
112359 **
112360 **     "abc"   becomes   abc
112361 **     'xyz'   becomes   xyz
112362 **     [pqr]   becomes   pqr
112363 **     `mno`   becomes   mno
112364 **
112365 */
112366 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
112367   char quote;                     /* Quote character (if any ) */
112368
112369   quote = z[0];
112370   if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
112371     int iIn = 1;                  /* Index of next byte to read from input */
112372     int iOut = 0;                 /* Index of next byte to write to output */
112373
112374     /* If the first byte was a '[', then the close-quote character is a ']' */
112375     if( quote=='[' ) quote = ']';  
112376
112377     while( ALWAYS(z[iIn]) ){
112378       if( z[iIn]==quote ){
112379         if( z[iIn+1]!=quote ) break;
112380         z[iOut++] = quote;
112381         iIn += 2;
112382       }else{
112383         z[iOut++] = z[iIn++];
112384       }
112385     }
112386     z[iOut] = '\0';
112387   }
112388 }
112389
112390 /*
112391 ** Read a single varint from the doclist at *pp and advance *pp to point
112392 ** to the first byte past the end of the varint.  Add the value of the varint
112393 ** to *pVal.
112394 */
112395 static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
112396   sqlite3_int64 iVal;
112397   *pp += sqlite3Fts3GetVarint(*pp, &iVal);
112398   *pVal += iVal;
112399 }
112400
112401 /*
112402 ** When this function is called, *pp points to the first byte following a
112403 ** varint that is part of a doclist (or position-list, or any other list
112404 ** of varints). This function moves *pp to point to the start of that varint,
112405 ** and sets *pVal by the varint value.
112406 **
112407 ** Argument pStart points to the first byte of the doclist that the
112408 ** varint is part of.
112409 */
112410 static void fts3GetReverseVarint(
112411   char **pp, 
112412   char *pStart, 
112413   sqlite3_int64 *pVal
112414 ){
112415   sqlite3_int64 iVal;
112416   char *p = *pp;
112417
112418   /* Pointer p now points at the first byte past the varint we are 
112419   ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
112420   ** clear on character p[-1]. */
112421   for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
112422   p++;
112423   *pp = p;
112424
112425   sqlite3Fts3GetVarint(p, &iVal);
112426   *pVal = iVal;
112427 }
112428
112429 /*
112430 ** The xDisconnect() virtual table method.
112431 */
112432 static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
112433   Fts3Table *p = (Fts3Table *)pVtab;
112434   int i;
112435
112436   assert( p->nPendingData==0 );
112437   assert( p->pSegments==0 );
112438
112439   /* Free any prepared statements held */
112440   for(i=0; i<SizeofArray(p->aStmt); i++){
112441     sqlite3_finalize(p->aStmt[i]);
112442   }
112443   sqlite3_free(p->zSegmentsTbl);
112444   sqlite3_free(p->zReadExprlist);
112445   sqlite3_free(p->zWriteExprlist);
112446
112447   /* Invoke the tokenizer destructor to free the tokenizer. */
112448   p->pTokenizer->pModule->xDestroy(p->pTokenizer);
112449
112450   sqlite3_free(p);
112451   return SQLITE_OK;
112452 }
112453
112454 /*
112455 ** Construct one or more SQL statements from the format string given
112456 ** and then evaluate those statements. The success code is written
112457 ** into *pRc.
112458 **
112459 ** If *pRc is initially non-zero then this routine is a no-op.
112460 */
112461 static void fts3DbExec(
112462   int *pRc,              /* Success code */
112463   sqlite3 *db,           /* Database in which to run SQL */
112464   const char *zFormat,   /* Format string for SQL */
112465   ...                    /* Arguments to the format string */
112466 ){
112467   va_list ap;
112468   char *zSql;
112469   if( *pRc ) return;
112470   va_start(ap, zFormat);
112471   zSql = sqlite3_vmprintf(zFormat, ap);
112472   va_end(ap);
112473   if( zSql==0 ){
112474     *pRc = SQLITE_NOMEM;
112475   }else{
112476     *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
112477     sqlite3_free(zSql);
112478   }
112479 }
112480
112481 /*
112482 ** The xDestroy() virtual table method.
112483 */
112484 static int fts3DestroyMethod(sqlite3_vtab *pVtab){
112485   int rc = SQLITE_OK;              /* Return code */
112486   Fts3Table *p = (Fts3Table *)pVtab;
112487   sqlite3 *db = p->db;
112488
112489   /* Drop the shadow tables */
112490   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", p->zDb, p->zName);
112491   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", p->zDb,p->zName);
112492   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", p->zDb, p->zName);
112493   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", p->zDb, p->zName);
112494   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", p->zDb, p->zName);
112495
112496   /* If everything has worked, invoke fts3DisconnectMethod() to free the
112497   ** memory associated with the Fts3Table structure and return SQLITE_OK.
112498   ** Otherwise, return an SQLite error code.
112499   */
112500   return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
112501 }
112502
112503
112504 /*
112505 ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
112506 ** passed as the first argument. This is done as part of the xConnect()
112507 ** and xCreate() methods.
112508 **
112509 ** If *pRc is non-zero when this function is called, it is a no-op. 
112510 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
112511 ** before returning.
112512 */
112513 static void fts3DeclareVtab(int *pRc, Fts3Table *p){
112514   if( *pRc==SQLITE_OK ){
112515     int i;                        /* Iterator variable */
112516     int rc;                       /* Return code */
112517     char *zSql;                   /* SQL statement passed to declare_vtab() */
112518     char *zCols;                  /* List of user defined columns */
112519
112520     sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
112521
112522     /* Create a list of user columns for the virtual table */
112523     zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
112524     for(i=1; zCols && i<p->nColumn; i++){
112525       zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
112526     }
112527
112528     /* Create the whole "CREATE TABLE" statement to pass to SQLite */
112529     zSql = sqlite3_mprintf(
112530         "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN)", zCols, p->zName
112531     );
112532     if( !zCols || !zSql ){
112533       rc = SQLITE_NOMEM;
112534     }else{
112535       rc = sqlite3_declare_vtab(p->db, zSql);
112536     }
112537
112538     sqlite3_free(zSql);
112539     sqlite3_free(zCols);
112540     *pRc = rc;
112541   }
112542 }
112543
112544 /*
112545 ** Create the backing store tables (%_content, %_segments and %_segdir)
112546 ** required by the FTS3 table passed as the only argument. This is done
112547 ** as part of the vtab xCreate() method.
112548 **
112549 ** If the p->bHasDocsize boolean is true (indicating that this is an
112550 ** FTS4 table, not an FTS3 table) then also create the %_docsize and
112551 ** %_stat tables required by FTS4.
112552 */
112553 static int fts3CreateTables(Fts3Table *p){
112554   int rc = SQLITE_OK;             /* Return code */
112555   int i;                          /* Iterator variable */
112556   char *zContentCols;             /* Columns of %_content table */
112557   sqlite3 *db = p->db;            /* The database connection */
112558
112559   /* Create a list of user columns for the content table */
112560   zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
112561   for(i=0; zContentCols && i<p->nColumn; i++){
112562     char *z = p->azColumn[i];
112563     zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
112564   }
112565   if( zContentCols==0 ) rc = SQLITE_NOMEM;
112566
112567   /* Create the content table */
112568   fts3DbExec(&rc, db, 
112569      "CREATE TABLE %Q.'%q_content'(%s)",
112570      p->zDb, p->zName, zContentCols
112571   );
112572   sqlite3_free(zContentCols);
112573   /* Create other tables */
112574   fts3DbExec(&rc, db, 
112575       "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
112576       p->zDb, p->zName
112577   );
112578   fts3DbExec(&rc, db, 
112579       "CREATE TABLE %Q.'%q_segdir'("
112580         "level INTEGER,"
112581         "idx INTEGER,"
112582         "start_block INTEGER,"
112583         "leaves_end_block INTEGER,"
112584         "end_block INTEGER,"
112585         "root BLOB,"
112586         "PRIMARY KEY(level, idx)"
112587       ");",
112588       p->zDb, p->zName
112589   );
112590   if( p->bHasDocsize ){
112591     fts3DbExec(&rc, db, 
112592         "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
112593         p->zDb, p->zName
112594     );
112595   }
112596   if( p->bHasStat ){
112597     fts3DbExec(&rc, db, 
112598         "CREATE TABLE %Q.'%q_stat'(id INTEGER PRIMARY KEY, value BLOB);",
112599         p->zDb, p->zName
112600     );
112601   }
112602   return rc;
112603 }
112604
112605 /*
112606 ** Store the current database page-size in bytes in p->nPgsz.
112607 **
112608 ** If *pRc is non-zero when this function is called, it is a no-op. 
112609 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
112610 ** before returning.
112611 */
112612 static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
112613   if( *pRc==SQLITE_OK ){
112614     int rc;                       /* Return code */
112615     char *zSql;                   /* SQL text "PRAGMA %Q.page_size" */
112616     sqlite3_stmt *pStmt;          /* Compiled "PRAGMA %Q.page_size" statement */
112617   
112618     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
112619     if( !zSql ){
112620       rc = SQLITE_NOMEM;
112621     }else{
112622       rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
112623       if( rc==SQLITE_OK ){
112624         sqlite3_step(pStmt);
112625         p->nPgsz = sqlite3_column_int(pStmt, 0);
112626         rc = sqlite3_finalize(pStmt);
112627       }else if( rc==SQLITE_AUTH ){
112628         p->nPgsz = 1024;
112629         rc = SQLITE_OK;
112630       }
112631     }
112632     assert( p->nPgsz>0 || rc!=SQLITE_OK );
112633     sqlite3_free(zSql);
112634     *pRc = rc;
112635   }
112636 }
112637
112638 /*
112639 ** "Special" FTS4 arguments are column specifications of the following form:
112640 **
112641 **   <key> = <value>
112642 **
112643 ** There may not be whitespace surrounding the "=" character. The <value> 
112644 ** term may be quoted, but the <key> may not.
112645 */
112646 static int fts3IsSpecialColumn(
112647   const char *z, 
112648   int *pnKey,
112649   char **pzValue
112650 ){
112651   char *zValue;
112652   const char *zCsr = z;
112653
112654   while( *zCsr!='=' ){
112655     if( *zCsr=='\0' ) return 0;
112656     zCsr++;
112657   }
112658
112659   *pnKey = (int)(zCsr-z);
112660   zValue = sqlite3_mprintf("%s", &zCsr[1]);
112661   if( zValue ){
112662     sqlite3Fts3Dequote(zValue);
112663   }
112664   *pzValue = zValue;
112665   return 1;
112666 }
112667
112668 /*
112669 ** Append the output of a printf() style formatting to an existing string.
112670 */
112671 static void fts3Appendf(
112672   int *pRc,                       /* IN/OUT: Error code */
112673   char **pz,                      /* IN/OUT: Pointer to string buffer */
112674   const char *zFormat,            /* Printf format string to append */
112675   ...                             /* Arguments for printf format string */
112676 ){
112677   if( *pRc==SQLITE_OK ){
112678     va_list ap;
112679     char *z;
112680     va_start(ap, zFormat);
112681     z = sqlite3_vmprintf(zFormat, ap);
112682     if( z && *pz ){
112683       char *z2 = sqlite3_mprintf("%s%s", *pz, z);
112684       sqlite3_free(z);
112685       z = z2;
112686     }
112687     if( z==0 ) *pRc = SQLITE_NOMEM;
112688     sqlite3_free(*pz);
112689     *pz = z;
112690   }
112691 }
112692
112693 /*
112694 ** Return a copy of input string zInput enclosed in double-quotes (") and
112695 ** with all double quote characters escaped. For example:
112696 **
112697 **     fts3QuoteId("un \"zip\"")   ->    "un \"\"zip\"\""
112698 **
112699 ** The pointer returned points to memory obtained from sqlite3_malloc(). It
112700 ** is the callers responsibility to call sqlite3_free() to release this
112701 ** memory.
112702 */
112703 static char *fts3QuoteId(char const *zInput){
112704   int nRet;
112705   char *zRet;
112706   nRet = 2 + strlen(zInput)*2 + 1;
112707   zRet = sqlite3_malloc(nRet);
112708   if( zRet ){
112709     int i;
112710     char *z = zRet;
112711     *(z++) = '"';
112712     for(i=0; zInput[i]; i++){
112713       if( zInput[i]=='"' ) *(z++) = '"';
112714       *(z++) = zInput[i];
112715     }
112716     *(z++) = '"';
112717     *(z++) = '\0';
112718   }
112719   return zRet;
112720 }
112721
112722 /*
112723 ** Return a list of comma separated SQL expressions that could be used
112724 ** in a SELECT statement such as the following:
112725 **
112726 **     SELECT <list of expressions> FROM %_content AS x ...
112727 **
112728 ** to return the docid, followed by each column of text data in order
112729 ** from left to write. If parameter zFunc is not NULL, then instead of
112730 ** being returned directly each column of text data is passed to an SQL
112731 ** function named zFunc first. For example, if zFunc is "unzip" and the
112732 ** table has the three user-defined columns "a", "b", and "c", the following
112733 ** string is returned:
112734 **
112735 **     "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c')"
112736 **
112737 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
112738 ** is the responsibility of the caller to eventually free it.
112739 **
112740 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
112741 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
112742 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
112743 ** no error occurs, *pRc is left unmodified.
112744 */
112745 static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
112746   char *zRet = 0;
112747   char *zFree = 0;
112748   char *zFunction;
112749   int i;
112750
112751   if( !zFunc ){
112752     zFunction = "";
112753   }else{
112754     zFree = zFunction = fts3QuoteId(zFunc);
112755   }
112756   fts3Appendf(pRc, &zRet, "docid");
112757   for(i=0; i<p->nColumn; i++){
112758     fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
112759   }
112760   sqlite3_free(zFree);
112761   return zRet;
112762 }
112763
112764 /*
112765 ** Return a list of N comma separated question marks, where N is the number
112766 ** of columns in the %_content table (one for the docid plus one for each
112767 ** user-defined text column).
112768 **
112769 ** If argument zFunc is not NULL, then all but the first question mark
112770 ** is preceded by zFunc and an open bracket, and followed by a closed
112771 ** bracket. For example, if zFunc is "zip" and the FTS3 table has three 
112772 ** user-defined text columns, the following string is returned:
112773 **
112774 **     "?, zip(?), zip(?), zip(?)"
112775 **
112776 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
112777 ** is the responsibility of the caller to eventually free it.
112778 **
112779 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
112780 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
112781 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
112782 ** no error occurs, *pRc is left unmodified.
112783 */
112784 static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
112785   char *zRet = 0;
112786   char *zFree = 0;
112787   char *zFunction;
112788   int i;
112789
112790   if( !zFunc ){
112791     zFunction = "";
112792   }else{
112793     zFree = zFunction = fts3QuoteId(zFunc);
112794   }
112795   fts3Appendf(pRc, &zRet, "?");
112796   for(i=0; i<p->nColumn; i++){
112797     fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
112798   }
112799   sqlite3_free(zFree);
112800   return zRet;
112801 }
112802
112803 static int fts3GobbleInt(const char **pp, int *pnOut){
112804   const char *p = *pp;
112805   int nInt = 0;
112806   for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
112807     nInt = nInt * 10 + (p[0] - '0');
112808   }
112809   if( p==*pp ) return SQLITE_ERROR;
112810   *pnOut = nInt;
112811   *pp = p;
112812   return SQLITE_OK;
112813 }
112814
112815
112816 static int fts3PrefixParameter(
112817   const char *zParam,             /* ABC in prefix=ABC parameter to parse */
112818   int *pnIndex,                   /* OUT: size of *apIndex[] array */
112819   struct Fts3Index **apIndex,     /* OUT: Array of indexes for this table */
112820   struct Fts3Index **apFree       /* OUT: Free this with sqlite3_free() */
112821 ){
112822   struct Fts3Index *aIndex;
112823   int nIndex = 1;
112824
112825   if( zParam && zParam[0] ){
112826     const char *p;
112827     nIndex++;
112828     for(p=zParam; *p; p++){
112829       if( *p==',' ) nIndex++;
112830     }
112831   }
112832
112833   aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
112834   *apIndex = *apFree = aIndex;
112835   *pnIndex = nIndex;
112836   if( !aIndex ){
112837     return SQLITE_NOMEM;
112838   }
112839
112840   memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
112841   if( zParam ){
112842     const char *p = zParam;
112843     int i;
112844     for(i=1; i<nIndex; i++){
112845       int nPrefix;
112846       if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
112847       aIndex[i].nPrefix = nPrefix;
112848       p++;
112849     }
112850   }
112851
112852   return SQLITE_OK;
112853 }
112854
112855 /*
112856 ** This function is the implementation of both the xConnect and xCreate
112857 ** methods of the FTS3 virtual table.
112858 **
112859 ** The argv[] array contains the following:
112860 **
112861 **   argv[0]   -> module name  ("fts3" or "fts4")
112862 **   argv[1]   -> database name
112863 **   argv[2]   -> table name
112864 **   argv[...] -> "column name" and other module argument fields.
112865 */
112866 static int fts3InitVtab(
112867   int isCreate,                   /* True for xCreate, false for xConnect */
112868   sqlite3 *db,                    /* The SQLite database connection */
112869   void *pAux,                     /* Hash table containing tokenizers */
112870   int argc,                       /* Number of elements in argv array */
112871   const char * const *argv,       /* xCreate/xConnect argument array */
112872   sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
112873   char **pzErr                    /* Write any error message here */
112874 ){
112875   Fts3Hash *pHash = (Fts3Hash *)pAux;
112876   Fts3Table *p = 0;               /* Pointer to allocated vtab */
112877   int rc = SQLITE_OK;             /* Return code */
112878   int i;                          /* Iterator variable */
112879   int nByte;                      /* Size of allocation used for *p */
112880   int iCol;                       /* Column index */
112881   int nString = 0;                /* Bytes required to hold all column names */
112882   int nCol = 0;                   /* Number of columns in the FTS table */
112883   char *zCsr;                     /* Space for holding column names */
112884   int nDb;                        /* Bytes required to hold database name */
112885   int nName;                      /* Bytes required to hold table name */
112886   int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
112887   const char **aCol;              /* Array of column names */
112888   sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
112889
112890   int nIndex;                     /* Size of aIndex[] array */
112891   struct Fts3Index *aIndex;       /* Array of indexes for this table */
112892   struct Fts3Index *aFree = 0;    /* Free this before returning */
112893
112894   /* The results of parsing supported FTS4 key=value options: */
112895   int bNoDocsize = 0;             /* True to omit %_docsize table */
112896   int bDescIdx = 0;               /* True to store descending indexes */
112897   char *zPrefix = 0;              /* Prefix parameter value (or NULL) */
112898   char *zCompress = 0;            /* compress=? parameter (or NULL) */
112899   char *zUncompress = 0;          /* uncompress=? parameter (or NULL) */
112900
112901   assert( strlen(argv[0])==4 );
112902   assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
112903        || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
112904   );
112905
112906   nDb = (int)strlen(argv[1]) + 1;
112907   nName = (int)strlen(argv[2]) + 1;
112908
112909   aCol = (const char **)sqlite3_malloc(sizeof(const char *) * (argc-2) );
112910   if( !aCol ) return SQLITE_NOMEM;
112911   memset((void *)aCol, 0, sizeof(const char *) * (argc-2));
112912
112913   /* Loop through all of the arguments passed by the user to the FTS3/4
112914   ** module (i.e. all the column names and special arguments). This loop
112915   ** does the following:
112916   **
112917   **   + Figures out the number of columns the FTSX table will have, and
112918   **     the number of bytes of space that must be allocated to store copies
112919   **     of the column names.
112920   **
112921   **   + If there is a tokenizer specification included in the arguments,
112922   **     initializes the tokenizer pTokenizer.
112923   */
112924   for(i=3; rc==SQLITE_OK && i<argc; i++){
112925     char const *z = argv[i];
112926     int nKey;
112927     char *zVal;
112928
112929     /* Check if this is a tokenizer specification */
112930     if( !pTokenizer 
112931      && strlen(z)>8
112932      && 0==sqlite3_strnicmp(z, "tokenize", 8) 
112933      && 0==sqlite3Fts3IsIdChar(z[8])
112934     ){
112935       rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
112936     }
112937
112938     /* Check if it is an FTS4 special argument. */
112939     else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
112940       struct Fts4Option {
112941         const char *zOpt;
112942         int nOpt;
112943         char **pzVar;
112944       } aFts4Opt[] = {
112945         { "matchinfo",   9, 0 },            /* 0 -> MATCHINFO */
112946         { "prefix",      6, 0 },            /* 1 -> PREFIX */
112947         { "compress",    8, 0 },            /* 2 -> COMPRESS */
112948         { "uncompress", 10, 0 },            /* 3 -> UNCOMPRESS */
112949         { "order",       5, 0 }             /* 4 -> ORDER */
112950       };
112951
112952       int iOpt;
112953       if( !zVal ){
112954         rc = SQLITE_NOMEM;
112955       }else{
112956         for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
112957           struct Fts4Option *pOp = &aFts4Opt[iOpt];
112958           if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
112959             break;
112960           }
112961         }
112962         if( iOpt==SizeofArray(aFts4Opt) ){
112963           *pzErr = sqlite3_mprintf("unrecognized parameter: %s", z);
112964           rc = SQLITE_ERROR;
112965         }else{
112966           switch( iOpt ){
112967             case 0:               /* MATCHINFO */
112968               if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
112969                 *pzErr = sqlite3_mprintf("unrecognized matchinfo: %s", zVal);
112970                 rc = SQLITE_ERROR;
112971               }
112972               bNoDocsize = 1;
112973               break;
112974
112975             case 1:               /* PREFIX */
112976               sqlite3_free(zPrefix);
112977               zPrefix = zVal;
112978               zVal = 0;
112979               break;
112980
112981             case 2:               /* COMPRESS */
112982               sqlite3_free(zCompress);
112983               zCompress = zVal;
112984               zVal = 0;
112985               break;
112986
112987             case 3:               /* UNCOMPRESS */
112988               sqlite3_free(zUncompress);
112989               zUncompress = zVal;
112990               zVal = 0;
112991               break;
112992
112993             case 4:               /* ORDER */
112994               if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3)) 
112995                && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 3)) 
112996               ){
112997                 *pzErr = sqlite3_mprintf("unrecognized order: %s", zVal);
112998                 rc = SQLITE_ERROR;
112999               }
113000               bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
113001               break;
113002           }
113003         }
113004         sqlite3_free(zVal);
113005       }
113006     }
113007
113008     /* Otherwise, the argument is a column name. */
113009     else {
113010       nString += (int)(strlen(z) + 1);
113011       aCol[nCol++] = z;
113012     }
113013   }
113014   if( rc!=SQLITE_OK ) goto fts3_init_out;
113015
113016   if( nCol==0 ){
113017     assert( nString==0 );
113018     aCol[0] = "content";
113019     nString = 8;
113020     nCol = 1;
113021   }
113022
113023   if( pTokenizer==0 ){
113024     rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
113025     if( rc!=SQLITE_OK ) goto fts3_init_out;
113026   }
113027   assert( pTokenizer );
113028
113029   rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex, &aFree);
113030   if( rc==SQLITE_ERROR ){
113031     assert( zPrefix );
113032     *pzErr = sqlite3_mprintf("error parsing prefix parameter: %s", zPrefix);
113033   }
113034   if( rc!=SQLITE_OK ) goto fts3_init_out;
113035
113036   /* Allocate and populate the Fts3Table structure. */
113037   nByte = sizeof(Fts3Table) +                  /* Fts3Table */
113038           nCol * sizeof(char *) +              /* azColumn */
113039           nIndex * sizeof(struct Fts3Index) +  /* aIndex */
113040           nName +                              /* zName */
113041           nDb +                                /* zDb */
113042           nString;                             /* Space for azColumn strings */
113043   p = (Fts3Table*)sqlite3_malloc(nByte);
113044   if( p==0 ){
113045     rc = SQLITE_NOMEM;
113046     goto fts3_init_out;
113047   }
113048   memset(p, 0, nByte);
113049   p->db = db;
113050   p->nColumn = nCol;
113051   p->nPendingData = 0;
113052   p->azColumn = (char **)&p[1];
113053   p->pTokenizer = pTokenizer;
113054   p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
113055   p->bHasDocsize = (isFts4 && bNoDocsize==0);
113056   p->bHasStat = isFts4;
113057   p->bDescIdx = bDescIdx;
113058   TESTONLY( p->inTransaction = -1 );
113059   TESTONLY( p->mxSavepoint = -1 );
113060
113061   p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
113062   memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
113063   p->nIndex = nIndex;
113064   for(i=0; i<nIndex; i++){
113065     fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
113066   }
113067
113068   /* Fill in the zName and zDb fields of the vtab structure. */
113069   zCsr = (char *)&p->aIndex[nIndex];
113070   p->zName = zCsr;
113071   memcpy(zCsr, argv[2], nName);
113072   zCsr += nName;
113073   p->zDb = zCsr;
113074   memcpy(zCsr, argv[1], nDb);
113075   zCsr += nDb;
113076
113077   /* Fill in the azColumn array */
113078   for(iCol=0; iCol<nCol; iCol++){
113079     char *z; 
113080     int n = 0;
113081     z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
113082     memcpy(zCsr, z, n);
113083     zCsr[n] = '\0';
113084     sqlite3Fts3Dequote(zCsr);
113085     p->azColumn[iCol] = zCsr;
113086     zCsr += n+1;
113087     assert( zCsr <= &((char *)p)[nByte] );
113088   }
113089
113090   if( (zCompress==0)!=(zUncompress==0) ){
113091     char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
113092     rc = SQLITE_ERROR;
113093     *pzErr = sqlite3_mprintf("missing %s parameter in fts4 constructor", zMiss);
113094   }
113095   p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
113096   p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
113097   if( rc!=SQLITE_OK ) goto fts3_init_out;
113098
113099   /* If this is an xCreate call, create the underlying tables in the 
113100   ** database. TODO: For xConnect(), it could verify that said tables exist.
113101   */
113102   if( isCreate ){
113103     rc = fts3CreateTables(p);
113104   }
113105
113106   /* Figure out the page-size for the database. This is required in order to
113107   ** estimate the cost of loading large doclists from the database.  */
113108   fts3DatabasePageSize(&rc, p);
113109   p->nNodeSize = p->nPgsz-35;
113110
113111   /* Declare the table schema to SQLite. */
113112   fts3DeclareVtab(&rc, p);
113113
113114 fts3_init_out:
113115   sqlite3_free(zPrefix);
113116   sqlite3_free(aFree);
113117   sqlite3_free(zCompress);
113118   sqlite3_free(zUncompress);
113119   sqlite3_free((void *)aCol);
113120   if( rc!=SQLITE_OK ){
113121     if( p ){
113122       fts3DisconnectMethod((sqlite3_vtab *)p);
113123     }else if( pTokenizer ){
113124       pTokenizer->pModule->xDestroy(pTokenizer);
113125     }
113126   }else{
113127     assert( p->pSegments==0 );
113128     *ppVTab = &p->base;
113129   }
113130   return rc;
113131 }
113132
113133 /*
113134 ** The xConnect() and xCreate() methods for the virtual table. All the
113135 ** work is done in function fts3InitVtab().
113136 */
113137 static int fts3ConnectMethod(
113138   sqlite3 *db,                    /* Database connection */
113139   void *pAux,                     /* Pointer to tokenizer hash table */
113140   int argc,                       /* Number of elements in argv array */
113141   const char * const *argv,       /* xCreate/xConnect argument array */
113142   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
113143   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
113144 ){
113145   return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
113146 }
113147 static int fts3CreateMethod(
113148   sqlite3 *db,                    /* Database connection */
113149   void *pAux,                     /* Pointer to tokenizer hash table */
113150   int argc,                       /* Number of elements in argv array */
113151   const char * const *argv,       /* xCreate/xConnect argument array */
113152   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
113153   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
113154 ){
113155   return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
113156 }
113157
113158 /* 
113159 ** Implementation of the xBestIndex method for FTS3 tables. There
113160 ** are three possible strategies, in order of preference:
113161 **
113162 **   1. Direct lookup by rowid or docid. 
113163 **   2. Full-text search using a MATCH operator on a non-docid column.
113164 **   3. Linear scan of %_content table.
113165 */
113166 static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
113167   Fts3Table *p = (Fts3Table *)pVTab;
113168   int i;                          /* Iterator variable */
113169   int iCons = -1;                 /* Index of constraint to use */
113170
113171   /* By default use a full table scan. This is an expensive option,
113172   ** so search through the constraints to see if a more efficient 
113173   ** strategy is possible.
113174   */
113175   pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
113176   pInfo->estimatedCost = 500000;
113177   for(i=0; i<pInfo->nConstraint; i++){
113178     struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
113179     if( pCons->usable==0 ) continue;
113180
113181     /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
113182     if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ 
113183      && (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1 )
113184     ){
113185       pInfo->idxNum = FTS3_DOCID_SEARCH;
113186       pInfo->estimatedCost = 1.0;
113187       iCons = i;
113188     }
113189
113190     /* A MATCH constraint. Use a full-text search.
113191     **
113192     ** If there is more than one MATCH constraint available, use the first
113193     ** one encountered. If there is both a MATCH constraint and a direct
113194     ** rowid/docid lookup, prefer the MATCH strategy. This is done even 
113195     ** though the rowid/docid lookup is faster than a MATCH query, selecting
113196     ** it would lead to an "unable to use function MATCH in the requested 
113197     ** context" error.
113198     */
113199     if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH 
113200      && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
113201     ){
113202       pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
113203       pInfo->estimatedCost = 2.0;
113204       iCons = i;
113205       break;
113206     }
113207   }
113208
113209   if( iCons>=0 ){
113210     pInfo->aConstraintUsage[iCons].argvIndex = 1;
113211     pInfo->aConstraintUsage[iCons].omit = 1;
113212   } 
113213
113214   /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
113215   ** docid) order. Both ascending and descending are possible. 
113216   */
113217   if( pInfo->nOrderBy==1 ){
113218     struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
113219     if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
113220       if( pOrder->desc ){
113221         pInfo->idxStr = "DESC";
113222       }else{
113223         pInfo->idxStr = "ASC";
113224       }
113225       pInfo->orderByConsumed = 1;
113226     }
113227   }
113228
113229   assert( p->pSegments==0 );
113230   return SQLITE_OK;
113231 }
113232
113233 /*
113234 ** Implementation of xOpen method.
113235 */
113236 static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
113237   sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
113238
113239   UNUSED_PARAMETER(pVTab);
113240
113241   /* Allocate a buffer large enough for an Fts3Cursor structure. If the
113242   ** allocation succeeds, zero it and return SQLITE_OK. Otherwise, 
113243   ** if the allocation fails, return SQLITE_NOMEM.
113244   */
113245   *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
113246   if( !pCsr ){
113247     return SQLITE_NOMEM;
113248   }
113249   memset(pCsr, 0, sizeof(Fts3Cursor));
113250   return SQLITE_OK;
113251 }
113252
113253 /*
113254 ** Close the cursor.  For additional information see the documentation
113255 ** on the xClose method of the virtual table interface.
113256 */
113257 static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
113258   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
113259   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
113260   sqlite3_finalize(pCsr->pStmt);
113261   sqlite3Fts3ExprFree(pCsr->pExpr);
113262   sqlite3Fts3FreeDeferredTokens(pCsr);
113263   sqlite3_free(pCsr->aDoclist);
113264   sqlite3_free(pCsr->aMatchinfo);
113265   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
113266   sqlite3_free(pCsr);
113267   return SQLITE_OK;
113268 }
113269
113270 /*
113271 ** Position the pCsr->pStmt statement so that it is on the row
113272 ** of the %_content table that contains the last match.  Return
113273 ** SQLITE_OK on success.  
113274 */
113275 static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
113276   if( pCsr->isRequireSeek ){
113277     sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
113278     pCsr->isRequireSeek = 0;
113279     if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
113280       return SQLITE_OK;
113281     }else{
113282       int rc = sqlite3_reset(pCsr->pStmt);
113283       if( rc==SQLITE_OK ){
113284         /* If no row was found and no error has occured, then the %_content
113285         ** table is missing a row that is present in the full-text index.
113286         ** The data structures are corrupt.
113287         */
113288         rc = SQLITE_CORRUPT_VTAB;
113289       }
113290       pCsr->isEof = 1;
113291       if( pContext ){
113292         sqlite3_result_error_code(pContext, rc);
113293       }
113294       return rc;
113295     }
113296   }else{
113297     return SQLITE_OK;
113298   }
113299 }
113300
113301 /*
113302 ** This function is used to process a single interior node when searching
113303 ** a b-tree for a term or term prefix. The node data is passed to this 
113304 ** function via the zNode/nNode parameters. The term to search for is
113305 ** passed in zTerm/nTerm.
113306 **
113307 ** If piFirst is not NULL, then this function sets *piFirst to the blockid
113308 ** of the child node that heads the sub-tree that may contain the term.
113309 **
113310 ** If piLast is not NULL, then *piLast is set to the right-most child node
113311 ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
113312 ** a prefix.
113313 **
113314 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
113315 */
113316 static int fts3ScanInteriorNode(
113317   const char *zTerm,              /* Term to select leaves for */
113318   int nTerm,                      /* Size of term zTerm in bytes */
113319   const char *zNode,              /* Buffer containing segment interior node */
113320   int nNode,                      /* Size of buffer at zNode */
113321   sqlite3_int64 *piFirst,         /* OUT: Selected child node */
113322   sqlite3_int64 *piLast           /* OUT: Selected child node */
113323 ){
113324   int rc = SQLITE_OK;             /* Return code */
113325   const char *zCsr = zNode;       /* Cursor to iterate through node */
113326   const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
113327   char *zBuffer = 0;              /* Buffer to load terms into */
113328   int nAlloc = 0;                 /* Size of allocated buffer */
113329   int isFirstTerm = 1;            /* True when processing first term on page */
113330   sqlite3_int64 iChild;           /* Block id of child node to descend to */
113331
113332   /* Skip over the 'height' varint that occurs at the start of every 
113333   ** interior node. Then load the blockid of the left-child of the b-tree
113334   ** node into variable iChild.  
113335   **
113336   ** Even if the data structure on disk is corrupted, this (reading two
113337   ** varints from the buffer) does not risk an overread. If zNode is a
113338   ** root node, then the buffer comes from a SELECT statement. SQLite does
113339   ** not make this guarantee explicitly, but in practice there are always
113340   ** either more than 20 bytes of allocated space following the nNode bytes of
113341   ** contents, or two zero bytes. Or, if the node is read from the %_segments
113342   ** table, then there are always 20 bytes of zeroed padding following the
113343   ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
113344   */
113345   zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
113346   zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
113347   if( zCsr>zEnd ){
113348     return SQLITE_CORRUPT_VTAB;
113349   }
113350   
113351   while( zCsr<zEnd && (piFirst || piLast) ){
113352     int cmp;                      /* memcmp() result */
113353     int nSuffix;                  /* Size of term suffix */
113354     int nPrefix = 0;              /* Size of term prefix */
113355     int nBuffer;                  /* Total term size */
113356   
113357     /* Load the next term on the node into zBuffer. Use realloc() to expand
113358     ** the size of zBuffer if required.  */
113359     if( !isFirstTerm ){
113360       zCsr += sqlite3Fts3GetVarint32(zCsr, &nPrefix);
113361     }
113362     isFirstTerm = 0;
113363     zCsr += sqlite3Fts3GetVarint32(zCsr, &nSuffix);
113364     
113365     if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
113366       rc = SQLITE_CORRUPT_VTAB;
113367       goto finish_scan;
113368     }
113369     if( nPrefix+nSuffix>nAlloc ){
113370       char *zNew;
113371       nAlloc = (nPrefix+nSuffix) * 2;
113372       zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
113373       if( !zNew ){
113374         rc = SQLITE_NOMEM;
113375         goto finish_scan;
113376       }
113377       zBuffer = zNew;
113378     }
113379     memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
113380     nBuffer = nPrefix + nSuffix;
113381     zCsr += nSuffix;
113382
113383     /* Compare the term we are searching for with the term just loaded from
113384     ** the interior node. If the specified term is greater than or equal
113385     ** to the term from the interior node, then all terms on the sub-tree 
113386     ** headed by node iChild are smaller than zTerm. No need to search 
113387     ** iChild.
113388     **
113389     ** If the interior node term is larger than the specified term, then
113390     ** the tree headed by iChild may contain the specified term.
113391     */
113392     cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
113393     if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
113394       *piFirst = iChild;
113395       piFirst = 0;
113396     }
113397
113398     if( piLast && cmp<0 ){
113399       *piLast = iChild;
113400       piLast = 0;
113401     }
113402
113403     iChild++;
113404   };
113405
113406   if( piFirst ) *piFirst = iChild;
113407   if( piLast ) *piLast = iChild;
113408
113409  finish_scan:
113410   sqlite3_free(zBuffer);
113411   return rc;
113412 }
113413
113414
113415 /*
113416 ** The buffer pointed to by argument zNode (size nNode bytes) contains an
113417 ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
113418 ** contains a term. This function searches the sub-tree headed by the zNode
113419 ** node for the range of leaf nodes that may contain the specified term
113420 ** or terms for which the specified term is a prefix.
113421 **
113422 ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the 
113423 ** left-most leaf node in the tree that may contain the specified term.
113424 ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
113425 ** right-most leaf node that may contain a term for which the specified
113426 ** term is a prefix.
113427 **
113428 ** It is possible that the range of returned leaf nodes does not contain 
113429 ** the specified term or any terms for which it is a prefix. However, if the 
113430 ** segment does contain any such terms, they are stored within the identified
113431 ** range. Because this function only inspects interior segment nodes (and
113432 ** never loads leaf nodes into memory), it is not possible to be sure.
113433 **
113434 ** If an error occurs, an error code other than SQLITE_OK is returned.
113435 */ 
113436 static int fts3SelectLeaf(
113437   Fts3Table *p,                   /* Virtual table handle */
113438   const char *zTerm,              /* Term to select leaves for */
113439   int nTerm,                      /* Size of term zTerm in bytes */
113440   const char *zNode,              /* Buffer containing segment interior node */
113441   int nNode,                      /* Size of buffer at zNode */
113442   sqlite3_int64 *piLeaf,          /* Selected leaf node */
113443   sqlite3_int64 *piLeaf2          /* Selected leaf node */
113444 ){
113445   int rc;                         /* Return code */
113446   int iHeight;                    /* Height of this node in tree */
113447
113448   assert( piLeaf || piLeaf2 );
113449
113450   sqlite3Fts3GetVarint32(zNode, &iHeight);
113451   rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
113452   assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
113453
113454   if( rc==SQLITE_OK && iHeight>1 ){
113455     char *zBlob = 0;              /* Blob read from %_segments table */
113456     int nBlob;                    /* Size of zBlob in bytes */
113457
113458     if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
113459       rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
113460       if( rc==SQLITE_OK ){
113461         rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
113462       }
113463       sqlite3_free(zBlob);
113464       piLeaf = 0;
113465       zBlob = 0;
113466     }
113467
113468     if( rc==SQLITE_OK ){
113469       rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
113470     }
113471     if( rc==SQLITE_OK ){
113472       rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
113473     }
113474     sqlite3_free(zBlob);
113475   }
113476
113477   return rc;
113478 }
113479
113480 /*
113481 ** This function is used to create delta-encoded serialized lists of FTS3 
113482 ** varints. Each call to this function appends a single varint to a list.
113483 */
113484 static void fts3PutDeltaVarint(
113485   char **pp,                      /* IN/OUT: Output pointer */
113486   sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
113487   sqlite3_int64 iVal              /* Write this value to the list */
113488 ){
113489   assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
113490   *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
113491   *piPrev = iVal;
113492 }
113493
113494 /*
113495 ** When this function is called, *ppPoslist is assumed to point to the 
113496 ** start of a position-list. After it returns, *ppPoslist points to the
113497 ** first byte after the position-list.
113498 **
113499 ** A position list is list of positions (delta encoded) and columns for 
113500 ** a single document record of a doclist.  So, in other words, this
113501 ** routine advances *ppPoslist so that it points to the next docid in
113502 ** the doclist, or to the first byte past the end of the doclist.
113503 **
113504 ** If pp is not NULL, then the contents of the position list are copied
113505 ** to *pp. *pp is set to point to the first byte past the last byte copied
113506 ** before this function returns.
113507 */
113508 static void fts3PoslistCopy(char **pp, char **ppPoslist){
113509   char *pEnd = *ppPoslist;
113510   char c = 0;
113511
113512   /* The end of a position list is marked by a zero encoded as an FTS3 
113513   ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
113514   ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
113515   ** of some other, multi-byte, value.
113516   **
113517   ** The following while-loop moves pEnd to point to the first byte that is not 
113518   ** immediately preceded by a byte with the 0x80 bit set. Then increments
113519   ** pEnd once more so that it points to the byte immediately following the
113520   ** last byte in the position-list.
113521   */
113522   while( *pEnd | c ){
113523     c = *pEnd++ & 0x80;
113524     testcase( c!=0 && (*pEnd)==0 );
113525   }
113526   pEnd++;  /* Advance past the POS_END terminator byte */
113527
113528   if( pp ){
113529     int n = (int)(pEnd - *ppPoslist);
113530     char *p = *pp;
113531     memcpy(p, *ppPoslist, n);
113532     p += n;
113533     *pp = p;
113534   }
113535   *ppPoslist = pEnd;
113536 }
113537
113538 /*
113539 ** When this function is called, *ppPoslist is assumed to point to the 
113540 ** start of a column-list. After it returns, *ppPoslist points to the
113541 ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
113542 **
113543 ** A column-list is list of delta-encoded positions for a single column
113544 ** within a single document within a doclist.
113545 **
113546 ** The column-list is terminated either by a POS_COLUMN varint (1) or
113547 ** a POS_END varint (0).  This routine leaves *ppPoslist pointing to
113548 ** the POS_COLUMN or POS_END that terminates the column-list.
113549 **
113550 ** If pp is not NULL, then the contents of the column-list are copied
113551 ** to *pp. *pp is set to point to the first byte past the last byte copied
113552 ** before this function returns.  The POS_COLUMN or POS_END terminator
113553 ** is not copied into *pp.
113554 */
113555 static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
113556   char *pEnd = *ppPoslist;
113557   char c = 0;
113558
113559   /* A column-list is terminated by either a 0x01 or 0x00 byte that is
113560   ** not part of a multi-byte varint.
113561   */
113562   while( 0xFE & (*pEnd | c) ){
113563     c = *pEnd++ & 0x80;
113564     testcase( c!=0 && ((*pEnd)&0xfe)==0 );
113565   }
113566   if( pp ){
113567     int n = (int)(pEnd - *ppPoslist);
113568     char *p = *pp;
113569     memcpy(p, *ppPoslist, n);
113570     p += n;
113571     *pp = p;
113572   }
113573   *ppPoslist = pEnd;
113574 }
113575
113576 /*
113577 ** Value used to signify the end of an position-list. This is safe because
113578 ** it is not possible to have a document with 2^31 terms.
113579 */
113580 #define POSITION_LIST_END 0x7fffffff
113581
113582 /*
113583 ** This function is used to help parse position-lists. When this function is
113584 ** called, *pp may point to the start of the next varint in the position-list
113585 ** being parsed, or it may point to 1 byte past the end of the position-list
113586 ** (in which case **pp will be a terminator bytes POS_END (0) or
113587 ** (1)).
113588 **
113589 ** If *pp points past the end of the current position-list, set *pi to 
113590 ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
113591 ** increment the current value of *pi by the value read, and set *pp to
113592 ** point to the next value before returning.
113593 **
113594 ** Before calling this routine *pi must be initialized to the value of
113595 ** the previous position, or zero if we are reading the first position
113596 ** in the position-list.  Because positions are delta-encoded, the value
113597 ** of the previous position is needed in order to compute the value of
113598 ** the next position.
113599 */
113600 static void fts3ReadNextPos(
113601   char **pp,                    /* IN/OUT: Pointer into position-list buffer */
113602   sqlite3_int64 *pi             /* IN/OUT: Value read from position-list */
113603 ){
113604   if( (**pp)&0xFE ){
113605     fts3GetDeltaVarint(pp, pi);
113606     *pi -= 2;
113607   }else{
113608     *pi = POSITION_LIST_END;
113609   }
113610 }
113611
113612 /*
113613 ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
113614 ** the value of iCol encoded as a varint to *pp.   This will start a new
113615 ** column list.
113616 **
113617 ** Set *pp to point to the byte just after the last byte written before 
113618 ** returning (do not modify it if iCol==0). Return the total number of bytes
113619 ** written (0 if iCol==0).
113620 */
113621 static int fts3PutColNumber(char **pp, int iCol){
113622   int n = 0;                      /* Number of bytes written */
113623   if( iCol ){
113624     char *p = *pp;                /* Output pointer */
113625     n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
113626     *p = 0x01;
113627     *pp = &p[n];
113628   }
113629   return n;
113630 }
113631
113632 /*
113633 ** Compute the union of two position lists.  The output written
113634 ** into *pp contains all positions of both *pp1 and *pp2 in sorted
113635 ** order and with any duplicates removed.  All pointers are
113636 ** updated appropriately.   The caller is responsible for insuring
113637 ** that there is enough space in *pp to hold the complete output.
113638 */
113639 static void fts3PoslistMerge(
113640   char **pp,                      /* Output buffer */
113641   char **pp1,                     /* Left input list */
113642   char **pp2                      /* Right input list */
113643 ){
113644   char *p = *pp;
113645   char *p1 = *pp1;
113646   char *p2 = *pp2;
113647
113648   while( *p1 || *p2 ){
113649     int iCol1;         /* The current column index in pp1 */
113650     int iCol2;         /* The current column index in pp2 */
113651
113652     if( *p1==POS_COLUMN ) sqlite3Fts3GetVarint32(&p1[1], &iCol1);
113653     else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
113654     else iCol1 = 0;
113655
113656     if( *p2==POS_COLUMN ) sqlite3Fts3GetVarint32(&p2[1], &iCol2);
113657     else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
113658     else iCol2 = 0;
113659
113660     if( iCol1==iCol2 ){
113661       sqlite3_int64 i1 = 0;       /* Last position from pp1 */
113662       sqlite3_int64 i2 = 0;       /* Last position from pp2 */
113663       sqlite3_int64 iPrev = 0;
113664       int n = fts3PutColNumber(&p, iCol1);
113665       p1 += n;
113666       p2 += n;
113667
113668       /* At this point, both p1 and p2 point to the start of column-lists
113669       ** for the same column (the column with index iCol1 and iCol2).
113670       ** A column-list is a list of non-negative delta-encoded varints, each 
113671       ** incremented by 2 before being stored. Each list is terminated by a
113672       ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
113673       ** and writes the results to buffer p. p is left pointing to the byte
113674       ** after the list written. No terminator (POS_END or POS_COLUMN) is
113675       ** written to the output.
113676       */
113677       fts3GetDeltaVarint(&p1, &i1);
113678       fts3GetDeltaVarint(&p2, &i2);
113679       do {
113680         fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2); 
113681         iPrev -= 2;
113682         if( i1==i2 ){
113683           fts3ReadNextPos(&p1, &i1);
113684           fts3ReadNextPos(&p2, &i2);
113685         }else if( i1<i2 ){
113686           fts3ReadNextPos(&p1, &i1);
113687         }else{
113688           fts3ReadNextPos(&p2, &i2);
113689         }
113690       }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
113691     }else if( iCol1<iCol2 ){
113692       p1 += fts3PutColNumber(&p, iCol1);
113693       fts3ColumnlistCopy(&p, &p1);
113694     }else{
113695       p2 += fts3PutColNumber(&p, iCol2);
113696       fts3ColumnlistCopy(&p, &p2);
113697     }
113698   }
113699
113700   *p++ = POS_END;
113701   *pp = p;
113702   *pp1 = p1 + 1;
113703   *pp2 = p2 + 1;
113704 }
113705
113706 /*
113707 ** nToken==1 searches for adjacent positions.
113708 **
113709 ** This function is used to merge two position lists into one. When it is
113710 ** called, *pp1 and *pp2 must both point to position lists. A position-list is
113711 ** the part of a doclist that follows each document id. For example, if a row
113712 ** contains:
113713 **
113714 **     'a b c'|'x y z'|'a b b a'
113715 **
113716 ** Then the position list for this row for token 'b' would consist of:
113717 **
113718 **     0x02 0x01 0x02 0x03 0x03 0x00
113719 **
113720 ** When this function returns, both *pp1 and *pp2 are left pointing to the
113721 ** byte following the 0x00 terminator of their respective position lists.
113722 **
113723 ** If isSaveLeft is 0, an entry is added to the output position list for 
113724 ** each position in *pp2 for which there exists one or more positions in
113725 ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
113726 ** when the *pp1 token appears before the *pp2 token, but not more than nToken
113727 ** slots before it.
113728 */
113729 static int fts3PoslistPhraseMerge(
113730   char **pp,                      /* IN/OUT: Preallocated output buffer */
113731   int nToken,                     /* Maximum difference in token positions */
113732   int isSaveLeft,                 /* Save the left position */
113733   int isExact,                    /* If *pp1 is exactly nTokens before *pp2 */
113734   char **pp1,                     /* IN/OUT: Left input list */
113735   char **pp2                      /* IN/OUT: Right input list */
113736 ){
113737   char *p = (pp ? *pp : 0);
113738   char *p1 = *pp1;
113739   char *p2 = *pp2;
113740   int iCol1 = 0;
113741   int iCol2 = 0;
113742
113743   /* Never set both isSaveLeft and isExact for the same invocation. */
113744   assert( isSaveLeft==0 || isExact==0 );
113745
113746   assert( *p1!=0 && *p2!=0 );
113747   if( *p1==POS_COLUMN ){ 
113748     p1++;
113749     p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
113750   }
113751   if( *p2==POS_COLUMN ){ 
113752     p2++;
113753     p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
113754   }
113755
113756   while( 1 ){
113757     if( iCol1==iCol2 ){
113758       char *pSave = p;
113759       sqlite3_int64 iPrev = 0;
113760       sqlite3_int64 iPos1 = 0;
113761       sqlite3_int64 iPos2 = 0;
113762
113763       if( pp && iCol1 ){
113764         *p++ = POS_COLUMN;
113765         p += sqlite3Fts3PutVarint(p, iCol1);
113766       }
113767
113768       assert( *p1!=POS_END && *p1!=POS_COLUMN );
113769       assert( *p2!=POS_END && *p2!=POS_COLUMN );
113770       fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
113771       fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
113772
113773       while( 1 ){
113774         if( iPos2==iPos1+nToken 
113775          || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken) 
113776         ){
113777           sqlite3_int64 iSave;
113778           if( !pp ){
113779             fts3PoslistCopy(0, &p2);
113780             fts3PoslistCopy(0, &p1);
113781             *pp1 = p1;
113782             *pp2 = p2;
113783             return 1;
113784           }
113785           iSave = isSaveLeft ? iPos1 : iPos2;
113786           fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
113787           pSave = 0;
113788         }
113789         if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
113790           if( (*p2&0xFE)==0 ) break;
113791           fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
113792         }else{
113793           if( (*p1&0xFE)==0 ) break;
113794           fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
113795         }
113796       }
113797
113798       if( pSave ){
113799         assert( pp && p );
113800         p = pSave;
113801       }
113802
113803       fts3ColumnlistCopy(0, &p1);
113804       fts3ColumnlistCopy(0, &p2);
113805       assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
113806       if( 0==*p1 || 0==*p2 ) break;
113807
113808       p1++;
113809       p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
113810       p2++;
113811       p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
113812     }
113813
113814     /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
113815     ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
113816     ** end of the position list, or the 0x01 that precedes the next 
113817     ** column-number in the position list. 
113818     */
113819     else if( iCol1<iCol2 ){
113820       fts3ColumnlistCopy(0, &p1);
113821       if( 0==*p1 ) break;
113822       p1++;
113823       p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
113824     }else{
113825       fts3ColumnlistCopy(0, &p2);
113826       if( 0==*p2 ) break;
113827       p2++;
113828       p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
113829     }
113830   }
113831
113832   fts3PoslistCopy(0, &p2);
113833   fts3PoslistCopy(0, &p1);
113834   *pp1 = p1;
113835   *pp2 = p2;
113836   if( !pp || *pp==p ){
113837     return 0;
113838   }
113839   *p++ = 0x00;
113840   *pp = p;
113841   return 1;
113842 }
113843
113844 /*
113845 ** Merge two position-lists as required by the NEAR operator. The argument
113846 ** position lists correspond to the left and right phrases of an expression 
113847 ** like:
113848 **
113849 **     "phrase 1" NEAR "phrase number 2"
113850 **
113851 ** Position list *pp1 corresponds to the left-hand side of the NEAR 
113852 ** expression and *pp2 to the right. As usual, the indexes in the position 
113853 ** lists are the offsets of the last token in each phrase (tokens "1" and "2" 
113854 ** in the example above).
113855 **
113856 ** The output position list - written to *pp - is a copy of *pp2 with those
113857 ** entries that are not sufficiently NEAR entries in *pp1 removed.
113858 */
113859 static int fts3PoslistNearMerge(
113860   char **pp,                      /* Output buffer */
113861   char *aTmp,                     /* Temporary buffer space */
113862   int nRight,                     /* Maximum difference in token positions */
113863   int nLeft,                      /* Maximum difference in token positions */
113864   char **pp1,                     /* IN/OUT: Left input list */
113865   char **pp2                      /* IN/OUT: Right input list */
113866 ){
113867   char *p1 = *pp1;
113868   char *p2 = *pp2;
113869
113870   char *pTmp1 = aTmp;
113871   char *pTmp2;
113872   char *aTmp2;
113873   int res = 1;
113874
113875   fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
113876   aTmp2 = pTmp2 = pTmp1;
113877   *pp1 = p1;
113878   *pp2 = p2;
113879   fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
113880   if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
113881     fts3PoslistMerge(pp, &aTmp, &aTmp2);
113882   }else if( pTmp1!=aTmp ){
113883     fts3PoslistCopy(pp, &aTmp);
113884   }else if( pTmp2!=aTmp2 ){
113885     fts3PoslistCopy(pp, &aTmp2);
113886   }else{
113887     res = 0;
113888   }
113889
113890   return res;
113891 }
113892
113893 /* 
113894 ** A pointer to an instance of this structure is used as the context 
113895 ** argument to sqlite3Fts3SegReaderIterate()
113896 */
113897 typedef struct TermSelect TermSelect;
113898 struct TermSelect {
113899   int isReqPos;
113900   char *aaOutput[16];             /* Malloc'd output buffer */
113901   int anOutput[16];               /* Size of output in bytes */
113902 };
113903
113904
113905 static void fts3GetDeltaVarint3(
113906   char **pp, 
113907   char *pEnd, 
113908   int bDescIdx,
113909   sqlite3_int64 *pVal
113910 ){
113911   if( *pp>=pEnd ){
113912     *pp = 0;
113913   }else{
113914     sqlite3_int64 iVal;
113915     *pp += sqlite3Fts3GetVarint(*pp, &iVal);
113916     if( bDescIdx ){
113917       *pVal -= iVal;
113918     }else{
113919       *pVal += iVal;
113920     }
113921   }
113922 }
113923
113924 static void fts3PutDeltaVarint3(
113925   char **pp,                      /* IN/OUT: Output pointer */
113926   int bDescIdx,                   /* True for descending docids */
113927   sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
113928   int *pbFirst,                   /* IN/OUT: True after first int written */
113929   sqlite3_int64 iVal              /* Write this value to the list */
113930 ){
113931   sqlite3_int64 iWrite;
113932   if( bDescIdx==0 || *pbFirst==0 ){
113933     iWrite = iVal - *piPrev;
113934   }else{
113935     iWrite = *piPrev - iVal;
113936   }
113937   assert( *pbFirst || *piPrev==0 );
113938   assert( *pbFirst==0 || iWrite>0 );
113939   *pp += sqlite3Fts3PutVarint(*pp, iWrite);
113940   *piPrev = iVal;
113941   *pbFirst = 1;
113942 }
113943
113944 #define COMPARE_DOCID(i1, i2) ((bDescIdx?-1:1) * (i1-i2))
113945
113946 static int fts3DoclistOrMerge(
113947   int bDescIdx,                   /* True if arguments are desc */
113948   char *a1, int n1,               /* First doclist */
113949   char *a2, int n2,               /* Second doclist */
113950   char **paOut, int *pnOut        /* OUT: Malloc'd doclist */
113951 ){
113952   sqlite3_int64 i1 = 0;
113953   sqlite3_int64 i2 = 0;
113954   sqlite3_int64 iPrev = 0;
113955   char *pEnd1 = &a1[n1];
113956   char *pEnd2 = &a2[n2];
113957   char *p1 = a1;
113958   char *p2 = a2;
113959   char *p;
113960   char *aOut;
113961   int bFirstOut = 0;
113962
113963   *paOut = 0;
113964   *pnOut = 0;
113965   aOut = sqlite3_malloc(n1+n2);
113966   if( !aOut ) return SQLITE_NOMEM;
113967
113968   p = aOut;
113969   fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
113970   fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
113971   while( p1 || p2 ){
113972     sqlite3_int64 iDiff = COMPARE_DOCID(i1, i2);
113973
113974     if( p2 && p1 && iDiff==0 ){
113975       fts3PutDeltaVarint3(&p, bDescIdx, &iPrev, &bFirstOut, i1);
113976       fts3PoslistMerge(&p, &p1, &p2);
113977       fts3GetDeltaVarint3(&p1, pEnd1, bDescIdx, &i1);
113978       fts3GetDeltaVarint3(&p2, pEnd2, bDescIdx, &i2);
113979     }else if( !p2 || (p1 && iDiff<0) ){
113980       fts3PutDeltaVarint3(&p, bDescIdx, &iPrev, &bFirstOut, i1);
113981       fts3PoslistCopy(&p, &p1);
113982       fts3GetDeltaVarint3(&p1, pEnd1, bDescIdx, &i1);
113983     }else{
113984       fts3PutDeltaVarint3(&p, bDescIdx, &iPrev, &bFirstOut, i2);
113985       fts3PoslistCopy(&p, &p2);
113986       fts3GetDeltaVarint3(&p2, pEnd2, bDescIdx, &i2);
113987     }
113988   }
113989
113990   *paOut = aOut;
113991   *pnOut = (p-aOut);
113992   return SQLITE_OK;
113993 }
113994
113995 static void fts3DoclistPhraseMerge(
113996   int bDescIdx,                   /* True if arguments are desc */
113997   int nDist,                      /* Distance from left to right (1=adjacent) */
113998   char *aLeft, int nLeft,         /* Left doclist */
113999   char *aRight, int *pnRight      /* IN/OUT: Right/output doclist */
114000 ){
114001   sqlite3_int64 i1 = 0;
114002   sqlite3_int64 i2 = 0;
114003   sqlite3_int64 iPrev = 0;
114004   char *pEnd1 = &aLeft[nLeft];
114005   char *pEnd2 = &aRight[*pnRight];
114006   char *p1 = aLeft;
114007   char *p2 = aRight;
114008   char *p;
114009   int bFirstOut = 0;
114010   char *aOut = aRight;
114011
114012   assert( nDist>0 );
114013
114014   p = aOut;
114015   fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
114016   fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
114017
114018   while( p1 && p2 ){
114019     sqlite3_int64 iDiff = COMPARE_DOCID(i1, i2);
114020     if( iDiff==0 ){
114021       char *pSave = p;
114022       sqlite3_int64 iPrevSave = iPrev;
114023       int bFirstOutSave = bFirstOut;
114024
114025       fts3PutDeltaVarint3(&p, bDescIdx, &iPrev, &bFirstOut, i1);
114026       if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
114027         p = pSave;
114028         iPrev = iPrevSave;
114029         bFirstOut = bFirstOutSave;
114030       }
114031       fts3GetDeltaVarint3(&p1, pEnd1, bDescIdx, &i1);
114032       fts3GetDeltaVarint3(&p2, pEnd2, bDescIdx, &i2);
114033     }else if( iDiff<0 ){
114034       fts3PoslistCopy(0, &p1);
114035       fts3GetDeltaVarint3(&p1, pEnd1, bDescIdx, &i1);
114036     }else{
114037       fts3PoslistCopy(0, &p2);
114038       fts3GetDeltaVarint3(&p2, pEnd2, bDescIdx, &i2);
114039     }
114040   }
114041
114042   *pnRight = p - aOut;
114043 }
114044
114045
114046 /*
114047 ** Merge all doclists in the TermSelect.aaOutput[] array into a single
114048 ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
114049 ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
114050 **
114051 ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
114052 ** the responsibility of the caller to free any doclists left in the
114053 ** TermSelect.aaOutput[] array.
114054 */
114055 static int fts3TermSelectMerge(Fts3Table *p, TermSelect *pTS){
114056   char *aOut = 0;
114057   int nOut = 0;
114058   int i;
114059
114060   /* Loop through the doclists in the aaOutput[] array. Merge them all
114061   ** into a single doclist.
114062   */
114063   for(i=0; i<SizeofArray(pTS->aaOutput); i++){
114064     if( pTS->aaOutput[i] ){
114065       if( !aOut ){
114066         aOut = pTS->aaOutput[i];
114067         nOut = pTS->anOutput[i];
114068         pTS->aaOutput[i] = 0;
114069       }else{
114070         int nNew;
114071         char *aNew;
114072
114073         int rc = fts3DoclistOrMerge(p->bDescIdx, 
114074             pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
114075         );
114076         if( rc!=SQLITE_OK ){
114077           sqlite3_free(aOut);
114078           return rc;
114079         }
114080
114081         sqlite3_free(pTS->aaOutput[i]);
114082         sqlite3_free(aOut);
114083         pTS->aaOutput[i] = 0;
114084         aOut = aNew;
114085         nOut = nNew;
114086       }
114087     }
114088   }
114089
114090   pTS->aaOutput[0] = aOut;
114091   pTS->anOutput[0] = nOut;
114092   return SQLITE_OK;
114093 }
114094
114095 /*
114096 ** This function is used as the sqlite3Fts3SegReaderIterate() callback when
114097 ** querying the full-text index for a doclist associated with a term or
114098 ** term-prefix.
114099 */
114100 static int fts3TermSelectCb(
114101   Fts3Table *p,                   /* Virtual table object */
114102   void *pContext,                 /* Pointer to TermSelect structure */
114103   char *zTerm,
114104   int nTerm,
114105   char *aDoclist,
114106   int nDoclist
114107 ){
114108   TermSelect *pTS = (TermSelect *)pContext;
114109
114110   UNUSED_PARAMETER(p);
114111   UNUSED_PARAMETER(zTerm);
114112   UNUSED_PARAMETER(nTerm);
114113
114114   if( pTS->aaOutput[0]==0 ){
114115     /* If this is the first term selected, copy the doclist to the output
114116     ** buffer using memcpy(). */
114117     pTS->aaOutput[0] = sqlite3_malloc(nDoclist);
114118     pTS->anOutput[0] = nDoclist;
114119     if( pTS->aaOutput[0] ){
114120       memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
114121     }else{
114122       return SQLITE_NOMEM;
114123     }
114124   }else{
114125     char *aMerge = aDoclist;
114126     int nMerge = nDoclist;
114127     int iOut;
114128
114129     for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
114130       if( pTS->aaOutput[iOut]==0 ){
114131         assert( iOut>0 );
114132         pTS->aaOutput[iOut] = aMerge;
114133         pTS->anOutput[iOut] = nMerge;
114134         break;
114135       }else{
114136         char *aNew;
114137         int nNew;
114138
114139         int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge, 
114140             pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
114141         );
114142         if( rc!=SQLITE_OK ){
114143           if( aMerge!=aDoclist ) sqlite3_free(aMerge);
114144           return rc;
114145         }
114146
114147         if( aMerge!=aDoclist ) sqlite3_free(aMerge);
114148         sqlite3_free(pTS->aaOutput[iOut]);
114149         pTS->aaOutput[iOut] = 0;
114150   
114151         aMerge = aNew;
114152         nMerge = nNew;
114153         if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
114154           pTS->aaOutput[iOut] = aMerge;
114155           pTS->anOutput[iOut] = nMerge;
114156         }
114157       }
114158     }
114159   }
114160   return SQLITE_OK;
114161 }
114162
114163 /*
114164 ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
114165 */
114166 static int fts3SegReaderCursorAppend(
114167   Fts3MultiSegReader *pCsr, 
114168   Fts3SegReader *pNew
114169 ){
114170   if( (pCsr->nSegment%16)==0 ){
114171     Fts3SegReader **apNew;
114172     int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
114173     apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
114174     if( !apNew ){
114175       sqlite3Fts3SegReaderFree(pNew);
114176       return SQLITE_NOMEM;
114177     }
114178     pCsr->apSegment = apNew;
114179   }
114180   pCsr->apSegment[pCsr->nSegment++] = pNew;
114181   return SQLITE_OK;
114182 }
114183
114184 static int fts3SegReaderCursor(
114185   Fts3Table *p,                   /* FTS3 table handle */
114186   int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
114187   int iLevel,                     /* Level of segments to scan */
114188   const char *zTerm,              /* Term to query for */
114189   int nTerm,                      /* Size of zTerm in bytes */
114190   int isPrefix,                   /* True for a prefix search */
114191   int isScan,                     /* True to scan from zTerm to EOF */
114192   Fts3MultiSegReader *pCsr       /* Cursor object to populate */
114193 ){
114194   int rc = SQLITE_OK;
114195   int rc2;
114196   sqlite3_stmt *pStmt = 0;
114197
114198   /* If iLevel is less than 0 and this is not a scan, include a seg-reader 
114199   ** for the pending-terms. If this is a scan, then this call must be being
114200   ** made by an fts4aux module, not an FTS table. In this case calling
114201   ** Fts3SegReaderPending might segfault, as the data structures used by 
114202   ** fts4aux are not completely populated. So it's easiest to filter these
114203   ** calls out here.  */
114204   if( iLevel<0 && p->aIndex ){
114205     Fts3SegReader *pSeg = 0;
114206     rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix, &pSeg);
114207     if( rc==SQLITE_OK && pSeg ){
114208       rc = fts3SegReaderCursorAppend(pCsr, pSeg);
114209     }
114210   }
114211
114212   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
114213     if( rc==SQLITE_OK ){
114214       rc = sqlite3Fts3AllSegdirs(p, iIndex, iLevel, &pStmt);
114215     }
114216
114217     while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
114218       Fts3SegReader *pSeg = 0;
114219
114220       /* Read the values returned by the SELECT into local variables. */
114221       sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
114222       sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
114223       sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
114224       int nRoot = sqlite3_column_bytes(pStmt, 4);
114225       char const *zRoot = sqlite3_column_blob(pStmt, 4);
114226
114227       /* If zTerm is not NULL, and this segment is not stored entirely on its
114228       ** root node, the range of leaves scanned can be reduced. Do this. */
114229       if( iStartBlock && zTerm ){
114230         sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
114231         rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
114232         if( rc!=SQLITE_OK ) goto finished;
114233         if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
114234       }
114235  
114236       rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1, 
114237           iStartBlock, iLeavesEndBlock, iEndBlock, zRoot, nRoot, &pSeg
114238       );
114239       if( rc!=SQLITE_OK ) goto finished;
114240       rc = fts3SegReaderCursorAppend(pCsr, pSeg);
114241     }
114242   }
114243
114244  finished:
114245   rc2 = sqlite3_reset(pStmt);
114246   if( rc==SQLITE_DONE ) rc = rc2;
114247
114248   return rc;
114249 }
114250
114251 /*
114252 ** Set up a cursor object for iterating through a full-text index or a 
114253 ** single level therein.
114254 */
114255 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
114256   Fts3Table *p,                   /* FTS3 table handle */
114257   int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
114258   int iLevel,                     /* Level of segments to scan */
114259   const char *zTerm,              /* Term to query for */
114260   int nTerm,                      /* Size of zTerm in bytes */
114261   int isPrefix,                   /* True for a prefix search */
114262   int isScan,                     /* True to scan from zTerm to EOF */
114263   Fts3MultiSegReader *pCsr       /* Cursor object to populate */
114264 ){
114265   assert( iIndex>=0 && iIndex<p->nIndex );
114266   assert( iLevel==FTS3_SEGCURSOR_ALL
114267       ||  iLevel==FTS3_SEGCURSOR_PENDING 
114268       ||  iLevel>=0
114269   );
114270   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
114271   assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
114272   assert( isPrefix==0 || isScan==0 );
114273
114274   /* "isScan" is only set to true by the ft4aux module, an ordinary
114275   ** full-text tables. */
114276   assert( isScan==0 || p->aIndex==0 );
114277
114278   memset(pCsr, 0, sizeof(Fts3MultiSegReader));
114279
114280   return fts3SegReaderCursor(
114281       p, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
114282   );
114283 }
114284
114285 static int fts3SegReaderCursorAddZero(
114286   Fts3Table *p,
114287   const char *zTerm,
114288   int nTerm,
114289   Fts3MultiSegReader *pCsr
114290 ){
114291   return fts3SegReaderCursor(p, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr);
114292 }
114293
114294
114295 SQLITE_PRIVATE int sqlite3Fts3TermSegReaderCursor(
114296   Fts3Cursor *pCsr,               /* Virtual table cursor handle */
114297   const char *zTerm,              /* Term to query for */
114298   int nTerm,                      /* Size of zTerm in bytes */
114299   int isPrefix,                   /* True for a prefix search */
114300   Fts3MultiSegReader **ppSegcsr   /* OUT: Allocated seg-reader cursor */
114301 ){
114302   Fts3MultiSegReader *pSegcsr;   /* Object to allocate and return */
114303   int rc = SQLITE_NOMEM;          /* Return code */
114304
114305   pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
114306   if( pSegcsr ){
114307     int i;
114308     int bFound = 0;               /* True once an index has been found */
114309     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
114310
114311     if( isPrefix ){
114312       for(i=1; bFound==0 && i<p->nIndex; i++){
114313         if( p->aIndex[i].nPrefix==nTerm ){
114314           bFound = 1;
114315           rc = sqlite3Fts3SegReaderCursor(
114316               p, i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr);
114317           pSegcsr->bLookup = 1;
114318         }
114319       }
114320
114321       for(i=1; bFound==0 && i<p->nIndex; i++){
114322         if( p->aIndex[i].nPrefix==nTerm+1 ){
114323           bFound = 1;
114324           rc = sqlite3Fts3SegReaderCursor(
114325               p, i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
114326           );
114327           if( rc==SQLITE_OK ){
114328             rc = fts3SegReaderCursorAddZero(p, zTerm, nTerm, pSegcsr);
114329           }
114330         }
114331       }
114332     }
114333
114334     if( bFound==0 ){
114335       rc = sqlite3Fts3SegReaderCursor(
114336           p, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
114337       );
114338       pSegcsr->bLookup = !isPrefix;
114339     }
114340   }
114341
114342   *ppSegcsr = pSegcsr;
114343   return rc;
114344 }
114345
114346 static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
114347   sqlite3Fts3SegReaderFinish(pSegcsr);
114348   sqlite3_free(pSegcsr);
114349 }
114350
114351 /*
114352 ** This function retreives the doclist for the specified term (or term
114353 ** prefix) from the database. 
114354 **
114355 ** The returned doclist may be in one of two formats, depending on the 
114356 ** value of parameter isReqPos. If isReqPos is zero, then the doclist is
114357 ** a sorted list of delta-compressed docids (a bare doclist). If isReqPos
114358 ** is non-zero, then the returned list is in the same format as is stored 
114359 ** in the database without the found length specifier at the start of on-disk
114360 ** doclists.
114361 */
114362 static int fts3TermSelect(
114363   Fts3Table *p,                   /* Virtual table handle */
114364   Fts3PhraseToken *pTok,          /* Token to query for */
114365   int iColumn,                    /* Column to query (or -ve for all columns) */
114366   int isReqPos,                   /* True to include position lists in output */
114367   int *pnOut,                     /* OUT: Size of buffer at *ppOut */
114368   char **ppOut                    /* OUT: Malloced result buffer */
114369 ){
114370   int rc;                         /* Return code */
114371   Fts3MultiSegReader *pSegcsr;   /* Seg-reader cursor for this term */
114372   TermSelect tsc;                 /* Context object for fts3TermSelectCb() */
114373   Fts3SegFilter filter;           /* Segment term filter configuration */
114374
114375   pSegcsr = pTok->pSegcsr;
114376   memset(&tsc, 0, sizeof(TermSelect));
114377   tsc.isReqPos = isReqPos;
114378
114379   filter.flags = FTS3_SEGMENT_IGNORE_EMPTY 
114380         | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
114381         | (isReqPos ? FTS3_SEGMENT_REQUIRE_POS : 0)
114382         | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
114383   filter.iCol = iColumn;
114384   filter.zTerm = pTok->z;
114385   filter.nTerm = pTok->n;
114386
114387   rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
114388   while( SQLITE_OK==rc
114389       && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr)) 
114390   ){
114391     rc = fts3TermSelectCb(p, (void *)&tsc, 
114392         pSegcsr->zTerm, pSegcsr->nTerm, pSegcsr->aDoclist, pSegcsr->nDoclist
114393     );
114394   }
114395
114396   if( rc==SQLITE_OK ){
114397     rc = fts3TermSelectMerge(p, &tsc);
114398   }
114399   if( rc==SQLITE_OK ){
114400     *ppOut = tsc.aaOutput[0];
114401     *pnOut = tsc.anOutput[0];
114402   }else{
114403     int i;
114404     for(i=0; i<SizeofArray(tsc.aaOutput); i++){
114405       sqlite3_free(tsc.aaOutput[i]);
114406     }
114407   }
114408
114409   fts3SegReaderCursorFree(pSegcsr);
114410   pTok->pSegcsr = 0;
114411   return rc;
114412 }
114413
114414 /*
114415 ** This function counts the total number of docids in the doclist stored
114416 ** in buffer aList[], size nList bytes.
114417 **
114418 ** If the isPoslist argument is true, then it is assumed that the doclist
114419 ** contains a position-list following each docid. Otherwise, it is assumed
114420 ** that the doclist is simply a list of docids stored as delta encoded 
114421 ** varints.
114422 */
114423 static int fts3DoclistCountDocids(int isPoslist, char *aList, int nList){
114424   int nDoc = 0;                   /* Return value */
114425   if( aList ){
114426     char *aEnd = &aList[nList];   /* Pointer to one byte after EOF */
114427     char *p = aList;              /* Cursor */
114428     if( !isPoslist ){
114429       /* The number of docids in the list is the same as the number of 
114430       ** varints. In FTS3 a varint consists of a single byte with the 0x80 
114431       ** bit cleared and zero or more bytes with the 0x80 bit set. So to
114432       ** count the varints in the buffer, just count the number of bytes
114433       ** with the 0x80 bit clear.  */
114434       while( p<aEnd ) nDoc += (((*p++)&0x80)==0);
114435     }else{
114436       while( p<aEnd ){
114437         nDoc++;
114438         while( (*p++)&0x80 );     /* Skip docid varint */
114439         fts3PoslistCopy(0, &p);   /* Skip over position list */
114440       }
114441     }
114442   }
114443
114444   return nDoc;
114445 }
114446
114447 /*
114448 ** Advance the cursor to the next row in the %_content table that
114449 ** matches the search criteria.  For a MATCH search, this will be
114450 ** the next row that matches. For a full-table scan, this will be
114451 ** simply the next row in the %_content table.  For a docid lookup,
114452 ** this routine simply sets the EOF flag.
114453 **
114454 ** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
114455 ** even if we reach end-of-file.  The fts3EofMethod() will be called
114456 ** subsequently to determine whether or not an EOF was hit.
114457 */
114458 static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
114459   int rc;
114460   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
114461   if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
114462     if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
114463       pCsr->isEof = 1;
114464       rc = sqlite3_reset(pCsr->pStmt);
114465     }else{
114466       pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
114467       rc = SQLITE_OK;
114468     }
114469   }else{
114470     rc = sqlite3Fts3EvalNext((Fts3Cursor *)pCursor);
114471   }
114472   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
114473   return rc;
114474 }
114475
114476 /*
114477 ** This is the xFilter interface for the virtual table.  See
114478 ** the virtual table xFilter method documentation for additional
114479 ** information.
114480 **
114481 ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
114482 ** the %_content table.
114483 **
114484 ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
114485 ** in the %_content table.
114486 **
114487 ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
114488 ** column on the left-hand side of the MATCH operator is column
114489 ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
114490 ** side of the MATCH operator.
114491 */
114492 static int fts3FilterMethod(
114493   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
114494   int idxNum,                     /* Strategy index */
114495   const char *idxStr,             /* Unused */
114496   int nVal,                       /* Number of elements in apVal */
114497   sqlite3_value **apVal           /* Arguments for the indexing scheme */
114498 ){
114499   int rc;
114500   char *zSql;                     /* SQL statement used to access %_content */
114501   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
114502   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
114503
114504   UNUSED_PARAMETER(idxStr);
114505   UNUSED_PARAMETER(nVal);
114506
114507   assert( idxNum>=0 && idxNum<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
114508   assert( nVal==0 || nVal==1 );
114509   assert( (nVal==0)==(idxNum==FTS3_FULLSCAN_SEARCH) );
114510   assert( p->pSegments==0 );
114511
114512   /* In case the cursor has been used before, clear it now. */
114513   sqlite3_finalize(pCsr->pStmt);
114514   sqlite3_free(pCsr->aDoclist);
114515   sqlite3Fts3ExprFree(pCsr->pExpr);
114516   memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
114517
114518   if( idxStr ){
114519     pCsr->bDesc = (idxStr[0]=='D');
114520   }else{
114521     pCsr->bDesc = p->bDescIdx;
114522   }
114523   pCsr->eSearch = (i16)idxNum;
114524
114525   if( idxNum!=FTS3_DOCID_SEARCH && idxNum!=FTS3_FULLSCAN_SEARCH ){
114526     int iCol = idxNum-FTS3_FULLTEXT_SEARCH;
114527     const char *zQuery = (const char *)sqlite3_value_text(apVal[0]);
114528
114529     if( zQuery==0 && sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
114530       return SQLITE_NOMEM;
114531     }
114532
114533     rc = sqlite3Fts3ExprParse(p->pTokenizer, p->azColumn, p->nColumn, 
114534         iCol, zQuery, -1, &pCsr->pExpr
114535     );
114536     if( rc!=SQLITE_OK ){
114537       if( rc==SQLITE_ERROR ){
114538         static const char *zErr = "malformed MATCH expression: [%s]";
114539         p->base.zErrMsg = sqlite3_mprintf(zErr, zQuery);
114540       }
114541       return rc;
114542     }
114543
114544     rc = sqlite3Fts3ReadLock(p);
114545     if( rc!=SQLITE_OK ) return rc;
114546
114547     rc = sqlite3Fts3EvalStart(pCsr, pCsr->pExpr, 1);
114548
114549     sqlite3Fts3SegmentsClose(p);
114550     if( rc!=SQLITE_OK ) return rc;
114551     pCsr->pNextId = pCsr->aDoclist;
114552     pCsr->iPrevId = 0;
114553   }
114554
114555   /* Compile a SELECT statement for this cursor. For a full-table-scan, the
114556   ** statement loops through all rows of the %_content table. For a
114557   ** full-text query or docid lookup, the statement retrieves a single
114558   ** row by docid.
114559   */
114560   if( idxNum==FTS3_FULLSCAN_SEARCH ){
114561     const char *zSort = (pCsr->bDesc ? "DESC" : "ASC");
114562     const char *zTmpl = "SELECT %s FROM %Q.'%q_content' AS x ORDER BY docid %s";
114563     zSql = sqlite3_mprintf(zTmpl, p->zReadExprlist, p->zDb, p->zName, zSort);
114564   }else{
114565     const char *zTmpl = "SELECT %s FROM %Q.'%q_content' AS x WHERE docid = ?";
114566     zSql = sqlite3_mprintf(zTmpl, p->zReadExprlist, p->zDb, p->zName);
114567   }
114568   if( !zSql ) return SQLITE_NOMEM;
114569   rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
114570   sqlite3_free(zSql);
114571   if( rc!=SQLITE_OK ) return rc;
114572
114573   if( idxNum==FTS3_DOCID_SEARCH ){
114574     rc = sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
114575     if( rc!=SQLITE_OK ) return rc;
114576   }
114577
114578   return fts3NextMethod(pCursor);
114579 }
114580
114581 /* 
114582 ** This is the xEof method of the virtual table. SQLite calls this 
114583 ** routine to find out if it has reached the end of a result set.
114584 */
114585 static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
114586   return ((Fts3Cursor *)pCursor)->isEof;
114587 }
114588
114589 /* 
114590 ** This is the xRowid method. The SQLite core calls this routine to
114591 ** retrieve the rowid for the current row of the result set. fts3
114592 ** exposes %_content.docid as the rowid for the virtual table. The
114593 ** rowid should be written to *pRowid.
114594 */
114595 static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
114596   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
114597   *pRowid = pCsr->iPrevId;
114598   return SQLITE_OK;
114599 }
114600
114601 /* 
114602 ** This is the xColumn method, called by SQLite to request a value from
114603 ** the row that the supplied cursor currently points to.
114604 */
114605 static int fts3ColumnMethod(
114606   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
114607   sqlite3_context *pContext,      /* Context for sqlite3_result_xxx() calls */
114608   int iCol                        /* Index of column to read value from */
114609 ){
114610   int rc = SQLITE_OK;             /* Return Code */
114611   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
114612   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
114613
114614   /* The column value supplied by SQLite must be in range. */
114615   assert( iCol>=0 && iCol<=p->nColumn+1 );
114616
114617   if( iCol==p->nColumn+1 ){
114618     /* This call is a request for the "docid" column. Since "docid" is an 
114619     ** alias for "rowid", use the xRowid() method to obtain the value.
114620     */
114621     sqlite3_result_int64(pContext, pCsr->iPrevId);
114622   }else if( iCol==p->nColumn ){
114623     /* The extra column whose name is the same as the table.
114624     ** Return a blob which is a pointer to the cursor.
114625     */
114626     sqlite3_result_blob(pContext, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
114627   }else{
114628     rc = fts3CursorSeek(0, pCsr);
114629     if( rc==SQLITE_OK ){
114630       sqlite3_result_value(pContext, sqlite3_column_value(pCsr->pStmt, iCol+1));
114631     }
114632   }
114633
114634   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
114635   return rc;
114636 }
114637
114638 /* 
114639 ** This function is the implementation of the xUpdate callback used by 
114640 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
114641 ** inserted, updated or deleted.
114642 */
114643 static int fts3UpdateMethod(
114644   sqlite3_vtab *pVtab,            /* Virtual table handle */
114645   int nArg,                       /* Size of argument array */
114646   sqlite3_value **apVal,          /* Array of arguments */
114647   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
114648 ){
114649   return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
114650 }
114651
114652 /*
114653 ** Implementation of xSync() method. Flush the contents of the pending-terms
114654 ** hash-table to the database.
114655 */
114656 static int fts3SyncMethod(sqlite3_vtab *pVtab){
114657   int rc = sqlite3Fts3PendingTermsFlush((Fts3Table *)pVtab);
114658   sqlite3Fts3SegmentsClose((Fts3Table *)pVtab);
114659   return rc;
114660 }
114661
114662 /*
114663 ** Implementation of xBegin() method. This is a no-op.
114664 */
114665 static int fts3BeginMethod(sqlite3_vtab *pVtab){
114666   TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
114667   UNUSED_PARAMETER(pVtab);
114668   assert( p->pSegments==0 );
114669   assert( p->nPendingData==0 );
114670   assert( p->inTransaction!=1 );
114671   TESTONLY( p->inTransaction = 1 );
114672   TESTONLY( p->mxSavepoint = -1; );
114673   return SQLITE_OK;
114674 }
114675
114676 /*
114677 ** Implementation of xCommit() method. This is a no-op. The contents of
114678 ** the pending-terms hash-table have already been flushed into the database
114679 ** by fts3SyncMethod().
114680 */
114681 static int fts3CommitMethod(sqlite3_vtab *pVtab){
114682   TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
114683   UNUSED_PARAMETER(pVtab);
114684   assert( p->nPendingData==0 );
114685   assert( p->inTransaction!=0 );
114686   assert( p->pSegments==0 );
114687   TESTONLY( p->inTransaction = 0 );
114688   TESTONLY( p->mxSavepoint = -1; );
114689   return SQLITE_OK;
114690 }
114691
114692 /*
114693 ** Implementation of xRollback(). Discard the contents of the pending-terms
114694 ** hash-table. Any changes made to the database are reverted by SQLite.
114695 */
114696 static int fts3RollbackMethod(sqlite3_vtab *pVtab){
114697   Fts3Table *p = (Fts3Table*)pVtab;
114698   sqlite3Fts3PendingTermsClear(p);
114699   assert( p->inTransaction!=0 );
114700   TESTONLY( p->inTransaction = 0 );
114701   TESTONLY( p->mxSavepoint = -1; );
114702   return SQLITE_OK;
114703 }
114704
114705 /*
114706 ** When called, *ppPoslist must point to the byte immediately following the
114707 ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
114708 ** moves *ppPoslist so that it instead points to the first byte of the
114709 ** same position list.
114710 */
114711 static void fts3ReversePoslist(char *pStart, char **ppPoslist){
114712   char *p = &(*ppPoslist)[-2];
114713   char c;
114714
114715   while( p>pStart && (c=*p--)==0 );
114716   while( p>pStart && (*p & 0x80) | c ){ 
114717     c = *p--; 
114718   }
114719   if( p>pStart ){ p = &p[2]; }
114720   while( *p++&0x80 );
114721   *ppPoslist = p;
114722 }
114723
114724 /*
114725 ** Helper function used by the implementation of the overloaded snippet(),
114726 ** offsets() and optimize() SQL functions.
114727 **
114728 ** If the value passed as the third argument is a blob of size
114729 ** sizeof(Fts3Cursor*), then the blob contents are copied to the 
114730 ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
114731 ** message is written to context pContext and SQLITE_ERROR returned. The
114732 ** string passed via zFunc is used as part of the error message.
114733 */
114734 static int fts3FunctionArg(
114735   sqlite3_context *pContext,      /* SQL function call context */
114736   const char *zFunc,              /* Function name */
114737   sqlite3_value *pVal,            /* argv[0] passed to function */
114738   Fts3Cursor **ppCsr              /* OUT: Store cursor handle here */
114739 ){
114740   Fts3Cursor *pRet;
114741   if( sqlite3_value_type(pVal)!=SQLITE_BLOB 
114742    || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
114743   ){
114744     char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
114745     sqlite3_result_error(pContext, zErr, -1);
114746     sqlite3_free(zErr);
114747     return SQLITE_ERROR;
114748   }
114749   memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
114750   *ppCsr = pRet;
114751   return SQLITE_OK;
114752 }
114753
114754 /*
114755 ** Implementation of the snippet() function for FTS3
114756 */
114757 static void fts3SnippetFunc(
114758   sqlite3_context *pContext,      /* SQLite function call context */
114759   int nVal,                       /* Size of apVal[] array */
114760   sqlite3_value **apVal           /* Array of arguments */
114761 ){
114762   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
114763   const char *zStart = "<b>";
114764   const char *zEnd = "</b>";
114765   const char *zEllipsis = "<b>...</b>";
114766   int iCol = -1;
114767   int nToken = 15;                /* Default number of tokens in snippet */
114768
114769   /* There must be at least one argument passed to this function (otherwise
114770   ** the non-overloaded version would have been called instead of this one).
114771   */
114772   assert( nVal>=1 );
114773
114774   if( nVal>6 ){
114775     sqlite3_result_error(pContext, 
114776         "wrong number of arguments to function snippet()", -1);
114777     return;
114778   }
114779   if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
114780
114781   switch( nVal ){
114782     case 6: nToken = sqlite3_value_int(apVal[5]);
114783     case 5: iCol = sqlite3_value_int(apVal[4]);
114784     case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
114785     case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
114786     case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
114787   }
114788   if( !zEllipsis || !zEnd || !zStart ){
114789     sqlite3_result_error_nomem(pContext);
114790   }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
114791     sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
114792   }
114793 }
114794
114795 /*
114796 ** Implementation of the offsets() function for FTS3
114797 */
114798 static void fts3OffsetsFunc(
114799   sqlite3_context *pContext,      /* SQLite function call context */
114800   int nVal,                       /* Size of argument array */
114801   sqlite3_value **apVal           /* Array of arguments */
114802 ){
114803   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
114804
114805   UNUSED_PARAMETER(nVal);
114806
114807   assert( nVal==1 );
114808   if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
114809   assert( pCsr );
114810   if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
114811     sqlite3Fts3Offsets(pContext, pCsr);
114812   }
114813 }
114814
114815 /* 
114816 ** Implementation of the special optimize() function for FTS3. This 
114817 ** function merges all segments in the database to a single segment.
114818 ** Example usage is:
114819 **
114820 **   SELECT optimize(t) FROM t LIMIT 1;
114821 **
114822 ** where 't' is the name of an FTS3 table.
114823 */
114824 static void fts3OptimizeFunc(
114825   sqlite3_context *pContext,      /* SQLite function call context */
114826   int nVal,                       /* Size of argument array */
114827   sqlite3_value **apVal           /* Array of arguments */
114828 ){
114829   int rc;                         /* Return code */
114830   Fts3Table *p;                   /* Virtual table handle */
114831   Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
114832
114833   UNUSED_PARAMETER(nVal);
114834
114835   assert( nVal==1 );
114836   if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
114837   p = (Fts3Table *)pCursor->base.pVtab;
114838   assert( p );
114839
114840   rc = sqlite3Fts3Optimize(p);
114841
114842   switch( rc ){
114843     case SQLITE_OK:
114844       sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
114845       break;
114846     case SQLITE_DONE:
114847       sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
114848       break;
114849     default:
114850       sqlite3_result_error_code(pContext, rc);
114851       break;
114852   }
114853 }
114854
114855 /*
114856 ** Implementation of the matchinfo() function for FTS3
114857 */
114858 static void fts3MatchinfoFunc(
114859   sqlite3_context *pContext,      /* SQLite function call context */
114860   int nVal,                       /* Size of argument array */
114861   sqlite3_value **apVal           /* Array of arguments */
114862 ){
114863   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
114864   assert( nVal==1 || nVal==2 );
114865   if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
114866     const char *zArg = 0;
114867     if( nVal>1 ){
114868       zArg = (const char *)sqlite3_value_text(apVal[1]);
114869     }
114870     sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
114871   }
114872 }
114873
114874 /*
114875 ** This routine implements the xFindFunction method for the FTS3
114876 ** virtual table.
114877 */
114878 static int fts3FindFunctionMethod(
114879   sqlite3_vtab *pVtab,            /* Virtual table handle */
114880   int nArg,                       /* Number of SQL function arguments */
114881   const char *zName,              /* Name of SQL function */
114882   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
114883   void **ppArg                    /* Unused */
114884 ){
114885   struct Overloaded {
114886     const char *zName;
114887     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
114888   } aOverload[] = {
114889     { "snippet", fts3SnippetFunc },
114890     { "offsets", fts3OffsetsFunc },
114891     { "optimize", fts3OptimizeFunc },
114892     { "matchinfo", fts3MatchinfoFunc },
114893   };
114894   int i;                          /* Iterator variable */
114895
114896   UNUSED_PARAMETER(pVtab);
114897   UNUSED_PARAMETER(nArg);
114898   UNUSED_PARAMETER(ppArg);
114899
114900   for(i=0; i<SizeofArray(aOverload); i++){
114901     if( strcmp(zName, aOverload[i].zName)==0 ){
114902       *pxFunc = aOverload[i].xFunc;
114903       return 1;
114904     }
114905   }
114906
114907   /* No function of the specified name was found. Return 0. */
114908   return 0;
114909 }
114910
114911 /*
114912 ** Implementation of FTS3 xRename method. Rename an fts3 table.
114913 */
114914 static int fts3RenameMethod(
114915   sqlite3_vtab *pVtab,            /* Virtual table handle */
114916   const char *zName               /* New name of table */
114917 ){
114918   Fts3Table *p = (Fts3Table *)pVtab;
114919   sqlite3 *db = p->db;            /* Database connection */
114920   int rc;                         /* Return Code */
114921
114922   rc = sqlite3Fts3PendingTermsFlush(p);
114923   if( rc!=SQLITE_OK ){
114924     return rc;
114925   }
114926
114927   fts3DbExec(&rc, db,
114928     "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';",
114929     p->zDb, p->zName, zName
114930   );
114931   if( p->bHasDocsize ){
114932     fts3DbExec(&rc, db,
114933       "ALTER TABLE %Q.'%q_docsize'  RENAME TO '%q_docsize';",
114934       p->zDb, p->zName, zName
114935     );
114936   }
114937   if( p->bHasStat ){
114938     fts3DbExec(&rc, db,
114939       "ALTER TABLE %Q.'%q_stat'  RENAME TO '%q_stat';",
114940       p->zDb, p->zName, zName
114941     );
114942   }
114943   fts3DbExec(&rc, db,
114944     "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
114945     p->zDb, p->zName, zName
114946   );
114947   fts3DbExec(&rc, db,
114948     "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';",
114949     p->zDb, p->zName, zName
114950   );
114951   return rc;
114952 }
114953
114954 static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
114955   UNUSED_PARAMETER(iSavepoint);
114956   assert( ((Fts3Table *)pVtab)->inTransaction );
114957   assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
114958   TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
114959   return fts3SyncMethod(pVtab);
114960 }
114961 static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
114962   TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
114963   UNUSED_PARAMETER(iSavepoint);
114964   UNUSED_PARAMETER(pVtab);
114965   assert( p->inTransaction );
114966   assert( p->mxSavepoint >= iSavepoint );
114967   TESTONLY( p->mxSavepoint = iSavepoint-1 );
114968   return SQLITE_OK;
114969 }
114970 static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
114971   Fts3Table *p = (Fts3Table*)pVtab;
114972   UNUSED_PARAMETER(iSavepoint);
114973   assert( p->inTransaction );
114974   assert( p->mxSavepoint >= iSavepoint );
114975   TESTONLY( p->mxSavepoint = iSavepoint );
114976   sqlite3Fts3PendingTermsClear(p);
114977   return SQLITE_OK;
114978 }
114979
114980 static const sqlite3_module fts3Module = {
114981   /* iVersion      */ 2,
114982   /* xCreate       */ fts3CreateMethod,
114983   /* xConnect      */ fts3ConnectMethod,
114984   /* xBestIndex    */ fts3BestIndexMethod,
114985   /* xDisconnect   */ fts3DisconnectMethod,
114986   /* xDestroy      */ fts3DestroyMethod,
114987   /* xOpen         */ fts3OpenMethod,
114988   /* xClose        */ fts3CloseMethod,
114989   /* xFilter       */ fts3FilterMethod,
114990   /* xNext         */ fts3NextMethod,
114991   /* xEof          */ fts3EofMethod,
114992   /* xColumn       */ fts3ColumnMethod,
114993   /* xRowid        */ fts3RowidMethod,
114994   /* xUpdate       */ fts3UpdateMethod,
114995   /* xBegin        */ fts3BeginMethod,
114996   /* xSync         */ fts3SyncMethod,
114997   /* xCommit       */ fts3CommitMethod,
114998   /* xRollback     */ fts3RollbackMethod,
114999   /* xFindFunction */ fts3FindFunctionMethod,
115000   /* xRename */       fts3RenameMethod,
115001   /* xSavepoint    */ fts3SavepointMethod,
115002   /* xRelease      */ fts3ReleaseMethod,
115003   /* xRollbackTo   */ fts3RollbackToMethod,
115004 };
115005
115006 /*
115007 ** This function is registered as the module destructor (called when an
115008 ** FTS3 enabled database connection is closed). It frees the memory
115009 ** allocated for the tokenizer hash table.
115010 */
115011 static void hashDestroy(void *p){
115012   Fts3Hash *pHash = (Fts3Hash *)p;
115013   sqlite3Fts3HashClear(pHash);
115014   sqlite3_free(pHash);
115015 }
115016
115017 /*
115018 ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are 
115019 ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
115020 ** respectively. The following three forward declarations are for functions
115021 ** declared in these files used to retrieve the respective implementations.
115022 **
115023 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
115024 ** to by the argument to point to the "simple" tokenizer implementation.
115025 ** And so on.
115026 */
115027 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
115028 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
115029 #ifdef SQLITE_ENABLE_ICU
115030 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
115031 #endif
115032
115033 /*
115034 ** Initialise the fts3 extension. If this extension is built as part
115035 ** of the sqlite library, then this function is called directly by
115036 ** SQLite. If fts3 is built as a dynamically loadable extension, this
115037 ** function is called by the sqlite3_extension_init() entry point.
115038 */
115039 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
115040   int rc = SQLITE_OK;
115041   Fts3Hash *pHash = 0;
115042   const sqlite3_tokenizer_module *pSimple = 0;
115043   const sqlite3_tokenizer_module *pPorter = 0;
115044
115045 #ifdef SQLITE_ENABLE_ICU
115046   const sqlite3_tokenizer_module *pIcu = 0;
115047   sqlite3Fts3IcuTokenizerModule(&pIcu);
115048 #endif
115049
115050 #ifdef SQLITE_TEST
115051   rc = sqlite3Fts3InitTerm(db);
115052   if( rc!=SQLITE_OK ) return rc;
115053 #endif
115054
115055   rc = sqlite3Fts3InitAux(db);
115056   if( rc!=SQLITE_OK ) return rc;
115057
115058   sqlite3Fts3SimpleTokenizerModule(&pSimple);
115059   sqlite3Fts3PorterTokenizerModule(&pPorter);
115060
115061   /* Allocate and initialise the hash-table used to store tokenizers. */
115062   pHash = sqlite3_malloc(sizeof(Fts3Hash));
115063   if( !pHash ){
115064     rc = SQLITE_NOMEM;
115065   }else{
115066     sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
115067   }
115068
115069   /* Load the built-in tokenizers into the hash table */
115070   if( rc==SQLITE_OK ){
115071     if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
115072      || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter) 
115073 #ifdef SQLITE_ENABLE_ICU
115074      || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
115075 #endif
115076     ){
115077       rc = SQLITE_NOMEM;
115078     }
115079   }
115080
115081 #ifdef SQLITE_TEST
115082   if( rc==SQLITE_OK ){
115083     rc = sqlite3Fts3ExprInitTestInterface(db);
115084   }
115085 #endif
115086
115087   /* Create the virtual table wrapper around the hash-table and overload 
115088   ** the two scalar functions. If this is successful, register the
115089   ** module with sqlite.
115090   */
115091   if( SQLITE_OK==rc 
115092    && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
115093    && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
115094    && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
115095    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
115096    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
115097    && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
115098   ){
115099     rc = sqlite3_create_module_v2(
115100         db, "fts3", &fts3Module, (void *)pHash, hashDestroy
115101     );
115102     if( rc==SQLITE_OK ){
115103       rc = sqlite3_create_module_v2(
115104           db, "fts4", &fts3Module, (void *)pHash, 0
115105       );
115106     }
115107     return rc;
115108   }
115109
115110   /* An error has occurred. Delete the hash table and return the error code. */
115111   assert( rc!=SQLITE_OK );
115112   if( pHash ){
115113     sqlite3Fts3HashClear(pHash);
115114     sqlite3_free(pHash);
115115   }
115116   return rc;
115117 }
115118
115119 #if !SQLITE_CORE
115120 SQLITE_API int sqlite3_extension_init(
115121   sqlite3 *db, 
115122   char **pzErrMsg,
115123   const sqlite3_api_routines *pApi
115124 ){
115125   SQLITE_EXTENSION_INIT2(pApi)
115126   return sqlite3Fts3Init(db);
115127 }
115128 #endif
115129
115130
115131 /*
115132 ** Allocate an Fts3MultiSegReader for each token in the expression headed
115133 ** by pExpr. 
115134 **
115135 ** An Fts3SegReader object is a cursor that can seek or scan a range of
115136 ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
115137 ** Fts3SegReader objects internally to provide an interface to seek or scan
115138 ** within the union of all segments of a b-tree. Hence the name.
115139 **
115140 ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
115141 ** segment b-tree (if the term is not a prefix or it is a prefix for which
115142 ** there exists prefix b-tree of the right length) then it may be traversed
115143 ** and merged incrementally. Otherwise, it has to be merged into an in-memory 
115144 ** doclist and then traversed.
115145 */
115146 static void fts3EvalAllocateReaders(
115147   Fts3Cursor *pCsr, 
115148   Fts3Expr *pExpr, 
115149   int *pnToken,                   /* OUT: Total number of tokens in phrase. */
115150   int *pnOr,                      /* OUT: Total number of OR nodes in expr. */
115151   int *pRc
115152 ){
115153   if( pExpr && SQLITE_OK==*pRc ){
115154     if( pExpr->eType==FTSQUERY_PHRASE ){
115155       int i;
115156       int nToken = pExpr->pPhrase->nToken;
115157       *pnToken += nToken;
115158       for(i=0; i<nToken; i++){
115159         Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
115160         int rc = sqlite3Fts3TermSegReaderCursor(pCsr, 
115161             pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
115162         );
115163         if( rc!=SQLITE_OK ){
115164           *pRc = rc;
115165           return;
115166         }
115167       }
115168       assert( pExpr->pPhrase->iDoclistToken==0 );
115169       pExpr->pPhrase->iDoclistToken = -1;
115170     }else{
115171       *pnOr += (pExpr->eType==FTSQUERY_OR);
115172       fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
115173       fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
115174     }
115175   }
115176 }
115177
115178 static void fts3EvalPhraseMergeToken(
115179   Fts3Table *pTab,
115180   Fts3Phrase *p,
115181   int iToken,
115182   char *pList,
115183   int nList
115184 ){
115185   assert( iToken!=p->iDoclistToken );
115186
115187   if( pList==0 ){
115188     sqlite3_free(p->doclist.aAll);
115189     p->doclist.aAll = 0;
115190     p->doclist.nAll = 0;
115191   }
115192
115193   else if( p->iDoclistToken<0 ){
115194     p->doclist.aAll = pList;
115195     p->doclist.nAll = nList;
115196   }
115197
115198   else if( p->doclist.aAll==0 ){
115199     sqlite3_free(pList);
115200   }
115201
115202   else {
115203     char *pLeft;
115204     char *pRight;
115205     int nLeft;
115206     int nRight;
115207     int nDiff;
115208
115209     if( p->iDoclistToken<iToken ){
115210       pLeft = p->doclist.aAll;
115211       nLeft = p->doclist.nAll;
115212       pRight = pList;
115213       nRight = nList;
115214       nDiff = iToken - p->iDoclistToken;
115215     }else{
115216       pRight = p->doclist.aAll;
115217       nRight = p->doclist.nAll;
115218       pLeft = pList;
115219       nLeft = nList;
115220       nDiff = p->iDoclistToken - iToken;
115221     }
115222
115223     fts3DoclistPhraseMerge(pTab->bDescIdx, nDiff, pLeft, nLeft, pRight,&nRight);
115224     sqlite3_free(pLeft);
115225     p->doclist.aAll = pRight;
115226     p->doclist.nAll = nRight;
115227   }
115228
115229   if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
115230 }
115231
115232 static int fts3EvalPhraseLoad(
115233   Fts3Cursor *pCsr, 
115234   Fts3Phrase *p
115235 ){
115236   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
115237   int iToken;
115238   int rc = SQLITE_OK;
115239
115240   for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
115241     Fts3PhraseToken *pToken = &p->aToken[iToken];
115242     assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
115243
115244     if( pToken->pSegcsr ){
115245       int nThis = 0;
115246       char *pThis = 0;
115247       rc = fts3TermSelect(pTab, pToken, p->iColumn, 1, &nThis, &pThis);
115248       if( rc==SQLITE_OK ){
115249         fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
115250       }
115251     }
115252     assert( pToken->pSegcsr==0 );
115253   }
115254
115255   return rc;
115256 }
115257
115258 static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
115259   int iToken;
115260   int rc = SQLITE_OK;
115261
115262   int nMaxUndeferred = pPhrase->iDoclistToken;
115263   char *aPoslist = 0;
115264   int nPoslist = 0;
115265   int iPrev = -1;
115266
115267   assert( pPhrase->doclist.bFreeList==0 );
115268
115269   for(iToken=0; rc==SQLITE_OK && iToken<pPhrase->nToken; iToken++){
115270     Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
115271     Fts3DeferredToken *pDeferred = pToken->pDeferred;
115272
115273     if( pDeferred ){
115274       char *pList;
115275       int nList;
115276       rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
115277       if( rc!=SQLITE_OK ) return rc;
115278
115279       if( pList==0 ){
115280         sqlite3_free(aPoslist);
115281         pPhrase->doclist.pList = 0;
115282         pPhrase->doclist.nList = 0;
115283         return SQLITE_OK;
115284
115285       }else if( aPoslist==0 ){
115286         aPoslist = pList;
115287         nPoslist = nList;
115288
115289       }else{
115290         char *aOut = pList;
115291         char *p1 = aPoslist;
115292         char *p2 = aOut;
115293
115294         assert( iPrev>=0 );
115295         fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
115296         sqlite3_free(aPoslist);
115297         aPoslist = pList;
115298         nPoslist = aOut - aPoslist;
115299         if( nPoslist==0 ){
115300           sqlite3_free(aPoslist);
115301           pPhrase->doclist.pList = 0;
115302           pPhrase->doclist.nList = 0;
115303           return SQLITE_OK;
115304         }
115305       }
115306       iPrev = iToken;
115307     }
115308   }
115309
115310   if( iPrev>=0 ){
115311     if( nMaxUndeferred<0 ){
115312       pPhrase->doclist.pList = aPoslist;
115313       pPhrase->doclist.nList = nPoslist;
115314       pPhrase->doclist.iDocid = pCsr->iPrevId;
115315       pPhrase->doclist.bFreeList = 1;
115316     }else{
115317       int nDistance;
115318       char *p1;
115319       char *p2;
115320       char *aOut;
115321
115322       if( nMaxUndeferred>iPrev ){
115323         p1 = aPoslist;
115324         p2 = pPhrase->doclist.pList;
115325         nDistance = nMaxUndeferred - iPrev;
115326       }else{
115327         p1 = pPhrase->doclist.pList;
115328         p2 = aPoslist;
115329         nDistance = iPrev - nMaxUndeferred;
115330       }
115331
115332       aOut = (char *)sqlite3_malloc(nPoslist+8);
115333       if( !aOut ){
115334         sqlite3_free(aPoslist);
115335         return SQLITE_NOMEM;
115336       }
115337       
115338       pPhrase->doclist.pList = aOut;
115339       if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
115340         pPhrase->doclist.bFreeList = 1;
115341         pPhrase->doclist.nList = (aOut - pPhrase->doclist.pList);
115342       }else{
115343         sqlite3_free(aOut);
115344         pPhrase->doclist.pList = 0;
115345         pPhrase->doclist.nList = 0;
115346       }
115347       sqlite3_free(aPoslist);
115348     }
115349   }
115350
115351   return SQLITE_OK;
115352 }
115353
115354 /*
115355 ** This function is called for each Fts3Phrase in a full-text query 
115356 ** expression to initialize the mechanism for returning rows. Once this
115357 ** function has been called successfully on an Fts3Phrase, it may be
115358 ** used with fts3EvalPhraseNext() to iterate through the matching docids.
115359 */
115360 static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
115361   int rc;
115362   Fts3PhraseToken *pFirst = &p->aToken[0];
115363   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
115364
115365   if( pCsr->bDesc==pTab->bDescIdx 
115366    && bOptOk==1 
115367    && p->nToken==1 
115368    && pFirst->pSegcsr 
115369    && pFirst->pSegcsr->bLookup 
115370   ){
115371     /* Use the incremental approach. */
115372     int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
115373     rc = sqlite3Fts3MsrIncrStart(
115374         pTab, pFirst->pSegcsr, iCol, pFirst->z, pFirst->n);
115375     p->bIncr = 1;
115376
115377   }else{
115378     /* Load the full doclist for the phrase into memory. */
115379     rc = fts3EvalPhraseLoad(pCsr, p);
115380     p->bIncr = 0;
115381   }
115382
115383   assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
115384   return rc;
115385 }
115386
115387 /*
115388 ** This function is used to iterate backwards (from the end to start) 
115389 ** through doclists.
115390 */
115391 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
115392   int bDescIdx,                   /* True if the doclist is desc */
115393   char *aDoclist,                 /* Pointer to entire doclist */
115394   int nDoclist,                   /* Length of aDoclist in bytes */
115395   char **ppIter,                  /* IN/OUT: Iterator pointer */
115396   sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
115397   int *pnList,                    /* IN/OUT: List length pointer */
115398   u8 *pbEof                       /* OUT: End-of-file flag */
115399 ){
115400   char *p = *ppIter;
115401
115402   assert( nDoclist>0 );
115403   assert( *pbEof==0 );
115404   assert( p || *piDocid==0 );
115405   assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
115406
115407   if( p==0 ){
115408     sqlite3_int64 iDocid = 0;
115409     char *pNext = 0;
115410     char *pDocid = aDoclist;
115411     char *pEnd = &aDoclist[nDoclist];
115412     int iMul = 1;
115413
115414     while( pDocid<pEnd ){
115415       sqlite3_int64 iDelta;
115416       pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
115417       iDocid += (iMul * iDelta);
115418       pNext = pDocid;
115419       fts3PoslistCopy(0, &pDocid);
115420       while( pDocid<pEnd && *pDocid==0 ) pDocid++;
115421       iMul = (bDescIdx ? -1 : 1);
115422     }
115423
115424     *pnList = pEnd - pNext;
115425     *ppIter = pNext;
115426     *piDocid = iDocid;
115427   }else{
115428     int iMul = (bDescIdx ? -1 : 1);
115429     sqlite3_int64 iDelta;
115430     fts3GetReverseVarint(&p, aDoclist, &iDelta);
115431     *piDocid -= (iMul * iDelta);
115432
115433     if( p==aDoclist ){
115434       *pbEof = 1;
115435     }else{
115436       char *pSave = p;
115437       fts3ReversePoslist(aDoclist, &p);
115438       *pnList = (pSave - p);
115439     }
115440     *ppIter = p;
115441   }
115442 }
115443
115444 /*
115445 ** Attempt to move the phrase iterator to point to the next matching docid. 
115446 ** If an error occurs, return an SQLite error code. Otherwise, return 
115447 ** SQLITE_OK.
115448 **
115449 ** If there is no "next" entry and no error occurs, then *pbEof is set to
115450 ** 1 before returning. Otherwise, if no error occurs and the iterator is
115451 ** successfully advanced, *pbEof is set to 0.
115452 */
115453 static int fts3EvalPhraseNext(
115454   Fts3Cursor *pCsr, 
115455   Fts3Phrase *p, 
115456   u8 *pbEof
115457 ){
115458   int rc = SQLITE_OK;
115459   Fts3Doclist *pDL = &p->doclist;
115460   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
115461
115462   if( p->bIncr ){
115463     assert( p->nToken==1 );
115464     assert( pDL->pNextDocid==0 );
115465     rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr, 
115466         &pDL->iDocid, &pDL->pList, &pDL->nList
115467     );
115468     if( rc==SQLITE_OK && !pDL->pList ){
115469       *pbEof = 1;
115470     }
115471   }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
115472     sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll, 
115473         &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
115474     );
115475     pDL->pList = pDL->pNextDocid;
115476   }else{
115477     char *pIter;                            /* Used to iterate through aAll */
115478     char *pEnd = &pDL->aAll[pDL->nAll];     /* 1 byte past end of aAll */
115479     if( pDL->pNextDocid ){
115480       pIter = pDL->pNextDocid;
115481     }else{
115482       pIter = pDL->aAll;
115483     }
115484
115485     if( pIter>=pEnd ){
115486       /* We have already reached the end of this doclist. EOF. */
115487       *pbEof = 1;
115488     }else{
115489       sqlite3_int64 iDelta;
115490       pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
115491       if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
115492         pDL->iDocid += iDelta;
115493       }else{
115494         pDL->iDocid -= iDelta;
115495       }
115496       pDL->pList = pIter;
115497       fts3PoslistCopy(0, &pIter);
115498       pDL->nList = (pIter - pDL->pList);
115499
115500       /* pIter now points just past the 0x00 that terminates the position-
115501       ** list for document pDL->iDocid. However, if this position-list was
115502       ** edited in place by fts3EvalNearTrim2(), then pIter may not actually
115503       ** point to the start of the next docid value. The following line deals
115504       ** with this case by advancing pIter past the zero-padding added by
115505       ** fts3EvalNearTrim2().  */
115506       while( pIter<pEnd && *pIter==0 ) pIter++;
115507
115508       pDL->pNextDocid = pIter;
115509       assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
115510       *pbEof = 0;
115511     }
115512   }
115513
115514   return rc;
115515 }
115516
115517 static void fts3EvalStartReaders(
115518   Fts3Cursor *pCsr, 
115519   Fts3Expr *pExpr, 
115520   int bOptOk,
115521   int *pRc
115522 ){
115523   if( pExpr && SQLITE_OK==*pRc ){
115524     if( pExpr->eType==FTSQUERY_PHRASE ){
115525       int i;
115526       int nToken = pExpr->pPhrase->nToken;
115527       for(i=0; i<nToken; i++){
115528         if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
115529       }
115530       pExpr->bDeferred = (i==nToken);
115531       *pRc = fts3EvalPhraseStart(pCsr, bOptOk, pExpr->pPhrase);
115532     }else{
115533       fts3EvalStartReaders(pCsr, pExpr->pLeft, bOptOk, pRc);
115534       fts3EvalStartReaders(pCsr, pExpr->pRight, bOptOk, pRc);
115535       pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
115536     }
115537   }
115538 }
115539
115540 typedef struct Fts3TokenAndCost Fts3TokenAndCost;
115541 struct Fts3TokenAndCost {
115542   Fts3Phrase *pPhrase;            /* The phrase the token belongs to */
115543   int iToken;                     /* Position of token in phrase */
115544   Fts3PhraseToken *pToken;        /* The token itself */
115545   Fts3Expr *pRoot; 
115546   int nOvfl;
115547   int iCol;                       /* The column the token must match */
115548 };
115549
115550 static void fts3EvalTokenCosts(
115551   Fts3Cursor *pCsr, 
115552   Fts3Expr *pRoot, 
115553   Fts3Expr *pExpr, 
115554   Fts3TokenAndCost **ppTC,
115555   Fts3Expr ***ppOr,
115556   int *pRc
115557 ){
115558   if( *pRc==SQLITE_OK && pExpr ){
115559     if( pExpr->eType==FTSQUERY_PHRASE ){
115560       Fts3Phrase *pPhrase = pExpr->pPhrase;
115561       int i;
115562       for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
115563         Fts3TokenAndCost *pTC = (*ppTC)++;
115564         pTC->pPhrase = pPhrase;
115565         pTC->iToken = i;
115566         pTC->pRoot = pRoot;
115567         pTC->pToken = &pPhrase->aToken[i];
115568         pTC->iCol = pPhrase->iColumn;
115569         *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
115570       }
115571     }else if( pExpr->eType!=FTSQUERY_NOT ){
115572       if( pExpr->eType==FTSQUERY_OR ){
115573         pRoot = pExpr->pLeft;
115574         **ppOr = pRoot;
115575         (*ppOr)++;
115576       }
115577       fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
115578       if( pExpr->eType==FTSQUERY_OR ){
115579         pRoot = pExpr->pRight;
115580         **ppOr = pRoot;
115581         (*ppOr)++;
115582       }
115583       fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
115584     }
115585   }
115586 }
115587
115588 static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
115589   if( pCsr->nRowAvg==0 ){
115590     /* The average document size, which is required to calculate the cost
115591      ** of each doclist, has not yet been determined. Read the required 
115592      ** data from the %_stat table to calculate it.
115593      **
115594      ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3 
115595      ** varints, where nCol is the number of columns in the FTS3 table.
115596      ** The first varint is the number of documents currently stored in
115597      ** the table. The following nCol varints contain the total amount of
115598      ** data stored in all rows of each column of the table, from left
115599      ** to right.
115600      */
115601     int rc;
115602     Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
115603     sqlite3_stmt *pStmt;
115604     sqlite3_int64 nDoc = 0;
115605     sqlite3_int64 nByte = 0;
115606     const char *pEnd;
115607     const char *a;
115608
115609     rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
115610     if( rc!=SQLITE_OK ) return rc;
115611     a = sqlite3_column_blob(pStmt, 0);
115612     assert( a );
115613
115614     pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
115615     a += sqlite3Fts3GetVarint(a, &nDoc);
115616     while( a<pEnd ){
115617       a += sqlite3Fts3GetVarint(a, &nByte);
115618     }
115619     if( nDoc==0 || nByte==0 ){
115620       sqlite3_reset(pStmt);
115621       return SQLITE_CORRUPT_VTAB;
115622     }
115623
115624     pCsr->nDoc = nDoc;
115625     pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
115626     assert( pCsr->nRowAvg>0 ); 
115627     rc = sqlite3_reset(pStmt);
115628     if( rc!=SQLITE_OK ) return rc;
115629   }
115630
115631   *pnPage = pCsr->nRowAvg;
115632   return SQLITE_OK;
115633 }
115634
115635 static int fts3EvalSelectDeferred(
115636   Fts3Cursor *pCsr,
115637   Fts3Expr *pRoot,
115638   Fts3TokenAndCost *aTC,
115639   int nTC
115640 ){
115641   int nDocSize = 0;
115642   int nDocEst = 0;
115643   int rc = SQLITE_OK;
115644   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
115645   int ii;
115646
115647   int nOvfl = 0;
115648   int nTerm = 0;
115649
115650   for(ii=0; ii<nTC; ii++){
115651     if( aTC[ii].pRoot==pRoot ){
115652       nOvfl += aTC[ii].nOvfl;
115653       nTerm++;
115654     }
115655   }
115656   if( nOvfl==0 || nTerm<2 ) return SQLITE_OK;
115657
115658   rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
115659
115660   for(ii=0; ii<nTerm && rc==SQLITE_OK; ii++){
115661     int jj;
115662     Fts3TokenAndCost *pTC = 0;
115663
115664     for(jj=0; jj<nTC; jj++){
115665       if( aTC[jj].pToken && aTC[jj].pRoot==pRoot 
115666        && (!pTC || aTC[jj].nOvfl<pTC->nOvfl) 
115667       ){
115668         pTC = &aTC[jj];
115669       }
115670     }
115671     assert( pTC );
115672
115673     /* At this point pTC points to the cheapest remaining token. */
115674     if( ii==0 ){
115675       if( pTC->nOvfl ){
115676         nDocEst = (pTC->nOvfl * pTab->nPgsz + pTab->nPgsz) / 10;
115677       }else{
115678         Fts3PhraseToken *pToken = pTC->pToken;
115679         int nList = 0;
115680         char *pList = 0;
115681         rc = fts3TermSelect(pTab, pToken, pTC->iCol, 1, &nList, &pList);
115682         assert( rc==SQLITE_OK || pList==0 );
115683
115684         if( rc==SQLITE_OK ){
115685           nDocEst = fts3DoclistCountDocids(1, pList, nList);
115686           fts3EvalPhraseMergeToken(pTab, pTC->pPhrase, pTC->iToken,pList,nList);
115687         }
115688       }
115689     }else{
115690       if( pTC->nOvfl>=(nDocEst*nDocSize) ){
115691         Fts3PhraseToken *pToken = pTC->pToken;
115692         rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
115693         fts3SegReaderCursorFree(pToken->pSegcsr);
115694         pToken->pSegcsr = 0;
115695       }
115696       nDocEst = 1 + (nDocEst/4);
115697     }
115698     pTC->pToken = 0;
115699   }
115700
115701   return rc;
115702 }
115703
115704 SQLITE_PRIVATE int sqlite3Fts3EvalStart(Fts3Cursor *pCsr, Fts3Expr *pExpr, int bOptOk){
115705   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
115706   int rc = SQLITE_OK;
115707   int nToken = 0;
115708   int nOr = 0;
115709
115710   /* Allocate a MultiSegReader for each token in the expression. */
115711   fts3EvalAllocateReaders(pCsr, pExpr, &nToken, &nOr, &rc);
115712
115713   /* Call fts3EvalPhraseStart() on all phrases in the expression. TODO:
115714   ** This call will eventually also be responsible for determining which
115715   ** tokens are 'deferred' until the document text is loaded into memory.
115716   **
115717   ** Each token in each phrase is dealt with using one of the following
115718   ** three strategies:
115719   **
115720   **   1. Entire doclist loaded into memory as part of the
115721   **      fts3EvalStartReaders() call.
115722   **
115723   **   2. Doclist loaded into memory incrementally, as part of each
115724   **      sqlite3Fts3EvalNext() call.
115725   **
115726   **   3. Token doclist is never loaded. Instead, documents are loaded into
115727   **      memory and scanned for the token as part of the sqlite3Fts3EvalNext()
115728   **      call. This is known as a "deferred" token.
115729   */
115730
115731   /* If bOptOk is true, check if there are any tokens that should be deferred.
115732   */
115733   if( rc==SQLITE_OK && bOptOk && nToken>1 && pTab->bHasStat ){
115734     Fts3TokenAndCost *aTC;
115735     Fts3Expr **apOr;
115736     aTC = (Fts3TokenAndCost *)sqlite3_malloc(
115737         sizeof(Fts3TokenAndCost) * nToken
115738       + sizeof(Fts3Expr *) * nOr * 2
115739     );
115740     apOr = (Fts3Expr **)&aTC[nToken];
115741
115742     if( !aTC ){
115743       rc = SQLITE_NOMEM;
115744     }else{
115745       int ii;
115746       Fts3TokenAndCost *pTC = aTC;
115747       Fts3Expr **ppOr = apOr;
115748
115749       fts3EvalTokenCosts(pCsr, 0, pExpr, &pTC, &ppOr, &rc);
115750       nToken = pTC-aTC;
115751       nOr = ppOr-apOr;
115752
115753       if( rc==SQLITE_OK ){
115754         rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
115755         for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
115756           rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
115757         }
115758       }
115759
115760       sqlite3_free(aTC);
115761     }
115762   }
115763
115764   fts3EvalStartReaders(pCsr, pExpr, bOptOk, &rc);
115765   return rc;
115766 }
115767
115768 static void fts3EvalZeroPoslist(Fts3Phrase *pPhrase){
115769   if( pPhrase->doclist.bFreeList ){
115770     sqlite3_free(pPhrase->doclist.pList);
115771   }
115772   pPhrase->doclist.pList = 0;
115773   pPhrase->doclist.nList = 0;
115774   pPhrase->doclist.bFreeList = 0;
115775 }
115776
115777 static int fts3EvalNearTrim2(
115778   int nNear,
115779   char *aTmp,                     /* Temporary space to use */
115780   char **paPoslist,               /* IN/OUT: Position list */
115781   int *pnToken,                   /* IN/OUT: Tokens in phrase of *paPoslist */
115782   Fts3Phrase *pPhrase             /* The phrase object to trim the doclist of */
115783 ){
115784   int nParam1 = nNear + pPhrase->nToken;
115785   int nParam2 = nNear + *pnToken;
115786   int nNew;
115787   char *p2; 
115788   char *pOut; 
115789   int res;
115790
115791   assert( pPhrase->doclist.pList );
115792
115793   p2 = pOut = pPhrase->doclist.pList;
115794   res = fts3PoslistNearMerge(
115795     &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
115796   );
115797   if( res ){
115798     nNew = (pOut - pPhrase->doclist.pList) - 1;
115799     assert( pPhrase->doclist.pList[nNew]=='\0' );
115800     assert( nNew<=pPhrase->doclist.nList && nNew>0 );
115801     memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
115802     pPhrase->doclist.nList = nNew;
115803     *paPoslist = pPhrase->doclist.pList;
115804     *pnToken = pPhrase->nToken;
115805   }
115806
115807   return res;
115808 }
115809
115810 static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
115811   int res = 1;
115812
115813   /* The following block runs if pExpr is the root of a NEAR query.
115814   ** For example, the query:
115815   **
115816   **         "w" NEAR "x" NEAR "y" NEAR "z"
115817   **
115818   ** which is represented in tree form as:
115819   **
115820   **                               |
115821   **                          +--NEAR--+      <-- root of NEAR query
115822   **                          |        |
115823   **                     +--NEAR--+   "z"
115824   **                     |        |
115825   **                +--NEAR--+   "y"
115826   **                |        |
115827   **               "w"      "x"
115828   **
115829   ** The right-hand child of a NEAR node is always a phrase. The 
115830   ** left-hand child may be either a phrase or a NEAR node. There are
115831   ** no exceptions to this.
115832   */
115833   if( *pRc==SQLITE_OK 
115834    && pExpr->eType==FTSQUERY_NEAR 
115835    && pExpr->bEof==0
115836    && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
115837   ){
115838     Fts3Expr *p; 
115839     int nTmp = 0;                 /* Bytes of temp space */
115840     char *aTmp;                   /* Temp space for PoslistNearMerge() */
115841
115842     /* Allocate temporary working space. */
115843     for(p=pExpr; p->pLeft; p=p->pLeft){
115844       nTmp += p->pRight->pPhrase->doclist.nList;
115845     }
115846     nTmp += p->pPhrase->doclist.nList;
115847     aTmp = sqlite3_malloc(nTmp*2);
115848     if( !aTmp ){
115849       *pRc = SQLITE_NOMEM;
115850       res = 0;
115851     }else{
115852       char *aPoslist = p->pPhrase->doclist.pList;
115853       int nToken = p->pPhrase->nToken;
115854
115855       for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
115856         Fts3Phrase *pPhrase = p->pRight->pPhrase;
115857         int nNear = p->nNear;
115858         res = fts3EvalNearTrim2(nNear, aTmp, &aPoslist, &nToken, pPhrase);
115859       }
115860   
115861       aPoslist = pExpr->pRight->pPhrase->doclist.pList;
115862       nToken = pExpr->pRight->pPhrase->nToken;
115863       for(p=pExpr->pLeft; p && res; p=p->pLeft){
115864         int nNear = p->pParent->nNear;
115865         Fts3Phrase *pPhrase = (
115866             p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
115867         );
115868         res = fts3EvalNearTrim2(nNear, aTmp, &aPoslist, &nToken, pPhrase);
115869       }
115870     }
115871
115872     sqlite3_free(aTmp);
115873   }
115874
115875   return res;
115876 }
115877
115878 /*
115879 ** This macro is used by the fts3EvalNext() function. The two arguments are
115880 ** 64-bit docid values. If the current query is "ORDER BY docid ASC", then
115881 ** the macro returns (i1 - i2). Or if it is "ORDER BY docid DESC", then
115882 ** it returns (i2 - i1). This allows the same code to be used for merging
115883 ** doclists in ascending or descending order.
115884 */
115885 #define DOCID_CMP(i1, i2) ((pCsr->bDesc?-1:1) * (i1-i2))
115886
115887 static void fts3EvalNext(
115888   Fts3Cursor *pCsr, 
115889   Fts3Expr *pExpr, 
115890   int *pRc
115891 ){
115892   if( *pRc==SQLITE_OK ){
115893     assert( pExpr->bEof==0 );
115894     pExpr->bStart = 1;
115895
115896     switch( pExpr->eType ){
115897       case FTSQUERY_NEAR:
115898       case FTSQUERY_AND: {
115899         Fts3Expr *pLeft = pExpr->pLeft;
115900         Fts3Expr *pRight = pExpr->pRight;
115901         assert( !pLeft->bDeferred || !pRight->bDeferred );
115902         if( pLeft->bDeferred ){
115903           fts3EvalNext(pCsr, pRight, pRc);
115904           pExpr->iDocid = pRight->iDocid;
115905           pExpr->bEof = pRight->bEof;
115906         }else if( pRight->bDeferred ){
115907           fts3EvalNext(pCsr, pLeft, pRc);
115908           pExpr->iDocid = pLeft->iDocid;
115909           pExpr->bEof = pLeft->bEof;
115910         }else{
115911           fts3EvalNext(pCsr, pLeft, pRc);
115912           fts3EvalNext(pCsr, pRight, pRc);
115913
115914           while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
115915             sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
115916             if( iDiff==0 ) break;
115917             if( iDiff<0 ){
115918               fts3EvalNext(pCsr, pLeft, pRc);
115919             }else{
115920               fts3EvalNext(pCsr, pRight, pRc);
115921             }
115922           }
115923
115924           pExpr->iDocid = pLeft->iDocid;
115925           pExpr->bEof = (pLeft->bEof || pRight->bEof);
115926         }
115927         break;
115928       }
115929   
115930       case FTSQUERY_OR: {
115931         Fts3Expr *pLeft = pExpr->pLeft;
115932         Fts3Expr *pRight = pExpr->pRight;
115933         sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
115934
115935         assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
115936         assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
115937
115938         if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
115939           fts3EvalNext(pCsr, pLeft, pRc);
115940         }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
115941           fts3EvalNext(pCsr, pRight, pRc);
115942         }else{
115943           fts3EvalNext(pCsr, pLeft, pRc);
115944           fts3EvalNext(pCsr, pRight, pRc);
115945         }
115946
115947         pExpr->bEof = (pLeft->bEof && pRight->bEof);
115948         iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
115949         if( pRight->bEof || (pLeft->bEof==0 &&  iCmp<0) ){
115950           pExpr->iDocid = pLeft->iDocid;
115951         }else{
115952           pExpr->iDocid = pRight->iDocid;
115953         }
115954
115955         break;
115956       }
115957
115958       case FTSQUERY_NOT: {
115959         Fts3Expr *pLeft = pExpr->pLeft;
115960         Fts3Expr *pRight = pExpr->pRight;
115961
115962         if( pRight->bStart==0 ){
115963           fts3EvalNext(pCsr, pRight, pRc);
115964           assert( *pRc!=SQLITE_OK || pRight->bStart );
115965         }
115966
115967         fts3EvalNext(pCsr, pLeft, pRc);
115968         if( pLeft->bEof==0 ){
115969           while( !*pRc 
115970               && !pRight->bEof 
115971               && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0 
115972           ){
115973             fts3EvalNext(pCsr, pRight, pRc);
115974           }
115975         }
115976         pExpr->iDocid = pLeft->iDocid;
115977         pExpr->bEof = pLeft->bEof;
115978         break;
115979       }
115980
115981       default: {
115982         Fts3Phrase *pPhrase = pExpr->pPhrase;
115983         fts3EvalZeroPoslist(pPhrase);
115984         *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
115985         pExpr->iDocid = pPhrase->doclist.iDocid;
115986         break;
115987       }
115988     }
115989   }
115990 }
115991
115992 static int fts3EvalDeferredTest(Fts3Cursor *pCsr, Fts3Expr *pExpr, int *pRc){
115993   int bHit = 1;
115994   if( *pRc==SQLITE_OK ){
115995     switch( pExpr->eType ){
115996       case FTSQUERY_NEAR:
115997       case FTSQUERY_AND:
115998         bHit = (
115999             fts3EvalDeferredTest(pCsr, pExpr->pLeft, pRc)
116000          && fts3EvalDeferredTest(pCsr, pExpr->pRight, pRc)
116001          && fts3EvalNearTest(pExpr, pRc)
116002         );
116003
116004         /* If the NEAR expression does not match any rows, zero the doclist for 
116005         ** all phrases involved in the NEAR. This is because the snippet(),
116006         ** offsets() and matchinfo() functions are not supposed to recognize 
116007         ** any instances of phrases that are part of unmatched NEAR queries. 
116008         ** For example if this expression:
116009         **
116010         **    ... MATCH 'a OR (b NEAR c)'
116011         **
116012         ** is matched against a row containing:
116013         **
116014         **        'a b d e'
116015         **
116016         ** then any snippet() should ony highlight the "a" term, not the "b"
116017         ** (as "b" is part of a non-matching NEAR clause).
116018         */
116019         if( bHit==0 
116020          && pExpr->eType==FTSQUERY_NEAR 
116021          && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
116022         ){
116023           Fts3Expr *p;
116024           for(p=pExpr; p->pPhrase==0; p=p->pLeft){
116025             if( p->pRight->iDocid==pCsr->iPrevId ){
116026               fts3EvalZeroPoslist(p->pRight->pPhrase);
116027             }
116028           }
116029           if( p->iDocid==pCsr->iPrevId ){
116030             fts3EvalZeroPoslist(p->pPhrase);
116031           }
116032         }
116033
116034         break;
116035
116036       case FTSQUERY_OR: {
116037         int bHit1 = fts3EvalDeferredTest(pCsr, pExpr->pLeft, pRc);
116038         int bHit2 = fts3EvalDeferredTest(pCsr, pExpr->pRight, pRc);
116039         bHit = bHit1 || bHit2;
116040         break;
116041       }
116042
116043       case FTSQUERY_NOT:
116044         bHit = (
116045             fts3EvalDeferredTest(pCsr, pExpr->pLeft, pRc)
116046          && !fts3EvalDeferredTest(pCsr, pExpr->pRight, pRc)
116047         );
116048         break;
116049
116050       default: {
116051         if( pCsr->pDeferred 
116052          && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
116053         ){
116054           Fts3Phrase *pPhrase = pExpr->pPhrase;
116055           assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
116056           if( pExpr->bDeferred ){
116057             fts3EvalZeroPoslist(pPhrase);
116058           }
116059           *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
116060           bHit = (pPhrase->doclist.pList!=0);
116061           pExpr->iDocid = pCsr->iPrevId;
116062         }else{
116063           bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
116064         }
116065         break;
116066       }
116067     }
116068   }
116069   return bHit;
116070 }
116071
116072 /*
116073 ** Return 1 if both of the following are true:
116074 **
116075 **   1. *pRc is SQLITE_OK when this function returns, and
116076 **
116077 **   2. After scanning the current FTS table row for the deferred tokens,
116078 **      it is determined that the row does not match the query.
116079 **
116080 ** Or, if no error occurs and it seems the current row does match the FTS
116081 ** query, return 0.
116082 */
116083 static int fts3EvalLoadDeferred(Fts3Cursor *pCsr, int *pRc){
116084   int rc = *pRc;
116085   int bMiss = 0;
116086   if( rc==SQLITE_OK ){
116087     if( pCsr->pDeferred ){
116088       rc = fts3CursorSeek(0, pCsr);
116089       if( rc==SQLITE_OK ){
116090         rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
116091       }
116092     }
116093     bMiss = (0==fts3EvalDeferredTest(pCsr, pCsr->pExpr, &rc));
116094     sqlite3Fts3FreeDeferredDoclists(pCsr);
116095     *pRc = rc;
116096   }
116097   return (rc==SQLITE_OK && bMiss);
116098 }
116099
116100 /*
116101 ** Advance to the next document that matches the FTS expression in
116102 ** Fts3Cursor.pExpr.
116103 */
116104 SQLITE_PRIVATE int sqlite3Fts3EvalNext(Fts3Cursor *pCsr){
116105   int rc = SQLITE_OK;             /* Return Code */
116106   Fts3Expr *pExpr = pCsr->pExpr;
116107   assert( pCsr->isEof==0 );
116108   if( pExpr==0 ){
116109     pCsr->isEof = 1;
116110   }else{
116111     do {
116112       if( pCsr->isRequireSeek==0 ){
116113         sqlite3_reset(pCsr->pStmt);
116114       }
116115       assert( sqlite3_data_count(pCsr->pStmt)==0 );
116116       fts3EvalNext(pCsr, pExpr, &rc);
116117       pCsr->isEof = pExpr->bEof;
116118       pCsr->isRequireSeek = 1;
116119       pCsr->isMatchinfoNeeded = 1;
116120       pCsr->iPrevId = pExpr->iDocid;
116121     }while( pCsr->isEof==0 && fts3EvalLoadDeferred(pCsr, &rc) );
116122   }
116123   return rc;
116124 }
116125
116126 /*
116127 ** Restart interation for expression pExpr so that the next call to
116128 ** sqlite3Fts3EvalNext() visits the first row. Do not allow incremental 
116129 ** loading or merging of phrase doclists for this iteration.
116130 **
116131 ** If *pRc is other than SQLITE_OK when this function is called, it is
116132 ** a no-op. If an error occurs within this function, *pRc is set to an
116133 ** SQLite error code before returning.
116134 */
116135 static void fts3EvalRestart(
116136   Fts3Cursor *pCsr,
116137   Fts3Expr *pExpr,
116138   int *pRc
116139 ){
116140   if( pExpr && *pRc==SQLITE_OK ){
116141     Fts3Phrase *pPhrase = pExpr->pPhrase;
116142
116143     if( pPhrase ){
116144       fts3EvalZeroPoslist(pPhrase);
116145       if( pPhrase->bIncr ){
116146         assert( pPhrase->nToken==1 );
116147         assert( pPhrase->aToken[0].pSegcsr );
116148         sqlite3Fts3MsrIncrRestart(pPhrase->aToken[0].pSegcsr);
116149         *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
116150       }
116151
116152       pPhrase->doclist.pNextDocid = 0;
116153       pPhrase->doclist.iDocid = 0;
116154     }
116155
116156     pExpr->iDocid = 0;
116157     pExpr->bEof = 0;
116158     pExpr->bStart = 0;
116159
116160     fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
116161     fts3EvalRestart(pCsr, pExpr->pRight, pRc);
116162   }
116163 }
116164
116165 /*
116166 ** After allocating the Fts3Expr.aMI[] array for each phrase in the 
116167 ** expression rooted at pExpr, the cursor iterates through all rows matched
116168 ** by pExpr, calling this function for each row. This function increments
116169 ** the values in Fts3Expr.aMI[] according to the position-list currently
116170 ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase 
116171 ** expression nodes.
116172 */
116173 static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
116174   if( pExpr ){
116175     Fts3Phrase *pPhrase = pExpr->pPhrase;
116176     if( pPhrase && pPhrase->doclist.pList ){
116177       int iCol = 0;
116178       char *p = pPhrase->doclist.pList;
116179
116180       assert( *p );
116181       while( 1 ){
116182         u8 c = 0;
116183         int iCnt = 0;
116184         while( 0xFE & (*p | c) ){
116185           if( (c&0x80)==0 ) iCnt++;
116186           c = *p++ & 0x80;
116187         }
116188
116189         /* aMI[iCol*3 + 1] = Number of occurrences
116190         ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
116191         */
116192         pExpr->aMI[iCol*3 + 1] += iCnt;
116193         pExpr->aMI[iCol*3 + 2] += (iCnt>0);
116194         if( *p==0x00 ) break;
116195         p++;
116196         p += sqlite3Fts3GetVarint32(p, &iCol);
116197       }
116198     }
116199
116200     fts3EvalUpdateCounts(pExpr->pLeft);
116201     fts3EvalUpdateCounts(pExpr->pRight);
116202   }
116203 }
116204
116205 /*
116206 ** Expression pExpr must be of type FTSQUERY_PHRASE.
116207 **
116208 ** If it is not already allocated and populated, this function allocates and
116209 ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
116210 ** of a NEAR expression, then it also allocates and populates the same array
116211 ** for all other phrases that are part of the NEAR expression.
116212 **
116213 ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
116214 ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
116215 */
116216 static int fts3EvalGatherStats(
116217   Fts3Cursor *pCsr,               /* Cursor object */
116218   Fts3Expr *pExpr                 /* FTSQUERY_PHRASE expression */
116219 ){
116220   int rc = SQLITE_OK;             /* Return code */
116221
116222   assert( pExpr->eType==FTSQUERY_PHRASE );
116223   if( pExpr->aMI==0 ){
116224     Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
116225     Fts3Expr *pRoot;                /* Root of NEAR expression */
116226     Fts3Expr *p;                    /* Iterator used for several purposes */
116227
116228     sqlite3_int64 iPrevId = pCsr->iPrevId;
116229     sqlite3_int64 iDocid;
116230     u8 bEof;
116231
116232     /* Find the root of the NEAR expression */
116233     pRoot = pExpr;
116234     while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
116235       pRoot = pRoot->pParent;
116236     }
116237     iDocid = pRoot->iDocid;
116238     bEof = pRoot->bEof;
116239     assert( pRoot->bStart );
116240
116241     /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
116242     for(p=pRoot; p; p=p->pLeft){
116243       Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
116244       assert( pE->aMI==0 );
116245       pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
116246       if( !pE->aMI ) return SQLITE_NOMEM;
116247       memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
116248     }
116249
116250     fts3EvalRestart(pCsr, pRoot, &rc);
116251
116252     while( pCsr->isEof==0 && rc==SQLITE_OK ){
116253
116254       do {
116255         /* Ensure the %_content statement is reset. */
116256         if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
116257         assert( sqlite3_data_count(pCsr->pStmt)==0 );
116258
116259         /* Advance to the next document */
116260         fts3EvalNext(pCsr, pRoot, &rc);
116261         pCsr->isEof = pRoot->bEof;
116262         pCsr->isRequireSeek = 1;
116263         pCsr->isMatchinfoNeeded = 1;
116264         pCsr->iPrevId = pRoot->iDocid;
116265       }while( pCsr->isEof==0 
116266            && pRoot->eType==FTSQUERY_NEAR 
116267            && fts3EvalLoadDeferred(pCsr, &rc) 
116268       );
116269
116270       if( rc==SQLITE_OK && pCsr->isEof==0 ){
116271         fts3EvalUpdateCounts(pRoot);
116272       }
116273     }
116274
116275     pCsr->isEof = 0;
116276     pCsr->iPrevId = iPrevId;
116277
116278     if( bEof ){
116279       pRoot->bEof = bEof;
116280     }else{
116281       /* Caution: pRoot may iterate through docids in ascending or descending
116282       ** order. For this reason, even though it seems more defensive, the 
116283       ** do loop can not be written:
116284       **
116285       **   do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
116286       */
116287       fts3EvalRestart(pCsr, pRoot, &rc);
116288       do {
116289         fts3EvalNext(pCsr, pRoot, &rc);
116290         assert( pRoot->bEof==0 );
116291       }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
116292       fts3EvalLoadDeferred(pCsr, &rc);
116293     }
116294   }
116295   return rc;
116296 }
116297
116298 /*
116299 ** This function is used by the matchinfo() module to query a phrase 
116300 ** expression node for the following information:
116301 **
116302 **   1. The total number of occurrences of the phrase in each column of 
116303 **      the FTS table (considering all rows), and
116304 **
116305 **   2. For each column, the number of rows in the table for which the
116306 **      column contains at least one instance of the phrase.
116307 **
116308 ** If no error occurs, SQLITE_OK is returned and the values for each column
116309 ** written into the array aiOut as follows:
116310 **
116311 **   aiOut[iCol*3 + 1] = Number of occurrences
116312 **   aiOut[iCol*3 + 2] = Number of rows containing at least one instance
116313 **
116314 ** Caveats:
116315 **
116316 **   * If a phrase consists entirely of deferred tokens, then all output 
116317 **     values are set to the number of documents in the table. In other
116318 **     words we assume that very common tokens occur exactly once in each 
116319 **     column of each row of the table.
116320 **
116321 **   * If a phrase contains some deferred tokens (and some non-deferred 
116322 **     tokens), count the potential occurrence identified by considering
116323 **     the non-deferred tokens instead of actual phrase occurrences.
116324 **
116325 **   * If the phrase is part of a NEAR expression, then only phrase instances
116326 **     that meet the NEAR constraint are included in the counts.
116327 */
116328 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
116329   Fts3Cursor *pCsr,               /* FTS cursor handle */
116330   Fts3Expr *pExpr,                /* Phrase expression */
116331   u32 *aiOut                      /* Array to write results into (see above) */
116332 ){
116333   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
116334   int rc = SQLITE_OK;
116335   int iCol;
116336
116337   if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
116338     assert( pCsr->nDoc>0 );
116339     for(iCol=0; iCol<pTab->nColumn; iCol++){
116340       aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
116341       aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
116342     }
116343   }else{
116344     rc = fts3EvalGatherStats(pCsr, pExpr);
116345     if( rc==SQLITE_OK ){
116346       assert( pExpr->aMI );
116347       for(iCol=0; iCol<pTab->nColumn; iCol++){
116348         aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
116349         aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
116350       }
116351     }
116352   }
116353
116354   return rc;
116355 }
116356
116357 /*
116358 ** The expression pExpr passed as the second argument to this function
116359 ** must be of type FTSQUERY_PHRASE. 
116360 **
116361 ** The returned value is either NULL or a pointer to a buffer containing
116362 ** a position-list indicating the occurrences of the phrase in column iCol
116363 ** of the current row. 
116364 **
116365 ** More specifically, the returned buffer contains 1 varint for each 
116366 ** occurence of the phrase in the column, stored using the normal (delta+2) 
116367 ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
116368 ** if the requested column contains "a b X c d X X" and the position-list
116369 ** for 'X' is requested, the buffer returned may contain:
116370 **
116371 **     0x04 0x05 0x03 0x01   or   0x04 0x05 0x03 0x00
116372 **
116373 ** This function works regardless of whether or not the phrase is deferred,
116374 ** incremental, or neither.
116375 */
116376 SQLITE_PRIVATE char *sqlite3Fts3EvalPhrasePoslist(
116377   Fts3Cursor *pCsr,               /* FTS3 cursor object */
116378   Fts3Expr *pExpr,                /* Phrase to return doclist for */
116379   int iCol                        /* Column to return position list for */
116380 ){
116381   Fts3Phrase *pPhrase = pExpr->pPhrase;
116382   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
116383   char *pIter = pPhrase->doclist.pList;
116384   int iThis;
116385
116386   assert( iCol>=0 && iCol<pTab->nColumn );
116387   if( !pIter 
116388    || pExpr->bEof 
116389    || pExpr->iDocid!=pCsr->iPrevId
116390    || (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) 
116391   ){
116392     return 0;
116393   }
116394
116395   assert( pPhrase->doclist.nList>0 );
116396   if( *pIter==0x01 ){
116397     pIter++;
116398     pIter += sqlite3Fts3GetVarint32(pIter, &iThis);
116399   }else{
116400     iThis = 0;
116401   }
116402   while( iThis<iCol ){
116403     fts3ColumnlistCopy(0, &pIter);
116404     if( *pIter==0x00 ) return 0;
116405     pIter++;
116406     pIter += sqlite3Fts3GetVarint32(pIter, &iThis);
116407   }
116408
116409   return ((iCol==iThis)?pIter:0);
116410 }
116411
116412 /*
116413 ** Free all components of the Fts3Phrase structure that were allocated by
116414 ** the eval module. Specifically, this means to free:
116415 **
116416 **   * the contents of pPhrase->doclist, and
116417 **   * any Fts3MultiSegReader objects held by phrase tokens.
116418 */
116419 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
116420   if( pPhrase ){
116421     int i;
116422     sqlite3_free(pPhrase->doclist.aAll);
116423     fts3EvalZeroPoslist(pPhrase);
116424     memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
116425     for(i=0; i<pPhrase->nToken; i++){
116426       fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
116427       pPhrase->aToken[i].pSegcsr = 0;
116428     }
116429   }
116430 }
116431
116432 #endif
116433
116434 /************** End of fts3.c ************************************************/
116435 /************** Begin file fts3_aux.c ****************************************/
116436 /*
116437 ** 2011 Jan 27
116438 **
116439 ** The author disclaims copyright to this source code.  In place of
116440 ** a legal notice, here is a blessing:
116441 **
116442 **    May you do good and not evil.
116443 **    May you find forgiveness for yourself and forgive others.
116444 **    May you share freely, never taking more than you give.
116445 **
116446 ******************************************************************************
116447 **
116448 */
116449 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
116450
116451
116452 typedef struct Fts3auxTable Fts3auxTable;
116453 typedef struct Fts3auxCursor Fts3auxCursor;
116454
116455 struct Fts3auxTable {
116456   sqlite3_vtab base;              /* Base class used by SQLite core */
116457   Fts3Table *pFts3Tab;
116458 };
116459
116460 struct Fts3auxCursor {
116461   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
116462   Fts3MultiSegReader csr;        /* Must be right after "base" */
116463   Fts3SegFilter filter;
116464   char *zStop;
116465   int nStop;                      /* Byte-length of string zStop */
116466   int isEof;                      /* True if cursor is at EOF */
116467   sqlite3_int64 iRowid;           /* Current rowid */
116468
116469   int iCol;                       /* Current value of 'col' column */
116470   int nStat;                      /* Size of aStat[] array */
116471   struct Fts3auxColstats {
116472     sqlite3_int64 nDoc;           /* 'documents' values for current csr row */
116473     sqlite3_int64 nOcc;           /* 'occurrences' values for current csr row */
116474   } *aStat;
116475 };
116476
116477 /*
116478 ** Schema of the terms table.
116479 */
116480 #define FTS3_TERMS_SCHEMA "CREATE TABLE x(term, col, documents, occurrences)"
116481
116482 /*
116483 ** This function does all the work for both the xConnect and xCreate methods.
116484 ** These tables have no persistent representation of their own, so xConnect
116485 ** and xCreate are identical operations.
116486 */
116487 static int fts3auxConnectMethod(
116488   sqlite3 *db,                    /* Database connection */
116489   void *pUnused,                  /* Unused */
116490   int argc,                       /* Number of elements in argv array */
116491   const char * const *argv,       /* xCreate/xConnect argument array */
116492   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
116493   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
116494 ){
116495   char const *zDb;                /* Name of database (e.g. "main") */
116496   char const *zFts3;              /* Name of fts3 table */
116497   int nDb;                        /* Result of strlen(zDb) */
116498   int nFts3;                      /* Result of strlen(zFts3) */
116499   int nByte;                      /* Bytes of space to allocate here */
116500   int rc;                         /* value returned by declare_vtab() */
116501   Fts3auxTable *p;                /* Virtual table object to return */
116502
116503   UNUSED_PARAMETER(pUnused);
116504
116505   /* The user should specify a single argument - the name of an fts3 table. */
116506   if( argc!=4 ){
116507     *pzErr = sqlite3_mprintf(
116508         "wrong number of arguments to fts4aux constructor"
116509     );
116510     return SQLITE_ERROR;
116511   }
116512
116513   zDb = argv[1]; 
116514   nDb = strlen(zDb);
116515   zFts3 = argv[3];
116516   nFts3 = strlen(zFts3);
116517
116518   rc = sqlite3_declare_vtab(db, FTS3_TERMS_SCHEMA);
116519   if( rc!=SQLITE_OK ) return rc;
116520
116521   nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
116522   p = (Fts3auxTable *)sqlite3_malloc(nByte);
116523   if( !p ) return SQLITE_NOMEM;
116524   memset(p, 0, nByte);
116525
116526   p->pFts3Tab = (Fts3Table *)&p[1];
116527   p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
116528   p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
116529   p->pFts3Tab->db = db;
116530   p->pFts3Tab->nIndex = 1;
116531
116532   memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
116533   memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
116534   sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
116535
116536   *ppVtab = (sqlite3_vtab *)p;
116537   return SQLITE_OK;
116538 }
116539
116540 /*
116541 ** This function does the work for both the xDisconnect and xDestroy methods.
116542 ** These tables have no persistent representation of their own, so xDisconnect
116543 ** and xDestroy are identical operations.
116544 */
116545 static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
116546   Fts3auxTable *p = (Fts3auxTable *)pVtab;
116547   Fts3Table *pFts3 = p->pFts3Tab;
116548   int i;
116549
116550   /* Free any prepared statements held */
116551   for(i=0; i<SizeofArray(pFts3->aStmt); i++){
116552     sqlite3_finalize(pFts3->aStmt[i]);
116553   }
116554   sqlite3_free(pFts3->zSegmentsTbl);
116555   sqlite3_free(p);
116556   return SQLITE_OK;
116557 }
116558
116559 #define FTS4AUX_EQ_CONSTRAINT 1
116560 #define FTS4AUX_GE_CONSTRAINT 2
116561 #define FTS4AUX_LE_CONSTRAINT 4
116562
116563 /*
116564 ** xBestIndex - Analyze a WHERE and ORDER BY clause.
116565 */
116566 static int fts3auxBestIndexMethod(
116567   sqlite3_vtab *pVTab, 
116568   sqlite3_index_info *pInfo
116569 ){
116570   int i;
116571   int iEq = -1;
116572   int iGe = -1;
116573   int iLe = -1;
116574
116575   UNUSED_PARAMETER(pVTab);
116576
116577   /* This vtab delivers always results in "ORDER BY term ASC" order. */
116578   if( pInfo->nOrderBy==1 
116579    && pInfo->aOrderBy[0].iColumn==0 
116580    && pInfo->aOrderBy[0].desc==0
116581   ){
116582     pInfo->orderByConsumed = 1;
116583   }
116584
116585   /* Search for equality and range constraints on the "term" column. */
116586   for(i=0; i<pInfo->nConstraint; i++){
116587     if( pInfo->aConstraint[i].usable && pInfo->aConstraint[i].iColumn==0 ){
116588       int op = pInfo->aConstraint[i].op;
116589       if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
116590       if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
116591       if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
116592       if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
116593       if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
116594     }
116595   }
116596
116597   if( iEq>=0 ){
116598     pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
116599     pInfo->aConstraintUsage[iEq].argvIndex = 1;
116600     pInfo->estimatedCost = 5;
116601   }else{
116602     pInfo->idxNum = 0;
116603     pInfo->estimatedCost = 20000;
116604     if( iGe>=0 ){
116605       pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
116606       pInfo->aConstraintUsage[iGe].argvIndex = 1;
116607       pInfo->estimatedCost /= 2;
116608     }
116609     if( iLe>=0 ){
116610       pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
116611       pInfo->aConstraintUsage[iLe].argvIndex = 1 + (iGe>=0);
116612       pInfo->estimatedCost /= 2;
116613     }
116614   }
116615
116616   return SQLITE_OK;
116617 }
116618
116619 /*
116620 ** xOpen - Open a cursor.
116621 */
116622 static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
116623   Fts3auxCursor *pCsr;            /* Pointer to cursor object to return */
116624
116625   UNUSED_PARAMETER(pVTab);
116626
116627   pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
116628   if( !pCsr ) return SQLITE_NOMEM;
116629   memset(pCsr, 0, sizeof(Fts3auxCursor));
116630
116631   *ppCsr = (sqlite3_vtab_cursor *)pCsr;
116632   return SQLITE_OK;
116633 }
116634
116635 /*
116636 ** xClose - Close a cursor.
116637 */
116638 static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
116639   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
116640   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
116641
116642   sqlite3Fts3SegmentsClose(pFts3);
116643   sqlite3Fts3SegReaderFinish(&pCsr->csr);
116644   sqlite3_free((void *)pCsr->filter.zTerm);
116645   sqlite3_free(pCsr->zStop);
116646   sqlite3_free(pCsr->aStat);
116647   sqlite3_free(pCsr);
116648   return SQLITE_OK;
116649 }
116650
116651 static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
116652   if( nSize>pCsr->nStat ){
116653     struct Fts3auxColstats *aNew;
116654     aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat, 
116655         sizeof(struct Fts3auxColstats) * nSize
116656     );
116657     if( aNew==0 ) return SQLITE_NOMEM;
116658     memset(&aNew[pCsr->nStat], 0, 
116659         sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
116660     );
116661     pCsr->aStat = aNew;
116662     pCsr->nStat = nSize;
116663   }
116664   return SQLITE_OK;
116665 }
116666
116667 /*
116668 ** xNext - Advance the cursor to the next row, if any.
116669 */
116670 static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
116671   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
116672   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
116673   int rc;
116674
116675   /* Increment our pretend rowid value. */
116676   pCsr->iRowid++;
116677
116678   for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
116679     if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
116680   }
116681
116682   rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
116683   if( rc==SQLITE_ROW ){
116684     int i = 0;
116685     int nDoclist = pCsr->csr.nDoclist;
116686     char *aDoclist = pCsr->csr.aDoclist;
116687     int iCol;
116688
116689     int eState = 0;
116690
116691     if( pCsr->zStop ){
116692       int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
116693       int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
116694       if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
116695         pCsr->isEof = 1;
116696         return SQLITE_OK;
116697       }
116698     }
116699
116700     if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
116701     memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
116702     iCol = 0;
116703
116704     while( i<nDoclist ){
116705       sqlite3_int64 v = 0;
116706
116707       i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
116708       switch( eState ){
116709         /* State 0. In this state the integer just read was a docid. */
116710         case 0:
116711           pCsr->aStat[0].nDoc++;
116712           eState = 1;
116713           iCol = 0;
116714           break;
116715
116716         /* State 1. In this state we are expecting either a 1, indicating
116717         ** that the following integer will be a column number, or the
116718         ** start of a position list for column 0.  
116719         ** 
116720         ** The only difference between state 1 and state 2 is that if the
116721         ** integer encountered in state 1 is not 0 or 1, then we need to
116722         ** increment the column 0 "nDoc" count for this term.
116723         */
116724         case 1:
116725           assert( iCol==0 );
116726           if( v>1 ){
116727             pCsr->aStat[1].nDoc++;
116728           }
116729           eState = 2;
116730           /* fall through */
116731
116732         case 2:
116733           if( v==0 ){       /* 0x00. Next integer will be a docid. */
116734             eState = 0;
116735           }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
116736             eState = 3;
116737           }else{            /* 2 or greater. A position. */
116738             pCsr->aStat[iCol+1].nOcc++;
116739             pCsr->aStat[0].nOcc++;
116740           }
116741           break;
116742
116743         /* State 3. The integer just read is a column number. */
116744         default: assert( eState==3 );
116745           iCol = (int)v;
116746           if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
116747           pCsr->aStat[iCol+1].nDoc++;
116748           eState = 2;
116749           break;
116750       }
116751     }
116752
116753     pCsr->iCol = 0;
116754     rc = SQLITE_OK;
116755   }else{
116756     pCsr->isEof = 1;
116757   }
116758   return rc;
116759 }
116760
116761 /*
116762 ** xFilter - Initialize a cursor to point at the start of its data.
116763 */
116764 static int fts3auxFilterMethod(
116765   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
116766   int idxNum,                     /* Strategy index */
116767   const char *idxStr,             /* Unused */
116768   int nVal,                       /* Number of elements in apVal */
116769   sqlite3_value **apVal           /* Arguments for the indexing scheme */
116770 ){
116771   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
116772   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
116773   int rc;
116774   int isScan;
116775
116776   UNUSED_PARAMETER(nVal);
116777   UNUSED_PARAMETER(idxStr);
116778
116779   assert( idxStr==0 );
116780   assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
116781        || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
116782        || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
116783   );
116784   isScan = (idxNum!=FTS4AUX_EQ_CONSTRAINT);
116785
116786   /* In case this cursor is being reused, close and zero it. */
116787   testcase(pCsr->filter.zTerm);
116788   sqlite3Fts3SegReaderFinish(&pCsr->csr);
116789   sqlite3_free((void *)pCsr->filter.zTerm);
116790   sqlite3_free(pCsr->aStat);
116791   memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
116792
116793   pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
116794   if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
116795
116796   if( idxNum&(FTS4AUX_EQ_CONSTRAINT|FTS4AUX_GE_CONSTRAINT) ){
116797     const unsigned char *zStr = sqlite3_value_text(apVal[0]);
116798     if( zStr ){
116799       pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
116800       pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
116801       if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
116802     }
116803   }
116804   if( idxNum&FTS4AUX_LE_CONSTRAINT ){
116805     int iIdx = (idxNum&FTS4AUX_GE_CONSTRAINT) ? 1 : 0;
116806     pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iIdx]));
116807     pCsr->nStop = sqlite3_value_bytes(apVal[iIdx]);
116808     if( pCsr->zStop==0 ) return SQLITE_NOMEM;
116809   }
116810
116811   rc = sqlite3Fts3SegReaderCursor(pFts3, 0, FTS3_SEGCURSOR_ALL,
116812       pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
116813   );
116814   if( rc==SQLITE_OK ){
116815     rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
116816   }
116817
116818   if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
116819   return rc;
116820 }
116821
116822 /*
116823 ** xEof - Return true if the cursor is at EOF, or false otherwise.
116824 */
116825 static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
116826   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
116827   return pCsr->isEof;
116828 }
116829
116830 /*
116831 ** xColumn - Return a column value.
116832 */
116833 static int fts3auxColumnMethod(
116834   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
116835   sqlite3_context *pContext,      /* Context for sqlite3_result_xxx() calls */
116836   int iCol                        /* Index of column to read value from */
116837 ){
116838   Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
116839
116840   assert( p->isEof==0 );
116841   if( iCol==0 ){        /* Column "term" */
116842     sqlite3_result_text(pContext, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
116843   }else if( iCol==1 ){  /* Column "col" */
116844     if( p->iCol ){
116845       sqlite3_result_int(pContext, p->iCol-1);
116846     }else{
116847       sqlite3_result_text(pContext, "*", -1, SQLITE_STATIC);
116848     }
116849   }else if( iCol==2 ){  /* Column "documents" */
116850     sqlite3_result_int64(pContext, p->aStat[p->iCol].nDoc);
116851   }else{                /* Column "occurrences" */
116852     sqlite3_result_int64(pContext, p->aStat[p->iCol].nOcc);
116853   }
116854
116855   return SQLITE_OK;
116856 }
116857
116858 /*
116859 ** xRowid - Return the current rowid for the cursor.
116860 */
116861 static int fts3auxRowidMethod(
116862   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
116863   sqlite_int64 *pRowid            /* OUT: Rowid value */
116864 ){
116865   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
116866   *pRowid = pCsr->iRowid;
116867   return SQLITE_OK;
116868 }
116869
116870 /*
116871 ** Register the fts3aux module with database connection db. Return SQLITE_OK
116872 ** if successful or an error code if sqlite3_create_module() fails.
116873 */
116874 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
116875   static const sqlite3_module fts3aux_module = {
116876      0,                           /* iVersion      */
116877      fts3auxConnectMethod,        /* xCreate       */
116878      fts3auxConnectMethod,        /* xConnect      */
116879      fts3auxBestIndexMethod,      /* xBestIndex    */
116880      fts3auxDisconnectMethod,     /* xDisconnect   */
116881      fts3auxDisconnectMethod,     /* xDestroy      */
116882      fts3auxOpenMethod,           /* xOpen         */
116883      fts3auxCloseMethod,          /* xClose        */
116884      fts3auxFilterMethod,         /* xFilter       */
116885      fts3auxNextMethod,           /* xNext         */
116886      fts3auxEofMethod,            /* xEof          */
116887      fts3auxColumnMethod,         /* xColumn       */
116888      fts3auxRowidMethod,          /* xRowid        */
116889      0,                           /* xUpdate       */
116890      0,                           /* xBegin        */
116891      0,                           /* xSync         */
116892      0,                           /* xCommit       */
116893      0,                           /* xRollback     */
116894      0,                           /* xFindFunction */
116895      0,                           /* xRename       */
116896      0,                           /* xSavepoint    */
116897      0,                           /* xRelease      */
116898      0                            /* xRollbackTo   */
116899   };
116900   int rc;                         /* Return code */
116901
116902   rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
116903   return rc;
116904 }
116905
116906 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
116907
116908 /************** End of fts3_aux.c ********************************************/
116909 /************** Begin file fts3_expr.c ***************************************/
116910 /*
116911 ** 2008 Nov 28
116912 **
116913 ** The author disclaims copyright to this source code.  In place of
116914 ** a legal notice, here is a blessing:
116915 **
116916 **    May you do good and not evil.
116917 **    May you find forgiveness for yourself and forgive others.
116918 **    May you share freely, never taking more than you give.
116919 **
116920 ******************************************************************************
116921 **
116922 ** This module contains code that implements a parser for fts3 query strings
116923 ** (the right-hand argument to the MATCH operator). Because the supported 
116924 ** syntax is relatively simple, the whole tokenizer/parser system is
116925 ** hand-coded. 
116926 */
116927 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
116928
116929 /*
116930 ** By default, this module parses the legacy syntax that has been 
116931 ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
116932 ** is defined, then it uses the new syntax. The differences between
116933 ** the new and the old syntaxes are:
116934 **
116935 **  a) The new syntax supports parenthesis. The old does not.
116936 **
116937 **  b) The new syntax supports the AND and NOT operators. The old does not.
116938 **
116939 **  c) The old syntax supports the "-" token qualifier. This is not 
116940 **     supported by the new syntax (it is replaced by the NOT operator).
116941 **
116942 **  d) When using the old syntax, the OR operator has a greater precedence
116943 **     than an implicit AND. When using the new, both implicity and explicit
116944 **     AND operators have a higher precedence than OR.
116945 **
116946 ** If compiled with SQLITE_TEST defined, then this module exports the
116947 ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
116948 ** to zero causes the module to use the old syntax. If it is set to 
116949 ** non-zero the new syntax is activated. This is so both syntaxes can
116950 ** be tested using a single build of testfixture.
116951 **
116952 ** The following describes the syntax supported by the fts3 MATCH
116953 ** operator in a similar format to that used by the lemon parser
116954 ** generator. This module does not use actually lemon, it uses a
116955 ** custom parser.
116956 **
116957 **   query ::= andexpr (OR andexpr)*.
116958 **
116959 **   andexpr ::= notexpr (AND? notexpr)*.
116960 **
116961 **   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
116962 **   notexpr ::= LP query RP.
116963 **
116964 **   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
116965 **
116966 **   distance_opt ::= .
116967 **   distance_opt ::= / INTEGER.
116968 **
116969 **   phrase ::= TOKEN.
116970 **   phrase ::= COLUMN:TOKEN.
116971 **   phrase ::= "TOKEN TOKEN TOKEN...".
116972 */
116973
116974 #ifdef SQLITE_TEST
116975 SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
116976 #else
116977 # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS 
116978 #  define sqlite3_fts3_enable_parentheses 1
116979 # else
116980 #  define sqlite3_fts3_enable_parentheses 0
116981 # endif
116982 #endif
116983
116984 /*
116985 ** Default span for NEAR operators.
116986 */
116987 #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
116988
116989
116990 /*
116991 ** isNot:
116992 **   This variable is used by function getNextNode(). When getNextNode() is
116993 **   called, it sets ParseContext.isNot to true if the 'next node' is a 
116994 **   FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
116995 **   FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
116996 **   zero.
116997 */
116998 typedef struct ParseContext ParseContext;
116999 struct ParseContext {
117000   sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
117001   const char **azCol;                 /* Array of column names for fts3 table */
117002   int nCol;                           /* Number of entries in azCol[] */
117003   int iDefaultCol;                    /* Default column to query */
117004   int isNot;                          /* True if getNextNode() sees a unary - */
117005   sqlite3_context *pCtx;              /* Write error message here */
117006   int nNest;                          /* Number of nested brackets */
117007 };
117008
117009 /*
117010 ** This function is equivalent to the standard isspace() function. 
117011 **
117012 ** The standard isspace() can be awkward to use safely, because although it
117013 ** is defined to accept an argument of type int, its behaviour when passed
117014 ** an integer that falls outside of the range of the unsigned char type
117015 ** is undefined (and sometimes, "undefined" means segfault). This wrapper
117016 ** is defined to accept an argument of type char, and always returns 0 for
117017 ** any values that fall outside of the range of the unsigned char type (i.e.
117018 ** negative values).
117019 */
117020 static int fts3isspace(char c){
117021   return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
117022 }
117023
117024 /*
117025 ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
117026 ** zero the memory before returning a pointer to it. If unsuccessful, 
117027 ** return NULL.
117028 */
117029 static void *fts3MallocZero(int nByte){
117030   void *pRet = sqlite3_malloc(nByte);
117031   if( pRet ) memset(pRet, 0, nByte);
117032   return pRet;
117033 }
117034
117035
117036 /*
117037 ** Extract the next token from buffer z (length n) using the tokenizer
117038 ** and other information (column names etc.) in pParse. Create an Fts3Expr
117039 ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
117040 ** single token and set *ppExpr to point to it. If the end of the buffer is
117041 ** reached before a token is found, set *ppExpr to zero. It is the
117042 ** responsibility of the caller to eventually deallocate the allocated 
117043 ** Fts3Expr structure (if any) by passing it to sqlite3_free().
117044 **
117045 ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
117046 ** fails.
117047 */
117048 static int getNextToken(
117049   ParseContext *pParse,                   /* fts3 query parse context */
117050   int iCol,                               /* Value for Fts3Phrase.iColumn */
117051   const char *z, int n,                   /* Input string */
117052   Fts3Expr **ppExpr,                      /* OUT: expression */
117053   int *pnConsumed                         /* OUT: Number of bytes consumed */
117054 ){
117055   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
117056   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
117057   int rc;
117058   sqlite3_tokenizer_cursor *pCursor;
117059   Fts3Expr *pRet = 0;
117060   int nConsumed = 0;
117061
117062   rc = pModule->xOpen(pTokenizer, z, n, &pCursor);
117063   if( rc==SQLITE_OK ){
117064     const char *zToken;
117065     int nToken, iStart, iEnd, iPosition;
117066     int nByte;                               /* total space to allocate */
117067
117068     pCursor->pTokenizer = pTokenizer;
117069     rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
117070
117071     if( rc==SQLITE_OK ){
117072       nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
117073       pRet = (Fts3Expr *)fts3MallocZero(nByte);
117074       if( !pRet ){
117075         rc = SQLITE_NOMEM;
117076       }else{
117077         pRet->eType = FTSQUERY_PHRASE;
117078         pRet->pPhrase = (Fts3Phrase *)&pRet[1];
117079         pRet->pPhrase->nToken = 1;
117080         pRet->pPhrase->iColumn = iCol;
117081         pRet->pPhrase->aToken[0].n = nToken;
117082         pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
117083         memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
117084
117085         if( iEnd<n && z[iEnd]=='*' ){
117086           pRet->pPhrase->aToken[0].isPrefix = 1;
117087           iEnd++;
117088         }
117089         if( !sqlite3_fts3_enable_parentheses && iStart>0 && z[iStart-1]=='-' ){
117090           pParse->isNot = 1;
117091         }
117092       }
117093       nConsumed = iEnd;
117094     }
117095
117096     pModule->xClose(pCursor);
117097   }
117098   
117099   *pnConsumed = nConsumed;
117100   *ppExpr = pRet;
117101   return rc;
117102 }
117103
117104
117105 /*
117106 ** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
117107 ** then free the old allocation.
117108 */
117109 static void *fts3ReallocOrFree(void *pOrig, int nNew){
117110   void *pRet = sqlite3_realloc(pOrig, nNew);
117111   if( !pRet ){
117112     sqlite3_free(pOrig);
117113   }
117114   return pRet;
117115 }
117116
117117 /*
117118 ** Buffer zInput, length nInput, contains the contents of a quoted string
117119 ** that appeared as part of an fts3 query expression. Neither quote character
117120 ** is included in the buffer. This function attempts to tokenize the entire
117121 ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE 
117122 ** containing the results.
117123 **
117124 ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
117125 ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
117126 ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
117127 ** to 0.
117128 */
117129 static int getNextString(
117130   ParseContext *pParse,                   /* fts3 query parse context */
117131   const char *zInput, int nInput,         /* Input string */
117132   Fts3Expr **ppExpr                       /* OUT: expression */
117133 ){
117134   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
117135   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
117136   int rc;
117137   Fts3Expr *p = 0;
117138   sqlite3_tokenizer_cursor *pCursor = 0;
117139   char *zTemp = 0;
117140   int nTemp = 0;
117141
117142   const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
117143   int nToken = 0;
117144
117145   /* The final Fts3Expr data structure, including the Fts3Phrase,
117146   ** Fts3PhraseToken structures token buffers are all stored as a single 
117147   ** allocation so that the expression can be freed with a single call to
117148   ** sqlite3_free(). Setting this up requires a two pass approach.
117149   **
117150   ** The first pass, in the block below, uses a tokenizer cursor to iterate
117151   ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
117152   ** to assemble data in two dynamic buffers:
117153   **
117154   **   Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
117155   **             structure, followed by the array of Fts3PhraseToken 
117156   **             structures. This pass only populates the Fts3PhraseToken array.
117157   **
117158   **   Buffer zTemp: Contains copies of all tokens.
117159   **
117160   ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
117161   ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
117162   ** structures.
117163   */
117164   rc = pModule->xOpen(pTokenizer, zInput, nInput, &pCursor);
117165   if( rc==SQLITE_OK ){
117166     int ii;
117167     pCursor->pTokenizer = pTokenizer;
117168     for(ii=0; rc==SQLITE_OK; ii++){
117169       const char *zByte;
117170       int nByte, iBegin, iEnd, iPos;
117171       rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
117172       if( rc==SQLITE_OK ){
117173         Fts3PhraseToken *pToken;
117174
117175         p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
117176         if( !p ) goto no_mem;
117177
117178         zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
117179         if( !zTemp ) goto no_mem;
117180
117181         assert( nToken==ii );
117182         pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
117183         memset(pToken, 0, sizeof(Fts3PhraseToken));
117184
117185         memcpy(&zTemp[nTemp], zByte, nByte);
117186         nTemp += nByte;
117187
117188         pToken->n = nByte;
117189         pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
117190         nToken = ii+1;
117191       }
117192     }
117193
117194     pModule->xClose(pCursor);
117195     pCursor = 0;
117196   }
117197
117198   if( rc==SQLITE_DONE ){
117199     int jj;
117200     char *zBuf = 0;
117201
117202     p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
117203     if( !p ) goto no_mem;
117204     memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
117205     p->eType = FTSQUERY_PHRASE;
117206     p->pPhrase = (Fts3Phrase *)&p[1];
117207     p->pPhrase->iColumn = pParse->iDefaultCol;
117208     p->pPhrase->nToken = nToken;
117209
117210     zBuf = (char *)&p->pPhrase->aToken[nToken];
117211     memcpy(zBuf, zTemp, nTemp);
117212     sqlite3_free(zTemp);
117213
117214     for(jj=0; jj<p->pPhrase->nToken; jj++){
117215       p->pPhrase->aToken[jj].z = zBuf;
117216       zBuf += p->pPhrase->aToken[jj].n;
117217     }
117218     rc = SQLITE_OK;
117219   }
117220
117221   *ppExpr = p;
117222   return rc;
117223 no_mem:
117224
117225   if( pCursor ){
117226     pModule->xClose(pCursor);
117227   }
117228   sqlite3_free(zTemp);
117229   sqlite3_free(p);
117230   *ppExpr = 0;
117231   return SQLITE_NOMEM;
117232 }
117233
117234 /*
117235 ** Function getNextNode(), which is called by fts3ExprParse(), may itself
117236 ** call fts3ExprParse(). So this forward declaration is required.
117237 */
117238 static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
117239
117240 /*
117241 ** The output variable *ppExpr is populated with an allocated Fts3Expr 
117242 ** structure, or set to 0 if the end of the input buffer is reached.
117243 **
117244 ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
117245 ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
117246 ** If SQLITE_ERROR is returned, pContext is populated with an error message.
117247 */
117248 static int getNextNode(
117249   ParseContext *pParse,                   /* fts3 query parse context */
117250   const char *z, int n,                   /* Input string */
117251   Fts3Expr **ppExpr,                      /* OUT: expression */
117252   int *pnConsumed                         /* OUT: Number of bytes consumed */
117253 ){
117254   static const struct Fts3Keyword {
117255     char *z;                              /* Keyword text */
117256     unsigned char n;                      /* Length of the keyword */
117257     unsigned char parenOnly;              /* Only valid in paren mode */
117258     unsigned char eType;                  /* Keyword code */
117259   } aKeyword[] = {
117260     { "OR" ,  2, 0, FTSQUERY_OR   },
117261     { "AND",  3, 1, FTSQUERY_AND  },
117262     { "NOT",  3, 1, FTSQUERY_NOT  },
117263     { "NEAR", 4, 0, FTSQUERY_NEAR }
117264   };
117265   int ii;
117266   int iCol;
117267   int iColLen;
117268   int rc;
117269   Fts3Expr *pRet = 0;
117270
117271   const char *zInput = z;
117272   int nInput = n;
117273
117274   pParse->isNot = 0;
117275
117276   /* Skip over any whitespace before checking for a keyword, an open or
117277   ** close bracket, or a quoted string. 
117278   */
117279   while( nInput>0 && fts3isspace(*zInput) ){
117280     nInput--;
117281     zInput++;
117282   }
117283   if( nInput==0 ){
117284     return SQLITE_DONE;
117285   }
117286
117287   /* See if we are dealing with a keyword. */
117288   for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
117289     const struct Fts3Keyword *pKey = &aKeyword[ii];
117290
117291     if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
117292       continue;
117293     }
117294
117295     if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
117296       int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
117297       int nKey = pKey->n;
117298       char cNext;
117299
117300       /* If this is a "NEAR" keyword, check for an explicit nearness. */
117301       if( pKey->eType==FTSQUERY_NEAR ){
117302         assert( nKey==4 );
117303         if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
117304           nNear = 0;
117305           for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
117306             nNear = nNear * 10 + (zInput[nKey] - '0');
117307           }
117308         }
117309       }
117310
117311       /* At this point this is probably a keyword. But for that to be true,
117312       ** the next byte must contain either whitespace, an open or close
117313       ** parenthesis, a quote character, or EOF. 
117314       */
117315       cNext = zInput[nKey];
117316       if( fts3isspace(cNext) 
117317        || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
117318       ){
117319         pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
117320         if( !pRet ){
117321           return SQLITE_NOMEM;
117322         }
117323         pRet->eType = pKey->eType;
117324         pRet->nNear = nNear;
117325         *ppExpr = pRet;
117326         *pnConsumed = (int)((zInput - z) + nKey);
117327         return SQLITE_OK;
117328       }
117329
117330       /* Turns out that wasn't a keyword after all. This happens if the
117331       ** user has supplied a token such as "ORacle". Continue.
117332       */
117333     }
117334   }
117335
117336   /* Check for an open bracket. */
117337   if( sqlite3_fts3_enable_parentheses ){
117338     if( *zInput=='(' ){
117339       int nConsumed;
117340       pParse->nNest++;
117341       rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);
117342       if( rc==SQLITE_OK && !*ppExpr ){
117343         rc = SQLITE_DONE;
117344       }
117345       *pnConsumed = (int)((zInput - z) + 1 + nConsumed);
117346       return rc;
117347     }
117348   
117349     /* Check for a close bracket. */
117350     if( *zInput==')' ){
117351       pParse->nNest--;
117352       *pnConsumed = (int)((zInput - z) + 1);
117353       return SQLITE_DONE;
117354     }
117355   }
117356
117357   /* See if we are dealing with a quoted phrase. If this is the case, then
117358   ** search for the closing quote and pass the whole string to getNextString()
117359   ** for processing. This is easy to do, as fts3 has no syntax for escaping
117360   ** a quote character embedded in a string.
117361   */
117362   if( *zInput=='"' ){
117363     for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
117364     *pnConsumed = (int)((zInput - z) + ii + 1);
117365     if( ii==nInput ){
117366       return SQLITE_ERROR;
117367     }
117368     return getNextString(pParse, &zInput[1], ii-1, ppExpr);
117369   }
117370
117371
117372   /* If control flows to this point, this must be a regular token, or 
117373   ** the end of the input. Read a regular token using the sqlite3_tokenizer
117374   ** interface. Before doing so, figure out if there is an explicit
117375   ** column specifier for the token. 
117376   **
117377   ** TODO: Strangely, it is not possible to associate a column specifier
117378   ** with a quoted phrase, only with a single token. Not sure if this was
117379   ** an implementation artifact or an intentional decision when fts3 was
117380   ** first implemented. Whichever it was, this module duplicates the 
117381   ** limitation.
117382   */
117383   iCol = pParse->iDefaultCol;
117384   iColLen = 0;
117385   for(ii=0; ii<pParse->nCol; ii++){
117386     const char *zStr = pParse->azCol[ii];
117387     int nStr = (int)strlen(zStr);
117388     if( nInput>nStr && zInput[nStr]==':' 
117389      && sqlite3_strnicmp(zStr, zInput, nStr)==0 
117390     ){
117391       iCol = ii;
117392       iColLen = (int)((zInput - z) + nStr + 1);
117393       break;
117394     }
117395   }
117396   rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
117397   *pnConsumed += iColLen;
117398   return rc;
117399 }
117400
117401 /*
117402 ** The argument is an Fts3Expr structure for a binary operator (any type
117403 ** except an FTSQUERY_PHRASE). Return an integer value representing the
117404 ** precedence of the operator. Lower values have a higher precedence (i.e.
117405 ** group more tightly). For example, in the C language, the == operator
117406 ** groups more tightly than ||, and would therefore have a higher precedence.
117407 **
117408 ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
117409 ** is defined), the order of the operators in precedence from highest to
117410 ** lowest is:
117411 **
117412 **   NEAR
117413 **   NOT
117414 **   AND (including implicit ANDs)
117415 **   OR
117416 **
117417 ** Note that when using the old query syntax, the OR operator has a higher
117418 ** precedence than the AND operator.
117419 */
117420 static int opPrecedence(Fts3Expr *p){
117421   assert( p->eType!=FTSQUERY_PHRASE );
117422   if( sqlite3_fts3_enable_parentheses ){
117423     return p->eType;
117424   }else if( p->eType==FTSQUERY_NEAR ){
117425     return 1;
117426   }else if( p->eType==FTSQUERY_OR ){
117427     return 2;
117428   }
117429   assert( p->eType==FTSQUERY_AND );
117430   return 3;
117431 }
117432
117433 /*
117434 ** Argument ppHead contains a pointer to the current head of a query 
117435 ** expression tree being parsed. pPrev is the expression node most recently
117436 ** inserted into the tree. This function adds pNew, which is always a binary
117437 ** operator node, into the expression tree based on the relative precedence
117438 ** of pNew and the existing nodes of the tree. This may result in the head
117439 ** of the tree changing, in which case *ppHead is set to the new root node.
117440 */
117441 static void insertBinaryOperator(
117442   Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
117443   Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
117444   Fts3Expr *pNew           /* New binary node to insert into expression tree */
117445 ){
117446   Fts3Expr *pSplit = pPrev;
117447   while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
117448     pSplit = pSplit->pParent;
117449   }
117450
117451   if( pSplit->pParent ){
117452     assert( pSplit->pParent->pRight==pSplit );
117453     pSplit->pParent->pRight = pNew;
117454     pNew->pParent = pSplit->pParent;
117455   }else{
117456     *ppHead = pNew;
117457   }
117458   pNew->pLeft = pSplit;
117459   pSplit->pParent = pNew;
117460 }
117461
117462 /*
117463 ** Parse the fts3 query expression found in buffer z, length n. This function
117464 ** returns either when the end of the buffer is reached or an unmatched 
117465 ** closing bracket - ')' - is encountered.
117466 **
117467 ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
117468 ** parsed form of the expression and *pnConsumed is set to the number of
117469 ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
117470 ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
117471 */
117472 static int fts3ExprParse(
117473   ParseContext *pParse,                   /* fts3 query parse context */
117474   const char *z, int n,                   /* Text of MATCH query */
117475   Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
117476   int *pnConsumed                         /* OUT: Number of bytes consumed */
117477 ){
117478   Fts3Expr *pRet = 0;
117479   Fts3Expr *pPrev = 0;
117480   Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
117481   int nIn = n;
117482   const char *zIn = z;
117483   int rc = SQLITE_OK;
117484   int isRequirePhrase = 1;
117485
117486   while( rc==SQLITE_OK ){
117487     Fts3Expr *p = 0;
117488     int nByte = 0;
117489     rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
117490     if( rc==SQLITE_OK ){
117491       int isPhrase;
117492
117493       if( !sqlite3_fts3_enable_parentheses 
117494        && p->eType==FTSQUERY_PHRASE && pParse->isNot 
117495       ){
117496         /* Create an implicit NOT operator. */
117497         Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
117498         if( !pNot ){
117499           sqlite3Fts3ExprFree(p);
117500           rc = SQLITE_NOMEM;
117501           goto exprparse_out;
117502         }
117503         pNot->eType = FTSQUERY_NOT;
117504         pNot->pRight = p;
117505         if( pNotBranch ){
117506           pNot->pLeft = pNotBranch;
117507         }
117508         pNotBranch = pNot;
117509         p = pPrev;
117510       }else{
117511         int eType = p->eType;
117512         isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
117513
117514         /* The isRequirePhrase variable is set to true if a phrase or
117515         ** an expression contained in parenthesis is required. If a
117516         ** binary operator (AND, OR, NOT or NEAR) is encounted when
117517         ** isRequirePhrase is set, this is a syntax error.
117518         */
117519         if( !isPhrase && isRequirePhrase ){
117520           sqlite3Fts3ExprFree(p);
117521           rc = SQLITE_ERROR;
117522           goto exprparse_out;
117523         }
117524   
117525         if( isPhrase && !isRequirePhrase ){
117526           /* Insert an implicit AND operator. */
117527           Fts3Expr *pAnd;
117528           assert( pRet && pPrev );
117529           pAnd = fts3MallocZero(sizeof(Fts3Expr));
117530           if( !pAnd ){
117531             sqlite3Fts3ExprFree(p);
117532             rc = SQLITE_NOMEM;
117533             goto exprparse_out;
117534           }
117535           pAnd->eType = FTSQUERY_AND;
117536           insertBinaryOperator(&pRet, pPrev, pAnd);
117537           pPrev = pAnd;
117538         }
117539
117540         /* This test catches attempts to make either operand of a NEAR
117541         ** operator something other than a phrase. For example, either of
117542         ** the following:
117543         **
117544         **    (bracketed expression) NEAR phrase
117545         **    phrase NEAR (bracketed expression)
117546         **
117547         ** Return an error in either case.
117548         */
117549         if( pPrev && (
117550             (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
117551          || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
117552         )){
117553           sqlite3Fts3ExprFree(p);
117554           rc = SQLITE_ERROR;
117555           goto exprparse_out;
117556         }
117557   
117558         if( isPhrase ){
117559           if( pRet ){
117560             assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
117561             pPrev->pRight = p;
117562             p->pParent = pPrev;
117563           }else{
117564             pRet = p;
117565           }
117566         }else{
117567           insertBinaryOperator(&pRet, pPrev, p);
117568         }
117569         isRequirePhrase = !isPhrase;
117570       }
117571       assert( nByte>0 );
117572     }
117573     assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
117574     nIn -= nByte;
117575     zIn += nByte;
117576     pPrev = p;
117577   }
117578
117579   if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
117580     rc = SQLITE_ERROR;
117581   }
117582
117583   if( rc==SQLITE_DONE ){
117584     rc = SQLITE_OK;
117585     if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
117586       if( !pRet ){
117587         rc = SQLITE_ERROR;
117588       }else{
117589         Fts3Expr *pIter = pNotBranch;
117590         while( pIter->pLeft ){
117591           pIter = pIter->pLeft;
117592         }
117593         pIter->pLeft = pRet;
117594         pRet = pNotBranch;
117595       }
117596     }
117597   }
117598   *pnConsumed = n - nIn;
117599
117600 exprparse_out:
117601   if( rc!=SQLITE_OK ){
117602     sqlite3Fts3ExprFree(pRet);
117603     sqlite3Fts3ExprFree(pNotBranch);
117604     pRet = 0;
117605   }
117606   *ppExpr = pRet;
117607   return rc;
117608 }
117609
117610 /*
117611 ** Parameters z and n contain a pointer to and length of a buffer containing
117612 ** an fts3 query expression, respectively. This function attempts to parse the
117613 ** query expression and create a tree of Fts3Expr structures representing the
117614 ** parsed expression. If successful, *ppExpr is set to point to the head
117615 ** of the parsed expression tree and SQLITE_OK is returned. If an error
117616 ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
117617 ** error) is returned and *ppExpr is set to 0.
117618 **
117619 ** If parameter n is a negative number, then z is assumed to point to a
117620 ** nul-terminated string and the length is determined using strlen().
117621 **
117622 ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
117623 ** use to normalize query tokens while parsing the expression. The azCol[]
117624 ** array, which is assumed to contain nCol entries, should contain the names
117625 ** of each column in the target fts3 table, in order from left to right. 
117626 ** Column names must be nul-terminated strings.
117627 **
117628 ** The iDefaultCol parameter should be passed the index of the table column
117629 ** that appears on the left-hand-side of the MATCH operator (the default
117630 ** column to match against for tokens for which a column name is not explicitly
117631 ** specified as part of the query string), or -1 if tokens may by default
117632 ** match any table column.
117633 */
117634 SQLITE_PRIVATE int sqlite3Fts3ExprParse(
117635   sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
117636   char **azCol,                       /* Array of column names for fts3 table */
117637   int nCol,                           /* Number of entries in azCol[] */
117638   int iDefaultCol,                    /* Default column to query */
117639   const char *z, int n,               /* Text of MATCH query */
117640   Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
117641 ){
117642   int nParsed;
117643   int rc;
117644   ParseContext sParse;
117645   sParse.pTokenizer = pTokenizer;
117646   sParse.azCol = (const char **)azCol;
117647   sParse.nCol = nCol;
117648   sParse.iDefaultCol = iDefaultCol;
117649   sParse.nNest = 0;
117650   if( z==0 ){
117651     *ppExpr = 0;
117652     return SQLITE_OK;
117653   }
117654   if( n<0 ){
117655     n = (int)strlen(z);
117656   }
117657   rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
117658
117659   /* Check for mismatched parenthesis */
117660   if( rc==SQLITE_OK && sParse.nNest ){
117661     rc = SQLITE_ERROR;
117662     sqlite3Fts3ExprFree(*ppExpr);
117663     *ppExpr = 0;
117664   }
117665
117666   return rc;
117667 }
117668
117669 /*
117670 ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
117671 */
117672 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *p){
117673   if( p ){
117674     assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
117675     sqlite3Fts3ExprFree(p->pLeft);
117676     sqlite3Fts3ExprFree(p->pRight);
117677     sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
117678     sqlite3_free(p->aMI);
117679     sqlite3_free(p);
117680   }
117681 }
117682
117683 /****************************************************************************
117684 *****************************************************************************
117685 ** Everything after this point is just test code.
117686 */
117687
117688 #ifdef SQLITE_TEST
117689
117690
117691 /*
117692 ** Function to query the hash-table of tokenizers (see README.tokenizers).
117693 */
117694 static int queryTestTokenizer(
117695   sqlite3 *db, 
117696   const char *zName,  
117697   const sqlite3_tokenizer_module **pp
117698 ){
117699   int rc;
117700   sqlite3_stmt *pStmt;
117701   const char zSql[] = "SELECT fts3_tokenizer(?)";
117702
117703   *pp = 0;
117704   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
117705   if( rc!=SQLITE_OK ){
117706     return rc;
117707   }
117708
117709   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
117710   if( SQLITE_ROW==sqlite3_step(pStmt) ){
117711     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
117712       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
117713     }
117714   }
117715
117716   return sqlite3_finalize(pStmt);
117717 }
117718
117719 /*
117720 ** Return a pointer to a buffer containing a text representation of the
117721 ** expression passed as the first argument. The buffer is obtained from
117722 ** sqlite3_malloc(). It is the responsibility of the caller to use 
117723 ** sqlite3_free() to release the memory. If an OOM condition is encountered,
117724 ** NULL is returned.
117725 **
117726 ** If the second argument is not NULL, then its contents are prepended to 
117727 ** the returned expression text and then freed using sqlite3_free().
117728 */
117729 static char *exprToString(Fts3Expr *pExpr, char *zBuf){
117730   switch( pExpr->eType ){
117731     case FTSQUERY_PHRASE: {
117732       Fts3Phrase *pPhrase = pExpr->pPhrase;
117733       int i;
117734       zBuf = sqlite3_mprintf(
117735           "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
117736       for(i=0; zBuf && i<pPhrase->nToken; i++){
117737         zBuf = sqlite3_mprintf("%z %.*s%s", zBuf, 
117738             pPhrase->aToken[i].n, pPhrase->aToken[i].z,
117739             (pPhrase->aToken[i].isPrefix?"+":"")
117740         );
117741       }
117742       return zBuf;
117743     }
117744
117745     case FTSQUERY_NEAR:
117746       zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
117747       break;
117748     case FTSQUERY_NOT:
117749       zBuf = sqlite3_mprintf("%zNOT ", zBuf);
117750       break;
117751     case FTSQUERY_AND:
117752       zBuf = sqlite3_mprintf("%zAND ", zBuf);
117753       break;
117754     case FTSQUERY_OR:
117755       zBuf = sqlite3_mprintf("%zOR ", zBuf);
117756       break;
117757   }
117758
117759   if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
117760   if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
117761   if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
117762
117763   if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
117764   if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
117765
117766   return zBuf;
117767 }
117768
117769 /*
117770 ** This is the implementation of a scalar SQL function used to test the 
117771 ** expression parser. It should be called as follows:
117772 **
117773 **   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
117774 **
117775 ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
117776 ** to parse the query expression (see README.tokenizers). The second argument
117777 ** is the query expression to parse. Each subsequent argument is the name
117778 ** of a column of the fts3 table that the query expression may refer to.
117779 ** For example:
117780 **
117781 **   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
117782 */
117783 static void fts3ExprTest(
117784   sqlite3_context *context,
117785   int argc,
117786   sqlite3_value **argv
117787 ){
117788   sqlite3_tokenizer_module const *pModule = 0;
117789   sqlite3_tokenizer *pTokenizer = 0;
117790   int rc;
117791   char **azCol = 0;
117792   const char *zExpr;
117793   int nExpr;
117794   int nCol;
117795   int ii;
117796   Fts3Expr *pExpr;
117797   char *zBuf = 0;
117798   sqlite3 *db = sqlite3_context_db_handle(context);
117799
117800   if( argc<3 ){
117801     sqlite3_result_error(context, 
117802         "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
117803     );
117804     return;
117805   }
117806
117807   rc = queryTestTokenizer(db,
117808                           (const char *)sqlite3_value_text(argv[0]), &pModule);
117809   if( rc==SQLITE_NOMEM ){
117810     sqlite3_result_error_nomem(context);
117811     goto exprtest_out;
117812   }else if( !pModule ){
117813     sqlite3_result_error(context, "No such tokenizer module", -1);
117814     goto exprtest_out;
117815   }
117816
117817   rc = pModule->xCreate(0, 0, &pTokenizer);
117818   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
117819   if( rc==SQLITE_NOMEM ){
117820     sqlite3_result_error_nomem(context);
117821     goto exprtest_out;
117822   }
117823   pTokenizer->pModule = pModule;
117824
117825   zExpr = (const char *)sqlite3_value_text(argv[1]);
117826   nExpr = sqlite3_value_bytes(argv[1]);
117827   nCol = argc-2;
117828   azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
117829   if( !azCol ){
117830     sqlite3_result_error_nomem(context);
117831     goto exprtest_out;
117832   }
117833   for(ii=0; ii<nCol; ii++){
117834     azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
117835   }
117836
117837   rc = sqlite3Fts3ExprParse(
117838       pTokenizer, azCol, nCol, nCol, zExpr, nExpr, &pExpr
117839   );
117840   if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
117841     sqlite3_result_error(context, "Error parsing expression", -1);
117842   }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
117843     sqlite3_result_error_nomem(context);
117844   }else{
117845     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
117846     sqlite3_free(zBuf);
117847   }
117848
117849   sqlite3Fts3ExprFree(pExpr);
117850
117851 exprtest_out:
117852   if( pModule && pTokenizer ){
117853     rc = pModule->xDestroy(pTokenizer);
117854   }
117855   sqlite3_free(azCol);
117856 }
117857
117858 /*
117859 ** Register the query expression parser test function fts3_exprtest() 
117860 ** with database connection db. 
117861 */
117862 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
117863   return sqlite3_create_function(
117864       db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
117865   );
117866 }
117867
117868 #endif
117869 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
117870
117871 /************** End of fts3_expr.c *******************************************/
117872 /************** Begin file fts3_hash.c ***************************************/
117873 /*
117874 ** 2001 September 22
117875 **
117876 ** The author disclaims copyright to this source code.  In place of
117877 ** a legal notice, here is a blessing:
117878 **
117879 **    May you do good and not evil.
117880 **    May you find forgiveness for yourself and forgive others.
117881 **    May you share freely, never taking more than you give.
117882 **
117883 *************************************************************************
117884 ** This is the implementation of generic hash-tables used in SQLite.
117885 ** We've modified it slightly to serve as a standalone hash table
117886 ** implementation for the full-text indexing module.
117887 */
117888
117889 /*
117890 ** The code in this file is only compiled if:
117891 **
117892 **     * The FTS3 module is being built as an extension
117893 **       (in which case SQLITE_CORE is not defined), or
117894 **
117895 **     * The FTS3 module is being built into the core of
117896 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
117897 */
117898 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
117899
117900
117901
117902 /*
117903 ** Malloc and Free functions
117904 */
117905 static void *fts3HashMalloc(int n){
117906   void *p = sqlite3_malloc(n);
117907   if( p ){
117908     memset(p, 0, n);
117909   }
117910   return p;
117911 }
117912 static void fts3HashFree(void *p){
117913   sqlite3_free(p);
117914 }
117915
117916 /* Turn bulk memory into a hash table object by initializing the
117917 ** fields of the Hash structure.
117918 **
117919 ** "pNew" is a pointer to the hash table that is to be initialized.
117920 ** keyClass is one of the constants 
117921 ** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass 
117922 ** determines what kind of key the hash table will use.  "copyKey" is
117923 ** true if the hash table should make its own private copy of keys and
117924 ** false if it should just use the supplied pointer.
117925 */
117926 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
117927   assert( pNew!=0 );
117928   assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
117929   pNew->keyClass = keyClass;
117930   pNew->copyKey = copyKey;
117931   pNew->first = 0;
117932   pNew->count = 0;
117933   pNew->htsize = 0;
117934   pNew->ht = 0;
117935 }
117936
117937 /* Remove all entries from a hash table.  Reclaim all memory.
117938 ** Call this routine to delete a hash table or to reset a hash table
117939 ** to the empty state.
117940 */
117941 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
117942   Fts3HashElem *elem;         /* For looping over all elements of the table */
117943
117944   assert( pH!=0 );
117945   elem = pH->first;
117946   pH->first = 0;
117947   fts3HashFree(pH->ht);
117948   pH->ht = 0;
117949   pH->htsize = 0;
117950   while( elem ){
117951     Fts3HashElem *next_elem = elem->next;
117952     if( pH->copyKey && elem->pKey ){
117953       fts3HashFree(elem->pKey);
117954     }
117955     fts3HashFree(elem);
117956     elem = next_elem;
117957   }
117958   pH->count = 0;
117959 }
117960
117961 /*
117962 ** Hash and comparison functions when the mode is FTS3_HASH_STRING
117963 */
117964 static int fts3StrHash(const void *pKey, int nKey){
117965   const char *z = (const char *)pKey;
117966   int h = 0;
117967   if( nKey<=0 ) nKey = (int) strlen(z);
117968   while( nKey > 0  ){
117969     h = (h<<3) ^ h ^ *z++;
117970     nKey--;
117971   }
117972   return h & 0x7fffffff;
117973 }
117974 static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
117975   if( n1!=n2 ) return 1;
117976   return strncmp((const char*)pKey1,(const char*)pKey2,n1);
117977 }
117978
117979 /*
117980 ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
117981 */
117982 static int fts3BinHash(const void *pKey, int nKey){
117983   int h = 0;
117984   const char *z = (const char *)pKey;
117985   while( nKey-- > 0 ){
117986     h = (h<<3) ^ h ^ *(z++);
117987   }
117988   return h & 0x7fffffff;
117989 }
117990 static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
117991   if( n1!=n2 ) return 1;
117992   return memcmp(pKey1,pKey2,n1);
117993 }
117994
117995 /*
117996 ** Return a pointer to the appropriate hash function given the key class.
117997 **
117998 ** The C syntax in this function definition may be unfamilar to some 
117999 ** programmers, so we provide the following additional explanation:
118000 **
118001 ** The name of the function is "ftsHashFunction".  The function takes a
118002 ** single parameter "keyClass".  The return value of ftsHashFunction()
118003 ** is a pointer to another function.  Specifically, the return value
118004 ** of ftsHashFunction() is a pointer to a function that takes two parameters
118005 ** with types "const void*" and "int" and returns an "int".
118006 */
118007 static int (*ftsHashFunction(int keyClass))(const void*,int){
118008   if( keyClass==FTS3_HASH_STRING ){
118009     return &fts3StrHash;
118010   }else{
118011     assert( keyClass==FTS3_HASH_BINARY );
118012     return &fts3BinHash;
118013   }
118014 }
118015
118016 /*
118017 ** Return a pointer to the appropriate hash function given the key class.
118018 **
118019 ** For help in interpreted the obscure C code in the function definition,
118020 ** see the header comment on the previous function.
118021 */
118022 static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
118023   if( keyClass==FTS3_HASH_STRING ){
118024     return &fts3StrCompare;
118025   }else{
118026     assert( keyClass==FTS3_HASH_BINARY );
118027     return &fts3BinCompare;
118028   }
118029 }
118030
118031 /* Link an element into the hash table
118032 */
118033 static void fts3HashInsertElement(
118034   Fts3Hash *pH,            /* The complete hash table */
118035   struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
118036   Fts3HashElem *pNew       /* The element to be inserted */
118037 ){
118038   Fts3HashElem *pHead;     /* First element already in pEntry */
118039   pHead = pEntry->chain;
118040   if( pHead ){
118041     pNew->next = pHead;
118042     pNew->prev = pHead->prev;
118043     if( pHead->prev ){ pHead->prev->next = pNew; }
118044     else             { pH->first = pNew; }
118045     pHead->prev = pNew;
118046   }else{
118047     pNew->next = pH->first;
118048     if( pH->first ){ pH->first->prev = pNew; }
118049     pNew->prev = 0;
118050     pH->first = pNew;
118051   }
118052   pEntry->count++;
118053   pEntry->chain = pNew;
118054 }
118055
118056
118057 /* Resize the hash table so that it cantains "new_size" buckets.
118058 ** "new_size" must be a power of 2.  The hash table might fail 
118059 ** to resize if sqliteMalloc() fails.
118060 **
118061 ** Return non-zero if a memory allocation error occurs.
118062 */
118063 static int fts3Rehash(Fts3Hash *pH, int new_size){
118064   struct _fts3ht *new_ht;          /* The new hash table */
118065   Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
118066   int (*xHash)(const void*,int);   /* The hash function */
118067
118068   assert( (new_size & (new_size-1))==0 );
118069   new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
118070   if( new_ht==0 ) return 1;
118071   fts3HashFree(pH->ht);
118072   pH->ht = new_ht;
118073   pH->htsize = new_size;
118074   xHash = ftsHashFunction(pH->keyClass);
118075   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
118076     int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
118077     next_elem = elem->next;
118078     fts3HashInsertElement(pH, &new_ht[h], elem);
118079   }
118080   return 0;
118081 }
118082
118083 /* This function (for internal use only) locates an element in an
118084 ** hash table that matches the given key.  The hash for this key has
118085 ** already been computed and is passed as the 4th parameter.
118086 */
118087 static Fts3HashElem *fts3FindElementByHash(
118088   const Fts3Hash *pH, /* The pH to be searched */
118089   const void *pKey,   /* The key we are searching for */
118090   int nKey,
118091   int h               /* The hash for this key. */
118092 ){
118093   Fts3HashElem *elem;            /* Used to loop thru the element list */
118094   int count;                     /* Number of elements left to test */
118095   int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
118096
118097   if( pH->ht ){
118098     struct _fts3ht *pEntry = &pH->ht[h];
118099     elem = pEntry->chain;
118100     count = pEntry->count;
118101     xCompare = ftsCompareFunction(pH->keyClass);
118102     while( count-- && elem ){
118103       if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ 
118104         return elem;
118105       }
118106       elem = elem->next;
118107     }
118108   }
118109   return 0;
118110 }
118111
118112 /* Remove a single entry from the hash table given a pointer to that
118113 ** element and a hash on the element's key.
118114 */
118115 static void fts3RemoveElementByHash(
118116   Fts3Hash *pH,         /* The pH containing "elem" */
118117   Fts3HashElem* elem,   /* The element to be removed from the pH */
118118   int h                 /* Hash value for the element */
118119 ){
118120   struct _fts3ht *pEntry;
118121   if( elem->prev ){
118122     elem->prev->next = elem->next; 
118123   }else{
118124     pH->first = elem->next;
118125   }
118126   if( elem->next ){
118127     elem->next->prev = elem->prev;
118128   }
118129   pEntry = &pH->ht[h];
118130   if( pEntry->chain==elem ){
118131     pEntry->chain = elem->next;
118132   }
118133   pEntry->count--;
118134   if( pEntry->count<=0 ){
118135     pEntry->chain = 0;
118136   }
118137   if( pH->copyKey && elem->pKey ){
118138     fts3HashFree(elem->pKey);
118139   }
118140   fts3HashFree( elem );
118141   pH->count--;
118142   if( pH->count<=0 ){
118143     assert( pH->first==0 );
118144     assert( pH->count==0 );
118145     fts3HashClear(pH);
118146   }
118147 }
118148
118149 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
118150   const Fts3Hash *pH, 
118151   const void *pKey, 
118152   int nKey
118153 ){
118154   int h;                          /* A hash on key */
118155   int (*xHash)(const void*,int);  /* The hash function */
118156
118157   if( pH==0 || pH->ht==0 ) return 0;
118158   xHash = ftsHashFunction(pH->keyClass);
118159   assert( xHash!=0 );
118160   h = (*xHash)(pKey,nKey);
118161   assert( (pH->htsize & (pH->htsize-1))==0 );
118162   return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
118163 }
118164
118165 /* 
118166 ** Attempt to locate an element of the hash table pH with a key
118167 ** that matches pKey,nKey.  Return the data for this element if it is
118168 ** found, or NULL if there is no match.
118169 */
118170 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
118171   Fts3HashElem *pElem;            /* The element that matches key (if any) */
118172
118173   pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
118174   return pElem ? pElem->data : 0;
118175 }
118176
118177 /* Insert an element into the hash table pH.  The key is pKey,nKey
118178 ** and the data is "data".
118179 **
118180 ** If no element exists with a matching key, then a new
118181 ** element is created.  A copy of the key is made if the copyKey
118182 ** flag is set.  NULL is returned.
118183 **
118184 ** If another element already exists with the same key, then the
118185 ** new data replaces the old data and the old data is returned.
118186 ** The key is not copied in this instance.  If a malloc fails, then
118187 ** the new data is returned and the hash table is unchanged.
118188 **
118189 ** If the "data" parameter to this function is NULL, then the
118190 ** element corresponding to "key" is removed from the hash table.
118191 */
118192 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
118193   Fts3Hash *pH,        /* The hash table to insert into */
118194   const void *pKey,    /* The key */
118195   int nKey,            /* Number of bytes in the key */
118196   void *data           /* The data */
118197 ){
118198   int hraw;                 /* Raw hash value of the key */
118199   int h;                    /* the hash of the key modulo hash table size */
118200   Fts3HashElem *elem;       /* Used to loop thru the element list */
118201   Fts3HashElem *new_elem;   /* New element added to the pH */
118202   int (*xHash)(const void*,int);  /* The hash function */
118203
118204   assert( pH!=0 );
118205   xHash = ftsHashFunction(pH->keyClass);
118206   assert( xHash!=0 );
118207   hraw = (*xHash)(pKey, nKey);
118208   assert( (pH->htsize & (pH->htsize-1))==0 );
118209   h = hraw & (pH->htsize-1);
118210   elem = fts3FindElementByHash(pH,pKey,nKey,h);
118211   if( elem ){
118212     void *old_data = elem->data;
118213     if( data==0 ){
118214       fts3RemoveElementByHash(pH,elem,h);
118215     }else{
118216       elem->data = data;
118217     }
118218     return old_data;
118219   }
118220   if( data==0 ) return 0;
118221   if( (pH->htsize==0 && fts3Rehash(pH,8))
118222    || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
118223   ){
118224     pH->count = 0;
118225     return data;
118226   }
118227   assert( pH->htsize>0 );
118228   new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
118229   if( new_elem==0 ) return data;
118230   if( pH->copyKey && pKey!=0 ){
118231     new_elem->pKey = fts3HashMalloc( nKey );
118232     if( new_elem->pKey==0 ){
118233       fts3HashFree(new_elem);
118234       return data;
118235     }
118236     memcpy((void*)new_elem->pKey, pKey, nKey);
118237   }else{
118238     new_elem->pKey = (void*)pKey;
118239   }
118240   new_elem->nKey = nKey;
118241   pH->count++;
118242   assert( pH->htsize>0 );
118243   assert( (pH->htsize & (pH->htsize-1))==0 );
118244   h = hraw & (pH->htsize-1);
118245   fts3HashInsertElement(pH, &pH->ht[h], new_elem);
118246   new_elem->data = data;
118247   return 0;
118248 }
118249
118250 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
118251
118252 /************** End of fts3_hash.c *******************************************/
118253 /************** Begin file fts3_porter.c *************************************/
118254 /*
118255 ** 2006 September 30
118256 **
118257 ** The author disclaims copyright to this source code.  In place of
118258 ** a legal notice, here is a blessing:
118259 **
118260 **    May you do good and not evil.
118261 **    May you find forgiveness for yourself and forgive others.
118262 **    May you share freely, never taking more than you give.
118263 **
118264 *************************************************************************
118265 ** Implementation of the full-text-search tokenizer that implements
118266 ** a Porter stemmer.
118267 */
118268
118269 /*
118270 ** The code in this file is only compiled if:
118271 **
118272 **     * The FTS3 module is being built as an extension
118273 **       (in which case SQLITE_CORE is not defined), or
118274 **
118275 **     * The FTS3 module is being built into the core of
118276 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
118277 */
118278 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
118279
118280
118281
118282 /*
118283 ** Class derived from sqlite3_tokenizer
118284 */
118285 typedef struct porter_tokenizer {
118286   sqlite3_tokenizer base;      /* Base class */
118287 } porter_tokenizer;
118288
118289 /*
118290 ** Class derived from sqlit3_tokenizer_cursor
118291 */
118292 typedef struct porter_tokenizer_cursor {
118293   sqlite3_tokenizer_cursor base;
118294   const char *zInput;          /* input we are tokenizing */
118295   int nInput;                  /* size of the input */
118296   int iOffset;                 /* current position in zInput */
118297   int iToken;                  /* index of next token to be returned */
118298   char *zToken;                /* storage for current token */
118299   int nAllocated;              /* space allocated to zToken buffer */
118300 } porter_tokenizer_cursor;
118301
118302
118303 /*
118304 ** Create a new tokenizer instance.
118305 */
118306 static int porterCreate(
118307   int argc, const char * const *argv,
118308   sqlite3_tokenizer **ppTokenizer
118309 ){
118310   porter_tokenizer *t;
118311
118312   UNUSED_PARAMETER(argc);
118313   UNUSED_PARAMETER(argv);
118314
118315   t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
118316   if( t==NULL ) return SQLITE_NOMEM;
118317   memset(t, 0, sizeof(*t));
118318   *ppTokenizer = &t->base;
118319   return SQLITE_OK;
118320 }
118321
118322 /*
118323 ** Destroy a tokenizer
118324 */
118325 static int porterDestroy(sqlite3_tokenizer *pTokenizer){
118326   sqlite3_free(pTokenizer);
118327   return SQLITE_OK;
118328 }
118329
118330 /*
118331 ** Prepare to begin tokenizing a particular string.  The input
118332 ** string to be tokenized is zInput[0..nInput-1].  A cursor
118333 ** used to incrementally tokenize this string is returned in 
118334 ** *ppCursor.
118335 */
118336 static int porterOpen(
118337   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
118338   const char *zInput, int nInput,        /* String to be tokenized */
118339   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
118340 ){
118341   porter_tokenizer_cursor *c;
118342
118343   UNUSED_PARAMETER(pTokenizer);
118344
118345   c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
118346   if( c==NULL ) return SQLITE_NOMEM;
118347
118348   c->zInput = zInput;
118349   if( zInput==0 ){
118350     c->nInput = 0;
118351   }else if( nInput<0 ){
118352     c->nInput = (int)strlen(zInput);
118353   }else{
118354     c->nInput = nInput;
118355   }
118356   c->iOffset = 0;                 /* start tokenizing at the beginning */
118357   c->iToken = 0;
118358   c->zToken = NULL;               /* no space allocated, yet. */
118359   c->nAllocated = 0;
118360
118361   *ppCursor = &c->base;
118362   return SQLITE_OK;
118363 }
118364
118365 /*
118366 ** Close a tokenization cursor previously opened by a call to
118367 ** porterOpen() above.
118368 */
118369 static int porterClose(sqlite3_tokenizer_cursor *pCursor){
118370   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
118371   sqlite3_free(c->zToken);
118372   sqlite3_free(c);
118373   return SQLITE_OK;
118374 }
118375 /*
118376 ** Vowel or consonant
118377 */
118378 static const char cType[] = {
118379    0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
118380    1, 1, 1, 2, 1
118381 };
118382
118383 /*
118384 ** isConsonant() and isVowel() determine if their first character in
118385 ** the string they point to is a consonant or a vowel, according
118386 ** to Porter ruls.  
118387 **
118388 ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
118389 ** 'Y' is a consonant unless it follows another consonant,
118390 ** in which case it is a vowel.
118391 **
118392 ** In these routine, the letters are in reverse order.  So the 'y' rule
118393 ** is that 'y' is a consonant unless it is followed by another
118394 ** consonent.
118395 */
118396 static int isVowel(const char*);
118397 static int isConsonant(const char *z){
118398   int j;
118399   char x = *z;
118400   if( x==0 ) return 0;
118401   assert( x>='a' && x<='z' );
118402   j = cType[x-'a'];
118403   if( j<2 ) return j;
118404   return z[1]==0 || isVowel(z + 1);
118405 }
118406 static int isVowel(const char *z){
118407   int j;
118408   char x = *z;
118409   if( x==0 ) return 0;
118410   assert( x>='a' && x<='z' );
118411   j = cType[x-'a'];
118412   if( j<2 ) return 1-j;
118413   return isConsonant(z + 1);
118414 }
118415
118416 /*
118417 ** Let any sequence of one or more vowels be represented by V and let
118418 ** C be sequence of one or more consonants.  Then every word can be
118419 ** represented as:
118420 **
118421 **           [C] (VC){m} [V]
118422 **
118423 ** In prose:  A word is an optional consonant followed by zero or
118424 ** vowel-consonant pairs followed by an optional vowel.  "m" is the
118425 ** number of vowel consonant pairs.  This routine computes the value
118426 ** of m for the first i bytes of a word.
118427 **
118428 ** Return true if the m-value for z is 1 or more.  In other words,
118429 ** return true if z contains at least one vowel that is followed
118430 ** by a consonant.
118431 **
118432 ** In this routine z[] is in reverse order.  So we are really looking
118433 ** for an instance of of a consonant followed by a vowel.
118434 */
118435 static int m_gt_0(const char *z){
118436   while( isVowel(z) ){ z++; }
118437   if( *z==0 ) return 0;
118438   while( isConsonant(z) ){ z++; }
118439   return *z!=0;
118440 }
118441
118442 /* Like mgt0 above except we are looking for a value of m which is
118443 ** exactly 1
118444 */
118445 static int m_eq_1(const char *z){
118446   while( isVowel(z) ){ z++; }
118447   if( *z==0 ) return 0;
118448   while( isConsonant(z) ){ z++; }
118449   if( *z==0 ) return 0;
118450   while( isVowel(z) ){ z++; }
118451   if( *z==0 ) return 1;
118452   while( isConsonant(z) ){ z++; }
118453   return *z==0;
118454 }
118455
118456 /* Like mgt0 above except we are looking for a value of m>1 instead
118457 ** or m>0
118458 */
118459 static int m_gt_1(const char *z){
118460   while( isVowel(z) ){ z++; }
118461   if( *z==0 ) return 0;
118462   while( isConsonant(z) ){ z++; }
118463   if( *z==0 ) return 0;
118464   while( isVowel(z) ){ z++; }
118465   if( *z==0 ) return 0;
118466   while( isConsonant(z) ){ z++; }
118467   return *z!=0;
118468 }
118469
118470 /*
118471 ** Return TRUE if there is a vowel anywhere within z[0..n-1]
118472 */
118473 static int hasVowel(const char *z){
118474   while( isConsonant(z) ){ z++; }
118475   return *z!=0;
118476 }
118477
118478 /*
118479 ** Return TRUE if the word ends in a double consonant.
118480 **
118481 ** The text is reversed here. So we are really looking at
118482 ** the first two characters of z[].
118483 */
118484 static int doubleConsonant(const char *z){
118485   return isConsonant(z) && z[0]==z[1];
118486 }
118487
118488 /*
118489 ** Return TRUE if the word ends with three letters which
118490 ** are consonant-vowel-consonent and where the final consonant
118491 ** is not 'w', 'x', or 'y'.
118492 **
118493 ** The word is reversed here.  So we are really checking the
118494 ** first three letters and the first one cannot be in [wxy].
118495 */
118496 static int star_oh(const char *z){
118497   return
118498     isConsonant(z) &&
118499     z[0]!='w' && z[0]!='x' && z[0]!='y' &&
118500     isVowel(z+1) &&
118501     isConsonant(z+2);
118502 }
118503
118504 /*
118505 ** If the word ends with zFrom and xCond() is true for the stem
118506 ** of the word that preceeds the zFrom ending, then change the 
118507 ** ending to zTo.
118508 **
118509 ** The input word *pz and zFrom are both in reverse order.  zTo
118510 ** is in normal order. 
118511 **
118512 ** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
118513 ** match.  Not that TRUE is returned even if xCond() fails and
118514 ** no substitution occurs.
118515 */
118516 static int stem(
118517   char **pz,             /* The word being stemmed (Reversed) */
118518   const char *zFrom,     /* If the ending matches this... (Reversed) */
118519   const char *zTo,       /* ... change the ending to this (not reversed) */
118520   int (*xCond)(const char*)   /* Condition that must be true */
118521 ){
118522   char *z = *pz;
118523   while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
118524   if( *zFrom!=0 ) return 0;
118525   if( xCond && !xCond(z) ) return 1;
118526   while( *zTo ){
118527     *(--z) = *(zTo++);
118528   }
118529   *pz = z;
118530   return 1;
118531 }
118532
118533 /*
118534 ** This is the fallback stemmer used when the porter stemmer is
118535 ** inappropriate.  The input word is copied into the output with
118536 ** US-ASCII case folding.  If the input word is too long (more
118537 ** than 20 bytes if it contains no digits or more than 6 bytes if
118538 ** it contains digits) then word is truncated to 20 or 6 bytes
118539 ** by taking 10 or 3 bytes from the beginning and end.
118540 */
118541 static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
118542   int i, mx, j;
118543   int hasDigit = 0;
118544   for(i=0; i<nIn; i++){
118545     char c = zIn[i];
118546     if( c>='A' && c<='Z' ){
118547       zOut[i] = c - 'A' + 'a';
118548     }else{
118549       if( c>='0' && c<='9' ) hasDigit = 1;
118550       zOut[i] = c;
118551     }
118552   }
118553   mx = hasDigit ? 3 : 10;
118554   if( nIn>mx*2 ){
118555     for(j=mx, i=nIn-mx; i<nIn; i++, j++){
118556       zOut[j] = zOut[i];
118557     }
118558     i = j;
118559   }
118560   zOut[i] = 0;
118561   *pnOut = i;
118562 }
118563
118564
118565 /*
118566 ** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
118567 ** zOut is at least big enough to hold nIn bytes.  Write the actual
118568 ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
118569 **
118570 ** Any upper-case characters in the US-ASCII character set ([A-Z])
118571 ** are converted to lower case.  Upper-case UTF characters are
118572 ** unchanged.
118573 **
118574 ** Words that are longer than about 20 bytes are stemmed by retaining
118575 ** a few bytes from the beginning and the end of the word.  If the
118576 ** word contains digits, 3 bytes are taken from the beginning and
118577 ** 3 bytes from the end.  For long words without digits, 10 bytes
118578 ** are taken from each end.  US-ASCII case folding still applies.
118579 ** 
118580 ** If the input word contains not digits but does characters not 
118581 ** in [a-zA-Z] then no stemming is attempted and this routine just 
118582 ** copies the input into the input into the output with US-ASCII
118583 ** case folding.
118584 **
118585 ** Stemming never increases the length of the word.  So there is
118586 ** no chance of overflowing the zOut buffer.
118587 */
118588 static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
118589   int i, j;
118590   char zReverse[28];
118591   char *z, *z2;
118592   if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
118593     /* The word is too big or too small for the porter stemmer.
118594     ** Fallback to the copy stemmer */
118595     copy_stemmer(zIn, nIn, zOut, pnOut);
118596     return;
118597   }
118598   for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
118599     char c = zIn[i];
118600     if( c>='A' && c<='Z' ){
118601       zReverse[j] = c + 'a' - 'A';
118602     }else if( c>='a' && c<='z' ){
118603       zReverse[j] = c;
118604     }else{
118605       /* The use of a character not in [a-zA-Z] means that we fallback
118606       ** to the copy stemmer */
118607       copy_stemmer(zIn, nIn, zOut, pnOut);
118608       return;
118609     }
118610   }
118611   memset(&zReverse[sizeof(zReverse)-5], 0, 5);
118612   z = &zReverse[j+1];
118613
118614
118615   /* Step 1a */
118616   if( z[0]=='s' ){
118617     if(
118618      !stem(&z, "sess", "ss", 0) &&
118619      !stem(&z, "sei", "i", 0)  &&
118620      !stem(&z, "ss", "ss", 0)
118621     ){
118622       z++;
118623     }
118624   }
118625
118626   /* Step 1b */  
118627   z2 = z;
118628   if( stem(&z, "dee", "ee", m_gt_0) ){
118629     /* Do nothing.  The work was all in the test */
118630   }else if( 
118631      (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
118632       && z!=z2
118633   ){
118634      if( stem(&z, "ta", "ate", 0) ||
118635          stem(&z, "lb", "ble", 0) ||
118636          stem(&z, "zi", "ize", 0) ){
118637        /* Do nothing.  The work was all in the test */
118638      }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
118639        z++;
118640      }else if( m_eq_1(z) && star_oh(z) ){
118641        *(--z) = 'e';
118642      }
118643   }
118644
118645   /* Step 1c */
118646   if( z[0]=='y' && hasVowel(z+1) ){
118647     z[0] = 'i';
118648   }
118649
118650   /* Step 2 */
118651   switch( z[1] ){
118652    case 'a':
118653      stem(&z, "lanoita", "ate", m_gt_0) ||
118654      stem(&z, "lanoit", "tion", m_gt_0);
118655      break;
118656    case 'c':
118657      stem(&z, "icne", "ence", m_gt_0) ||
118658      stem(&z, "icna", "ance", m_gt_0);
118659      break;
118660    case 'e':
118661      stem(&z, "rezi", "ize", m_gt_0);
118662      break;
118663    case 'g':
118664      stem(&z, "igol", "log", m_gt_0);
118665      break;
118666    case 'l':
118667      stem(&z, "ilb", "ble", m_gt_0) ||
118668      stem(&z, "illa", "al", m_gt_0) ||
118669      stem(&z, "iltne", "ent", m_gt_0) ||
118670      stem(&z, "ile", "e", m_gt_0) ||
118671      stem(&z, "ilsuo", "ous", m_gt_0);
118672      break;
118673    case 'o':
118674      stem(&z, "noitazi", "ize", m_gt_0) ||
118675      stem(&z, "noita", "ate", m_gt_0) ||
118676      stem(&z, "rota", "ate", m_gt_0);
118677      break;
118678    case 's':
118679      stem(&z, "msila", "al", m_gt_0) ||
118680      stem(&z, "ssenevi", "ive", m_gt_0) ||
118681      stem(&z, "ssenluf", "ful", m_gt_0) ||
118682      stem(&z, "ssensuo", "ous", m_gt_0);
118683      break;
118684    case 't':
118685      stem(&z, "itila", "al", m_gt_0) ||
118686      stem(&z, "itivi", "ive", m_gt_0) ||
118687      stem(&z, "itilib", "ble", m_gt_0);
118688      break;
118689   }
118690
118691   /* Step 3 */
118692   switch( z[0] ){
118693    case 'e':
118694      stem(&z, "etaci", "ic", m_gt_0) ||
118695      stem(&z, "evita", "", m_gt_0)   ||
118696      stem(&z, "ezila", "al", m_gt_0);
118697      break;
118698    case 'i':
118699      stem(&z, "itici", "ic", m_gt_0);
118700      break;
118701    case 'l':
118702      stem(&z, "laci", "ic", m_gt_0) ||
118703      stem(&z, "luf", "", m_gt_0);
118704      break;
118705    case 's':
118706      stem(&z, "ssen", "", m_gt_0);
118707      break;
118708   }
118709
118710   /* Step 4 */
118711   switch( z[1] ){
118712    case 'a':
118713      if( z[0]=='l' && m_gt_1(z+2) ){
118714        z += 2;
118715      }
118716      break;
118717    case 'c':
118718      if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
118719        z += 4;
118720      }
118721      break;
118722    case 'e':
118723      if( z[0]=='r' && m_gt_1(z+2) ){
118724        z += 2;
118725      }
118726      break;
118727    case 'i':
118728      if( z[0]=='c' && m_gt_1(z+2) ){
118729        z += 2;
118730      }
118731      break;
118732    case 'l':
118733      if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
118734        z += 4;
118735      }
118736      break;
118737    case 'n':
118738      if( z[0]=='t' ){
118739        if( z[2]=='a' ){
118740          if( m_gt_1(z+3) ){
118741            z += 3;
118742          }
118743        }else if( z[2]=='e' ){
118744          stem(&z, "tneme", "", m_gt_1) ||
118745          stem(&z, "tnem", "", m_gt_1) ||
118746          stem(&z, "tne", "", m_gt_1);
118747        }
118748      }
118749      break;
118750    case 'o':
118751      if( z[0]=='u' ){
118752        if( m_gt_1(z+2) ){
118753          z += 2;
118754        }
118755      }else if( z[3]=='s' || z[3]=='t' ){
118756        stem(&z, "noi", "", m_gt_1);
118757      }
118758      break;
118759    case 's':
118760      if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
118761        z += 3;
118762      }
118763      break;
118764    case 't':
118765      stem(&z, "eta", "", m_gt_1) ||
118766      stem(&z, "iti", "", m_gt_1);
118767      break;
118768    case 'u':
118769      if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
118770        z += 3;
118771      }
118772      break;
118773    case 'v':
118774    case 'z':
118775      if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
118776        z += 3;
118777      }
118778      break;
118779   }
118780
118781   /* Step 5a */
118782   if( z[0]=='e' ){
118783     if( m_gt_1(z+1) ){
118784       z++;
118785     }else if( m_eq_1(z+1) && !star_oh(z+1) ){
118786       z++;
118787     }
118788   }
118789
118790   /* Step 5b */
118791   if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
118792     z++;
118793   }
118794
118795   /* z[] is now the stemmed word in reverse order.  Flip it back
118796   ** around into forward order and return.
118797   */
118798   *pnOut = i = (int)strlen(z);
118799   zOut[i] = 0;
118800   while( *z ){
118801     zOut[--i] = *(z++);
118802   }
118803 }
118804
118805 /*
118806 ** Characters that can be part of a token.  We assume any character
118807 ** whose value is greater than 0x80 (any UTF character) can be
118808 ** part of a token.  In other words, delimiters all must have
118809 ** values of 0x7f or lower.
118810 */
118811 static const char porterIdChar[] = {
118812 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
118813     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
118814     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
118815     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
118816     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
118817     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
118818 };
118819 #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
118820
118821 /*
118822 ** Extract the next token from a tokenization cursor.  The cursor must
118823 ** have been opened by a prior call to porterOpen().
118824 */
118825 static int porterNext(
118826   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
118827   const char **pzToken,               /* OUT: *pzToken is the token text */
118828   int *pnBytes,                       /* OUT: Number of bytes in token */
118829   int *piStartOffset,                 /* OUT: Starting offset of token */
118830   int *piEndOffset,                   /* OUT: Ending offset of token */
118831   int *piPosition                     /* OUT: Position integer of token */
118832 ){
118833   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
118834   const char *z = c->zInput;
118835
118836   while( c->iOffset<c->nInput ){
118837     int iStartOffset, ch;
118838
118839     /* Scan past delimiter characters */
118840     while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
118841       c->iOffset++;
118842     }
118843
118844     /* Count non-delimiter characters. */
118845     iStartOffset = c->iOffset;
118846     while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
118847       c->iOffset++;
118848     }
118849
118850     if( c->iOffset>iStartOffset ){
118851       int n = c->iOffset-iStartOffset;
118852       if( n>c->nAllocated ){
118853         char *pNew;
118854         c->nAllocated = n+20;
118855         pNew = sqlite3_realloc(c->zToken, c->nAllocated);
118856         if( !pNew ) return SQLITE_NOMEM;
118857         c->zToken = pNew;
118858       }
118859       porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
118860       *pzToken = c->zToken;
118861       *piStartOffset = iStartOffset;
118862       *piEndOffset = c->iOffset;
118863       *piPosition = c->iToken++;
118864       return SQLITE_OK;
118865     }
118866   }
118867   return SQLITE_DONE;
118868 }
118869
118870 /*
118871 ** The set of routines that implement the porter-stemmer tokenizer
118872 */
118873 static const sqlite3_tokenizer_module porterTokenizerModule = {
118874   0,
118875   porterCreate,
118876   porterDestroy,
118877   porterOpen,
118878   porterClose,
118879   porterNext,
118880 };
118881
118882 /*
118883 ** Allocate a new porter tokenizer.  Return a pointer to the new
118884 ** tokenizer in *ppModule
118885 */
118886 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
118887   sqlite3_tokenizer_module const**ppModule
118888 ){
118889   *ppModule = &porterTokenizerModule;
118890 }
118891
118892 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
118893
118894 /************** End of fts3_porter.c *****************************************/
118895 /************** Begin file fts3_tokenizer.c **********************************/
118896 /*
118897 ** 2007 June 22
118898 **
118899 ** The author disclaims copyright to this source code.  In place of
118900 ** a legal notice, here is a blessing:
118901 **
118902 **    May you do good and not evil.
118903 **    May you find forgiveness for yourself and forgive others.
118904 **    May you share freely, never taking more than you give.
118905 **
118906 ******************************************************************************
118907 **
118908 ** This is part of an SQLite module implementing full-text search.
118909 ** This particular file implements the generic tokenizer interface.
118910 */
118911
118912 /*
118913 ** The code in this file is only compiled if:
118914 **
118915 **     * The FTS3 module is being built as an extension
118916 **       (in which case SQLITE_CORE is not defined), or
118917 **
118918 **     * The FTS3 module is being built into the core of
118919 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
118920 */
118921 #ifndef SQLITE_CORE
118922   SQLITE_EXTENSION_INIT1
118923 #endif
118924
118925 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
118926
118927
118928 /*
118929 ** Implementation of the SQL scalar function for accessing the underlying 
118930 ** hash table. This function may be called as follows:
118931 **
118932 **   SELECT <function-name>(<key-name>);
118933 **   SELECT <function-name>(<key-name>, <pointer>);
118934 **
118935 ** where <function-name> is the name passed as the second argument
118936 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
118937 **
118938 ** If the <pointer> argument is specified, it must be a blob value
118939 ** containing a pointer to be stored as the hash data corresponding
118940 ** to the string <key-name>. If <pointer> is not specified, then
118941 ** the string <key-name> must already exist in the has table. Otherwise,
118942 ** an error is returned.
118943 **
118944 ** Whether or not the <pointer> argument is specified, the value returned
118945 ** is a blob containing the pointer stored as the hash data corresponding
118946 ** to string <key-name> (after the hash-table is updated, if applicable).
118947 */
118948 static void scalarFunc(
118949   sqlite3_context *context,
118950   int argc,
118951   sqlite3_value **argv
118952 ){
118953   Fts3Hash *pHash;
118954   void *pPtr = 0;
118955   const unsigned char *zName;
118956   int nName;
118957
118958   assert( argc==1 || argc==2 );
118959
118960   pHash = (Fts3Hash *)sqlite3_user_data(context);
118961
118962   zName = sqlite3_value_text(argv[0]);
118963   nName = sqlite3_value_bytes(argv[0])+1;
118964
118965   if( argc==2 ){
118966     void *pOld;
118967     int n = sqlite3_value_bytes(argv[1]);
118968     if( n!=sizeof(pPtr) ){
118969       sqlite3_result_error(context, "argument type mismatch", -1);
118970       return;
118971     }
118972     pPtr = *(void **)sqlite3_value_blob(argv[1]);
118973     pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
118974     if( pOld==pPtr ){
118975       sqlite3_result_error(context, "out of memory", -1);
118976       return;
118977     }
118978   }else{
118979     pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
118980     if( !pPtr ){
118981       char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
118982       sqlite3_result_error(context, zErr, -1);
118983       sqlite3_free(zErr);
118984       return;
118985     }
118986   }
118987
118988   sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
118989 }
118990
118991 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
118992   static const char isFtsIdChar[] = {
118993       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
118994       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
118995       0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
118996       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
118997       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
118998       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
118999       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
119000       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
119001   };
119002   return (c&0x80 || isFtsIdChar[(int)(c)]);
119003 }
119004
119005 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
119006   const char *z1;
119007   const char *z2 = 0;
119008
119009   /* Find the start of the next token. */
119010   z1 = zStr;
119011   while( z2==0 ){
119012     char c = *z1;
119013     switch( c ){
119014       case '\0': return 0;        /* No more tokens here */
119015       case '\'':
119016       case '"':
119017       case '`': {
119018         z2 = z1;
119019         while( *++z2 && (*z2!=c || *++z2==c) );
119020         break;
119021       }
119022       case '[':
119023         z2 = &z1[1];
119024         while( *z2 && z2[0]!=']' ) z2++;
119025         if( *z2 ) z2++;
119026         break;
119027
119028       default:
119029         if( sqlite3Fts3IsIdChar(*z1) ){
119030           z2 = &z1[1];
119031           while( sqlite3Fts3IsIdChar(*z2) ) z2++;
119032         }else{
119033           z1++;
119034         }
119035     }
119036   }
119037
119038   *pn = (int)(z2-z1);
119039   return z1;
119040 }
119041
119042 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
119043   Fts3Hash *pHash,                /* Tokenizer hash table */
119044   const char *zArg,               /* Tokenizer name */
119045   sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
119046   char **pzErr                    /* OUT: Set to malloced error message */
119047 ){
119048   int rc;
119049   char *z = (char *)zArg;
119050   int n = 0;
119051   char *zCopy;
119052   char *zEnd;                     /* Pointer to nul-term of zCopy */
119053   sqlite3_tokenizer_module *m;
119054
119055   zCopy = sqlite3_mprintf("%s", zArg);
119056   if( !zCopy ) return SQLITE_NOMEM;
119057   zEnd = &zCopy[strlen(zCopy)];
119058
119059   z = (char *)sqlite3Fts3NextToken(zCopy, &n);
119060   z[n] = '\0';
119061   sqlite3Fts3Dequote(z);
119062
119063   m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
119064   if( !m ){
119065     *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
119066     rc = SQLITE_ERROR;
119067   }else{
119068     char const **aArg = 0;
119069     int iArg = 0;
119070     z = &z[n+1];
119071     while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
119072       int nNew = sizeof(char *)*(iArg+1);
119073       char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
119074       if( !aNew ){
119075         sqlite3_free(zCopy);
119076         sqlite3_free((void *)aArg);
119077         return SQLITE_NOMEM;
119078       }
119079       aArg = aNew;
119080       aArg[iArg++] = z;
119081       z[n] = '\0';
119082       sqlite3Fts3Dequote(z);
119083       z = &z[n+1];
119084     }
119085     rc = m->xCreate(iArg, aArg, ppTok);
119086     assert( rc!=SQLITE_OK || *ppTok );
119087     if( rc!=SQLITE_OK ){
119088       *pzErr = sqlite3_mprintf("unknown tokenizer");
119089     }else{
119090       (*ppTok)->pModule = m; 
119091     }
119092     sqlite3_free((void *)aArg);
119093   }
119094
119095   sqlite3_free(zCopy);
119096   return rc;
119097 }
119098
119099
119100 #ifdef SQLITE_TEST
119101
119102
119103 /*
119104 ** Implementation of a special SQL scalar function for testing tokenizers 
119105 ** designed to be used in concert with the Tcl testing framework. This
119106 ** function must be called with two arguments:
119107 **
119108 **   SELECT <function-name>(<key-name>, <input-string>);
119109 **   SELECT <function-name>(<key-name>, <pointer>);
119110 **
119111 ** where <function-name> is the name passed as the second argument
119112 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
119113 ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
119114 **
119115 ** The return value is a string that may be interpreted as a Tcl
119116 ** list. For each token in the <input-string>, three elements are
119117 ** added to the returned list. The first is the token position, the 
119118 ** second is the token text (folded, stemmed, etc.) and the third is the
119119 ** substring of <input-string> associated with the token. For example, 
119120 ** using the built-in "simple" tokenizer:
119121 **
119122 **   SELECT fts_tokenizer_test('simple', 'I don't see how');
119123 **
119124 ** will return the string:
119125 **
119126 **   "{0 i I 1 dont don't 2 see see 3 how how}"
119127 **   
119128 */
119129 static void testFunc(
119130   sqlite3_context *context,
119131   int argc,
119132   sqlite3_value **argv
119133 ){
119134   Fts3Hash *pHash;
119135   sqlite3_tokenizer_module *p;
119136   sqlite3_tokenizer *pTokenizer = 0;
119137   sqlite3_tokenizer_cursor *pCsr = 0;
119138
119139   const char *zErr = 0;
119140
119141   const char *zName;
119142   int nName;
119143   const char *zInput;
119144   int nInput;
119145
119146   const char *zArg = 0;
119147
119148   const char *zToken;
119149   int nToken;
119150   int iStart;
119151   int iEnd;
119152   int iPos;
119153
119154   Tcl_Obj *pRet;
119155
119156   assert( argc==2 || argc==3 );
119157
119158   nName = sqlite3_value_bytes(argv[0]);
119159   zName = (const char *)sqlite3_value_text(argv[0]);
119160   nInput = sqlite3_value_bytes(argv[argc-1]);
119161   zInput = (const char *)sqlite3_value_text(argv[argc-1]);
119162
119163   if( argc==3 ){
119164     zArg = (const char *)sqlite3_value_text(argv[1]);
119165   }
119166
119167   pHash = (Fts3Hash *)sqlite3_user_data(context);
119168   p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
119169
119170   if( !p ){
119171     char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
119172     sqlite3_result_error(context, zErr, -1);
119173     sqlite3_free(zErr);
119174     return;
119175   }
119176
119177   pRet = Tcl_NewObj();
119178   Tcl_IncrRefCount(pRet);
119179
119180   if( SQLITE_OK!=p->xCreate(zArg ? 1 : 0, &zArg, &pTokenizer) ){
119181     zErr = "error in xCreate()";
119182     goto finish;
119183   }
119184   pTokenizer->pModule = p;
119185   if( SQLITE_OK!=p->xOpen(pTokenizer, zInput, nInput, &pCsr) ){
119186     zErr = "error in xOpen()";
119187     goto finish;
119188   }
119189   pCsr->pTokenizer = pTokenizer;
119190
119191   while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
119192     Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
119193     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
119194     zToken = &zInput[iStart];
119195     nToken = iEnd-iStart;
119196     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
119197   }
119198
119199   if( SQLITE_OK!=p->xClose(pCsr) ){
119200     zErr = "error in xClose()";
119201     goto finish;
119202   }
119203   if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
119204     zErr = "error in xDestroy()";
119205     goto finish;
119206   }
119207
119208 finish:
119209   if( zErr ){
119210     sqlite3_result_error(context, zErr, -1);
119211   }else{
119212     sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
119213   }
119214   Tcl_DecrRefCount(pRet);
119215 }
119216
119217 static
119218 int registerTokenizer(
119219   sqlite3 *db, 
119220   char *zName, 
119221   const sqlite3_tokenizer_module *p
119222 ){
119223   int rc;
119224   sqlite3_stmt *pStmt;
119225   const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
119226
119227   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
119228   if( rc!=SQLITE_OK ){
119229     return rc;
119230   }
119231
119232   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
119233   sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
119234   sqlite3_step(pStmt);
119235
119236   return sqlite3_finalize(pStmt);
119237 }
119238
119239 static
119240 int queryTokenizer(
119241   sqlite3 *db, 
119242   char *zName,  
119243   const sqlite3_tokenizer_module **pp
119244 ){
119245   int rc;
119246   sqlite3_stmt *pStmt;
119247   const char zSql[] = "SELECT fts3_tokenizer(?)";
119248
119249   *pp = 0;
119250   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
119251   if( rc!=SQLITE_OK ){
119252     return rc;
119253   }
119254
119255   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
119256   if( SQLITE_ROW==sqlite3_step(pStmt) ){
119257     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
119258       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
119259     }
119260   }
119261
119262   return sqlite3_finalize(pStmt);
119263 }
119264
119265 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
119266
119267 /*
119268 ** Implementation of the scalar function fts3_tokenizer_internal_test().
119269 ** This function is used for testing only, it is not included in the
119270 ** build unless SQLITE_TEST is defined.
119271 **
119272 ** The purpose of this is to test that the fts3_tokenizer() function
119273 ** can be used as designed by the C-code in the queryTokenizer and
119274 ** registerTokenizer() functions above. These two functions are repeated
119275 ** in the README.tokenizer file as an example, so it is important to
119276 ** test them.
119277 **
119278 ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
119279 ** function with no arguments. An assert() will fail if a problem is
119280 ** detected. i.e.:
119281 **
119282 **     SELECT fts3_tokenizer_internal_test();
119283 **
119284 */
119285 static void intTestFunc(
119286   sqlite3_context *context,
119287   int argc,
119288   sqlite3_value **argv
119289 ){
119290   int rc;
119291   const sqlite3_tokenizer_module *p1;
119292   const sqlite3_tokenizer_module *p2;
119293   sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
119294
119295   UNUSED_PARAMETER(argc);
119296   UNUSED_PARAMETER(argv);
119297
119298   /* Test the query function */
119299   sqlite3Fts3SimpleTokenizerModule(&p1);
119300   rc = queryTokenizer(db, "simple", &p2);
119301   assert( rc==SQLITE_OK );
119302   assert( p1==p2 );
119303   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
119304   assert( rc==SQLITE_ERROR );
119305   assert( p2==0 );
119306   assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
119307
119308   /* Test the storage function */
119309   rc = registerTokenizer(db, "nosuchtokenizer", p1);
119310   assert( rc==SQLITE_OK );
119311   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
119312   assert( rc==SQLITE_OK );
119313   assert( p2==p1 );
119314
119315   sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
119316 }
119317
119318 #endif
119319
119320 /*
119321 ** Set up SQL objects in database db used to access the contents of
119322 ** the hash table pointed to by argument pHash. The hash table must
119323 ** been initialised to use string keys, and to take a private copy 
119324 ** of the key when a value is inserted. i.e. by a call similar to:
119325 **
119326 **    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
119327 **
119328 ** This function adds a scalar function (see header comment above
119329 ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
119330 ** defined at compilation time, a temporary virtual table (see header 
119331 ** comment above struct HashTableVtab) to the database schema. Both 
119332 ** provide read/write access to the contents of *pHash.
119333 **
119334 ** The third argument to this function, zName, is used as the name
119335 ** of both the scalar and, if created, the virtual table.
119336 */
119337 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
119338   sqlite3 *db, 
119339   Fts3Hash *pHash, 
119340   const char *zName
119341 ){
119342   int rc = SQLITE_OK;
119343   void *p = (void *)pHash;
119344   const int any = SQLITE_ANY;
119345
119346 #ifdef SQLITE_TEST
119347   char *zTest = 0;
119348   char *zTest2 = 0;
119349   void *pdb = (void *)db;
119350   zTest = sqlite3_mprintf("%s_test", zName);
119351   zTest2 = sqlite3_mprintf("%s_internal_test", zName);
119352   if( !zTest || !zTest2 ){
119353     rc = SQLITE_NOMEM;
119354   }
119355 #endif
119356
119357   if( SQLITE_OK==rc ){
119358     rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
119359   }
119360   if( SQLITE_OK==rc ){
119361     rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
119362   }
119363 #ifdef SQLITE_TEST
119364   if( SQLITE_OK==rc ){
119365     rc = sqlite3_create_function(db, zTest, 2, any, p, testFunc, 0, 0);
119366   }
119367   if( SQLITE_OK==rc ){
119368     rc = sqlite3_create_function(db, zTest, 3, any, p, testFunc, 0, 0);
119369   }
119370   if( SQLITE_OK==rc ){
119371     rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
119372   }
119373 #endif
119374
119375 #ifdef SQLITE_TEST
119376   sqlite3_free(zTest);
119377   sqlite3_free(zTest2);
119378 #endif
119379
119380   return rc;
119381 }
119382
119383 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
119384
119385 /************** End of fts3_tokenizer.c **************************************/
119386 /************** Begin file fts3_tokenizer1.c *********************************/
119387 /*
119388 ** 2006 Oct 10
119389 **
119390 ** The author disclaims copyright to this source code.  In place of
119391 ** a legal notice, here is a blessing:
119392 **
119393 **    May you do good and not evil.
119394 **    May you find forgiveness for yourself and forgive others.
119395 **    May you share freely, never taking more than you give.
119396 **
119397 ******************************************************************************
119398 **
119399 ** Implementation of the "simple" full-text-search tokenizer.
119400 */
119401
119402 /*
119403 ** The code in this file is only compiled if:
119404 **
119405 **     * The FTS3 module is being built as an extension
119406 **       (in which case SQLITE_CORE is not defined), or
119407 **
119408 **     * The FTS3 module is being built into the core of
119409 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
119410 */
119411 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
119412
119413
119414
119415 typedef struct simple_tokenizer {
119416   sqlite3_tokenizer base;
119417   char delim[128];             /* flag ASCII delimiters */
119418 } simple_tokenizer;
119419
119420 typedef struct simple_tokenizer_cursor {
119421   sqlite3_tokenizer_cursor base;
119422   const char *pInput;          /* input we are tokenizing */
119423   int nBytes;                  /* size of the input */
119424   int iOffset;                 /* current position in pInput */
119425   int iToken;                  /* index of next token to be returned */
119426   char *pToken;                /* storage for current token */
119427   int nTokenAllocated;         /* space allocated to zToken buffer */
119428 } simple_tokenizer_cursor;
119429
119430
119431 static int simpleDelim(simple_tokenizer *t, unsigned char c){
119432   return c<0x80 && t->delim[c];
119433 }
119434 static int fts3_isalnum(int x){
119435   return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
119436 }
119437
119438 /*
119439 ** Create a new tokenizer instance.
119440 */
119441 static int simpleCreate(
119442   int argc, const char * const *argv,
119443   sqlite3_tokenizer **ppTokenizer
119444 ){
119445   simple_tokenizer *t;
119446
119447   t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
119448   if( t==NULL ) return SQLITE_NOMEM;
119449   memset(t, 0, sizeof(*t));
119450
119451   /* TODO(shess) Delimiters need to remain the same from run to run,
119452   ** else we need to reindex.  One solution would be a meta-table to
119453   ** track such information in the database, then we'd only want this
119454   ** information on the initial create.
119455   */
119456   if( argc>1 ){
119457     int i, n = (int)strlen(argv[1]);
119458     for(i=0; i<n; i++){
119459       unsigned char ch = argv[1][i];
119460       /* We explicitly don't support UTF-8 delimiters for now. */
119461       if( ch>=0x80 ){
119462         sqlite3_free(t);
119463         return SQLITE_ERROR;
119464       }
119465       t->delim[ch] = 1;
119466     }
119467   } else {
119468     /* Mark non-alphanumeric ASCII characters as delimiters */
119469     int i;
119470     for(i=1; i<0x80; i++){
119471       t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
119472     }
119473   }
119474
119475   *ppTokenizer = &t->base;
119476   return SQLITE_OK;
119477 }
119478
119479 /*
119480 ** Destroy a tokenizer
119481 */
119482 static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
119483   sqlite3_free(pTokenizer);
119484   return SQLITE_OK;
119485 }
119486
119487 /*
119488 ** Prepare to begin tokenizing a particular string.  The input
119489 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
119490 ** used to incrementally tokenize this string is returned in 
119491 ** *ppCursor.
119492 */
119493 static int simpleOpen(
119494   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
119495   const char *pInput, int nBytes,        /* String to be tokenized */
119496   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
119497 ){
119498   simple_tokenizer_cursor *c;
119499
119500   UNUSED_PARAMETER(pTokenizer);
119501
119502   c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
119503   if( c==NULL ) return SQLITE_NOMEM;
119504
119505   c->pInput = pInput;
119506   if( pInput==0 ){
119507     c->nBytes = 0;
119508   }else if( nBytes<0 ){
119509     c->nBytes = (int)strlen(pInput);
119510   }else{
119511     c->nBytes = nBytes;
119512   }
119513   c->iOffset = 0;                 /* start tokenizing at the beginning */
119514   c->iToken = 0;
119515   c->pToken = NULL;               /* no space allocated, yet. */
119516   c->nTokenAllocated = 0;
119517
119518   *ppCursor = &c->base;
119519   return SQLITE_OK;
119520 }
119521
119522 /*
119523 ** Close a tokenization cursor previously opened by a call to
119524 ** simpleOpen() above.
119525 */
119526 static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
119527   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
119528   sqlite3_free(c->pToken);
119529   sqlite3_free(c);
119530   return SQLITE_OK;
119531 }
119532
119533 /*
119534 ** Extract the next token from a tokenization cursor.  The cursor must
119535 ** have been opened by a prior call to simpleOpen().
119536 */
119537 static int simpleNext(
119538   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
119539   const char **ppToken,               /* OUT: *ppToken is the token text */
119540   int *pnBytes,                       /* OUT: Number of bytes in token */
119541   int *piStartOffset,                 /* OUT: Starting offset of token */
119542   int *piEndOffset,                   /* OUT: Ending offset of token */
119543   int *piPosition                     /* OUT: Position integer of token */
119544 ){
119545   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
119546   simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
119547   unsigned char *p = (unsigned char *)c->pInput;
119548
119549   while( c->iOffset<c->nBytes ){
119550     int iStartOffset;
119551
119552     /* Scan past delimiter characters */
119553     while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
119554       c->iOffset++;
119555     }
119556
119557     /* Count non-delimiter characters. */
119558     iStartOffset = c->iOffset;
119559     while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
119560       c->iOffset++;
119561     }
119562
119563     if( c->iOffset>iStartOffset ){
119564       int i, n = c->iOffset-iStartOffset;
119565       if( n>c->nTokenAllocated ){
119566         char *pNew;
119567         c->nTokenAllocated = n+20;
119568         pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
119569         if( !pNew ) return SQLITE_NOMEM;
119570         c->pToken = pNew;
119571       }
119572       for(i=0; i<n; i++){
119573         /* TODO(shess) This needs expansion to handle UTF-8
119574         ** case-insensitivity.
119575         */
119576         unsigned char ch = p[iStartOffset+i];
119577         c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
119578       }
119579       *ppToken = c->pToken;
119580       *pnBytes = n;
119581       *piStartOffset = iStartOffset;
119582       *piEndOffset = c->iOffset;
119583       *piPosition = c->iToken++;
119584
119585       return SQLITE_OK;
119586     }
119587   }
119588   return SQLITE_DONE;
119589 }
119590
119591 /*
119592 ** The set of routines that implement the simple tokenizer
119593 */
119594 static const sqlite3_tokenizer_module simpleTokenizerModule = {
119595   0,
119596   simpleCreate,
119597   simpleDestroy,
119598   simpleOpen,
119599   simpleClose,
119600   simpleNext,
119601 };
119602
119603 /*
119604 ** Allocate a new simple tokenizer.  Return a pointer to the new
119605 ** tokenizer in *ppModule
119606 */
119607 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
119608   sqlite3_tokenizer_module const**ppModule
119609 ){
119610   *ppModule = &simpleTokenizerModule;
119611 }
119612
119613 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
119614
119615 /************** End of fts3_tokenizer1.c *************************************/
119616 /************** Begin file fts3_write.c **************************************/
119617 /*
119618 ** 2009 Oct 23
119619 **
119620 ** The author disclaims copyright to this source code.  In place of
119621 ** a legal notice, here is a blessing:
119622 **
119623 **    May you do good and not evil.
119624 **    May you find forgiveness for yourself and forgive others.
119625 **    May you share freely, never taking more than you give.
119626 **
119627 ******************************************************************************
119628 **
119629 ** This file is part of the SQLite FTS3 extension module. Specifically,
119630 ** this file contains code to insert, update and delete rows from FTS3
119631 ** tables. It also contains code to merge FTS3 b-tree segments. Some
119632 ** of the sub-routines used to merge segments are also used by the query 
119633 ** code in fts3.c.
119634 */
119635
119636 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
119637
119638
119639 /*
119640 ** When full-text index nodes are loaded from disk, the buffer that they
119641 ** are loaded into has the following number of bytes of padding at the end 
119642 ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
119643 ** of 920 bytes is allocated for it.
119644 **
119645 ** This means that if we have a pointer into a buffer containing node data,
119646 ** it is always safe to read up to two varints from it without risking an
119647 ** overread, even if the node data is corrupted.
119648 */
119649 #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
119650
119651 /*
119652 ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
119653 ** memory incrementally instead of all at once. This can be a big performance
119654 ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
119655 ** method before retrieving all query results (as may happen, for example,
119656 ** if a query has a LIMIT clause).
119657 **
119658 ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD 
119659 ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
119660 ** The code is written so that the hard lower-limit for each of these values 
119661 ** is 1. Clearly such small values would be inefficient, but can be useful 
119662 ** for testing purposes.
119663 **
119664 ** If this module is built with SQLITE_TEST defined, these constants may
119665 ** be overridden at runtime for testing purposes. File fts3_test.c contains
119666 ** a Tcl interface to read and write the values.
119667 */
119668 #ifdef SQLITE_TEST
119669 int test_fts3_node_chunksize = (4*1024);
119670 int test_fts3_node_chunk_threshold = (4*1024)*4;
119671 # define FTS3_NODE_CHUNKSIZE       test_fts3_node_chunksize
119672 # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
119673 #else
119674 # define FTS3_NODE_CHUNKSIZE (4*1024) 
119675 # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
119676 #endif
119677
119678 typedef struct PendingList PendingList;
119679 typedef struct SegmentNode SegmentNode;
119680 typedef struct SegmentWriter SegmentWriter;
119681
119682 /*
119683 ** An instance of the following data structure is used to build doclists
119684 ** incrementally. See function fts3PendingListAppend() for details.
119685 */
119686 struct PendingList {
119687   int nData;
119688   char *aData;
119689   int nSpace;
119690   sqlite3_int64 iLastDocid;
119691   sqlite3_int64 iLastCol;
119692   sqlite3_int64 iLastPos;
119693 };
119694
119695
119696 /*
119697 ** Each cursor has a (possibly empty) linked list of the following objects.
119698 */
119699 struct Fts3DeferredToken {
119700   Fts3PhraseToken *pToken;        /* Pointer to corresponding expr token */
119701   int iCol;                       /* Column token must occur in */
119702   Fts3DeferredToken *pNext;       /* Next in list of deferred tokens */
119703   PendingList *pList;             /* Doclist is assembled here */
119704 };
119705
119706 /*
119707 ** An instance of this structure is used to iterate through the terms on
119708 ** a contiguous set of segment b-tree leaf nodes. Although the details of
119709 ** this structure are only manipulated by code in this file, opaque handles
119710 ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
119711 ** terms when querying the full-text index. See functions:
119712 **
119713 **   sqlite3Fts3SegReaderNew()
119714 **   sqlite3Fts3SegReaderFree()
119715 **   sqlite3Fts3SegReaderIterate()
119716 **
119717 ** Methods used to manipulate Fts3SegReader structures:
119718 **
119719 **   fts3SegReaderNext()
119720 **   fts3SegReaderFirstDocid()
119721 **   fts3SegReaderNextDocid()
119722 */
119723 struct Fts3SegReader {
119724   int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
119725
119726   sqlite3_int64 iStartBlock;      /* Rowid of first leaf block to traverse */
119727   sqlite3_int64 iLeafEndBlock;    /* Rowid of final leaf block to traverse */
119728   sqlite3_int64 iEndBlock;        /* Rowid of final block in segment (or 0) */
119729   sqlite3_int64 iCurrentBlock;    /* Current leaf block (or 0) */
119730
119731   char *aNode;                    /* Pointer to node data (or NULL) */
119732   int nNode;                      /* Size of buffer at aNode (or 0) */
119733   int nPopulate;                  /* If >0, bytes of buffer aNode[] loaded */
119734   sqlite3_blob *pBlob;            /* If not NULL, blob handle to read node */
119735
119736   Fts3HashElem **ppNextElem;
119737
119738   /* Variables set by fts3SegReaderNext(). These may be read directly
119739   ** by the caller. They are valid from the time SegmentReaderNew() returns
119740   ** until SegmentReaderNext() returns something other than SQLITE_OK
119741   ** (i.e. SQLITE_DONE).
119742   */
119743   int nTerm;                      /* Number of bytes in current term */
119744   char *zTerm;                    /* Pointer to current term */
119745   int nTermAlloc;                 /* Allocated size of zTerm buffer */
119746   char *aDoclist;                 /* Pointer to doclist of current entry */
119747   int nDoclist;                   /* Size of doclist in current entry */
119748
119749   /* The following variables are used by fts3SegReaderNextDocid() to iterate 
119750   ** through the current doclist (aDoclist/nDoclist).
119751   */
119752   char *pOffsetList;
119753   int nOffsetList;                /* For descending pending seg-readers only */
119754   sqlite3_int64 iDocid;
119755 };
119756
119757 #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
119758 #define fts3SegReaderIsRootOnly(p) ((p)->aNode==(char *)&(p)[1])
119759
119760 /*
119761 ** An instance of this structure is used to create a segment b-tree in the
119762 ** database. The internal details of this type are only accessed by the
119763 ** following functions:
119764 **
119765 **   fts3SegWriterAdd()
119766 **   fts3SegWriterFlush()
119767 **   fts3SegWriterFree()
119768 */
119769 struct SegmentWriter {
119770   SegmentNode *pTree;             /* Pointer to interior tree structure */
119771   sqlite3_int64 iFirst;           /* First slot in %_segments written */
119772   sqlite3_int64 iFree;            /* Next free slot in %_segments */
119773   char *zTerm;                    /* Pointer to previous term buffer */
119774   int nTerm;                      /* Number of bytes in zTerm */
119775   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
119776   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
119777   int nSize;                      /* Size of allocation at aData */
119778   int nData;                      /* Bytes of data in aData */
119779   char *aData;                    /* Pointer to block from malloc() */
119780 };
119781
119782 /*
119783 ** Type SegmentNode is used by the following three functions to create
119784 ** the interior part of the segment b+-tree structures (everything except
119785 ** the leaf nodes). These functions and type are only ever used by code
119786 ** within the fts3SegWriterXXX() family of functions described above.
119787 **
119788 **   fts3NodeAddTerm()
119789 **   fts3NodeWrite()
119790 **   fts3NodeFree()
119791 **
119792 ** When a b+tree is written to the database (either as a result of a merge
119793 ** or the pending-terms table being flushed), leaves are written into the 
119794 ** database file as soon as they are completely populated. The interior of
119795 ** the tree is assembled in memory and written out only once all leaves have
119796 ** been populated and stored. This is Ok, as the b+-tree fanout is usually
119797 ** very large, meaning that the interior of the tree consumes relatively 
119798 ** little memory.
119799 */
119800 struct SegmentNode {
119801   SegmentNode *pParent;           /* Parent node (or NULL for root node) */
119802   SegmentNode *pRight;            /* Pointer to right-sibling */
119803   SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
119804   int nEntry;                     /* Number of terms written to node so far */
119805   char *zTerm;                    /* Pointer to previous term buffer */
119806   int nTerm;                      /* Number of bytes in zTerm */
119807   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
119808   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
119809   int nData;                      /* Bytes of valid data so far */
119810   char *aData;                    /* Node data */
119811 };
119812
119813 /*
119814 ** Valid values for the second argument to fts3SqlStmt().
119815 */
119816 #define SQL_DELETE_CONTENT             0
119817 #define SQL_IS_EMPTY                   1
119818 #define SQL_DELETE_ALL_CONTENT         2 
119819 #define SQL_DELETE_ALL_SEGMENTS        3
119820 #define SQL_DELETE_ALL_SEGDIR          4
119821 #define SQL_DELETE_ALL_DOCSIZE         5
119822 #define SQL_DELETE_ALL_STAT            6
119823 #define SQL_SELECT_CONTENT_BY_ROWID    7
119824 #define SQL_NEXT_SEGMENT_INDEX         8
119825 #define SQL_INSERT_SEGMENTS            9
119826 #define SQL_NEXT_SEGMENTS_ID          10
119827 #define SQL_INSERT_SEGDIR             11
119828 #define SQL_SELECT_LEVEL              12
119829 #define SQL_SELECT_LEVEL_RANGE        13
119830 #define SQL_SELECT_LEVEL_COUNT        14
119831 #define SQL_SELECT_SEGDIR_MAX_LEVEL   15
119832 #define SQL_DELETE_SEGDIR_LEVEL       16
119833 #define SQL_DELETE_SEGMENTS_RANGE     17
119834 #define SQL_CONTENT_INSERT            18
119835 #define SQL_DELETE_DOCSIZE            19
119836 #define SQL_REPLACE_DOCSIZE           20
119837 #define SQL_SELECT_DOCSIZE            21
119838 #define SQL_SELECT_DOCTOTAL           22
119839 #define SQL_REPLACE_DOCTOTAL          23
119840
119841 #define SQL_SELECT_ALL_PREFIX_LEVEL   24
119842 #define SQL_DELETE_ALL_TERMS_SEGDIR   25
119843
119844 #define SQL_DELETE_SEGDIR_RANGE       26
119845
119846 /*
119847 ** This function is used to obtain an SQLite prepared statement handle
119848 ** for the statement identified by the second argument. If successful,
119849 ** *pp is set to the requested statement handle and SQLITE_OK returned.
119850 ** Otherwise, an SQLite error code is returned and *pp is set to 0.
119851 **
119852 ** If argument apVal is not NULL, then it must point to an array with
119853 ** at least as many entries as the requested statement has bound 
119854 ** parameters. The values are bound to the statements parameters before
119855 ** returning.
119856 */
119857 static int fts3SqlStmt(
119858   Fts3Table *p,                   /* Virtual table handle */
119859   int eStmt,                      /* One of the SQL_XXX constants above */
119860   sqlite3_stmt **pp,              /* OUT: Statement handle */
119861   sqlite3_value **apVal           /* Values to bind to statement */
119862 ){
119863   const char *azSql[] = {
119864 /* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
119865 /* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
119866 /* 2  */  "DELETE FROM %Q.'%q_content'",
119867 /* 3  */  "DELETE FROM %Q.'%q_segments'",
119868 /* 4  */  "DELETE FROM %Q.'%q_segdir'",
119869 /* 5  */  "DELETE FROM %Q.'%q_docsize'",
119870 /* 6  */  "DELETE FROM %Q.'%q_stat'",
119871 /* 7  */  "SELECT %s FROM %Q.'%q_content' AS x WHERE rowid=?",
119872 /* 8  */  "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
119873 /* 9  */  "INSERT INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
119874 /* 10 */  "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
119875 /* 11 */  "INSERT INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
119876
119877           /* Return segments in order from oldest to newest.*/ 
119878 /* 12 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
119879             "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
119880 /* 13 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
119881             "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
119882             "ORDER BY level DESC, idx ASC",
119883
119884 /* 14 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
119885 /* 15 */  "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
119886
119887 /* 16 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
119888 /* 17 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
119889 /* 18 */  "INSERT INTO %Q.'%q_content' VALUES(%s)",
119890 /* 19 */  "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
119891 /* 20 */  "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
119892 /* 21 */  "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
119893 /* 22 */  "SELECT value FROM %Q.'%q_stat' WHERE id=0",
119894 /* 23 */  "REPLACE INTO %Q.'%q_stat' VALUES(0,?)",
119895 /* 24 */  "",
119896 /* 25 */  "",
119897
119898 /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
119899
119900   };
119901   int rc = SQLITE_OK;
119902   sqlite3_stmt *pStmt;
119903
119904   assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
119905   assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
119906   
119907   pStmt = p->aStmt[eStmt];
119908   if( !pStmt ){
119909     char *zSql;
119910     if( eStmt==SQL_CONTENT_INSERT ){
119911       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
119912     }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
119913       zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist, p->zDb, p->zName);
119914     }else{
119915       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
119916     }
119917     if( !zSql ){
119918       rc = SQLITE_NOMEM;
119919     }else{
119920       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
119921       sqlite3_free(zSql);
119922       assert( rc==SQLITE_OK || pStmt==0 );
119923       p->aStmt[eStmt] = pStmt;
119924     }
119925   }
119926   if( apVal ){
119927     int i;
119928     int nParam = sqlite3_bind_parameter_count(pStmt);
119929     for(i=0; rc==SQLITE_OK && i<nParam; i++){
119930       rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
119931     }
119932   }
119933   *pp = pStmt;
119934   return rc;
119935 }
119936
119937 static int fts3SelectDocsize(
119938   Fts3Table *pTab,                /* FTS3 table handle */
119939   int eStmt,                      /* Either SQL_SELECT_DOCSIZE or DOCTOTAL */
119940   sqlite3_int64 iDocid,           /* Docid to bind for SQL_SELECT_DOCSIZE */
119941   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
119942 ){
119943   sqlite3_stmt *pStmt = 0;        /* Statement requested from fts3SqlStmt() */
119944   int rc;                         /* Return code */
119945
119946   assert( eStmt==SQL_SELECT_DOCSIZE || eStmt==SQL_SELECT_DOCTOTAL );
119947
119948   rc = fts3SqlStmt(pTab, eStmt, &pStmt, 0);
119949   if( rc==SQLITE_OK ){
119950     if( eStmt==SQL_SELECT_DOCSIZE ){
119951       sqlite3_bind_int64(pStmt, 1, iDocid);
119952     }
119953     rc = sqlite3_step(pStmt);
119954     if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
119955       rc = sqlite3_reset(pStmt);
119956       if( rc==SQLITE_OK ) rc = SQLITE_CORRUPT_VTAB;
119957       pStmt = 0;
119958     }else{
119959       rc = SQLITE_OK;
119960     }
119961   }
119962
119963   *ppStmt = pStmt;
119964   return rc;
119965 }
119966
119967 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
119968   Fts3Table *pTab,                /* Fts3 table handle */
119969   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
119970 ){
119971   return fts3SelectDocsize(pTab, SQL_SELECT_DOCTOTAL, 0, ppStmt);
119972 }
119973
119974 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
119975   Fts3Table *pTab,                /* Fts3 table handle */
119976   sqlite3_int64 iDocid,           /* Docid to read size data for */
119977   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
119978 ){
119979   return fts3SelectDocsize(pTab, SQL_SELECT_DOCSIZE, iDocid, ppStmt);
119980 }
119981
119982 /*
119983 ** Similar to fts3SqlStmt(). Except, after binding the parameters in
119984 ** array apVal[] to the SQL statement identified by eStmt, the statement
119985 ** is executed.
119986 **
119987 ** Returns SQLITE_OK if the statement is successfully executed, or an
119988 ** SQLite error code otherwise.
119989 */
119990 static void fts3SqlExec(
119991   int *pRC,                /* Result code */
119992   Fts3Table *p,            /* The FTS3 table */
119993   int eStmt,               /* Index of statement to evaluate */
119994   sqlite3_value **apVal    /* Parameters to bind */
119995 ){
119996   sqlite3_stmt *pStmt;
119997   int rc;
119998   if( *pRC ) return;
119999   rc = fts3SqlStmt(p, eStmt, &pStmt, apVal); 
120000   if( rc==SQLITE_OK ){
120001     sqlite3_step(pStmt);
120002     rc = sqlite3_reset(pStmt);
120003   }
120004   *pRC = rc;
120005 }
120006
120007
120008 /*
120009 ** This function ensures that the caller has obtained a shared-cache
120010 ** table-lock on the %_content table. This is required before reading
120011 ** data from the fts3 table. If this lock is not acquired first, then
120012 ** the caller may end up holding read-locks on the %_segments and %_segdir
120013 ** tables, but no read-lock on the %_content table. If this happens 
120014 ** a second connection will be able to write to the fts3 table, but
120015 ** attempting to commit those writes might return SQLITE_LOCKED or
120016 ** SQLITE_LOCKED_SHAREDCACHE (because the commit attempts to obtain 
120017 ** write-locks on the %_segments and %_segdir ** tables). 
120018 **
120019 ** We try to avoid this because if FTS3 returns any error when committing
120020 ** a transaction, the whole transaction will be rolled back. And this is
120021 ** not what users expect when they get SQLITE_LOCKED_SHAREDCACHE. It can
120022 ** still happen if the user reads data directly from the %_segments or
120023 ** %_segdir tables instead of going through FTS3 though.
120024 */
120025 SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *p){
120026   int rc;                         /* Return code */
120027   sqlite3_stmt *pStmt;            /* Statement used to obtain lock */
120028
120029   rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pStmt, 0);
120030   if( rc==SQLITE_OK ){
120031     sqlite3_bind_null(pStmt, 1);
120032     sqlite3_step(pStmt);
120033     rc = sqlite3_reset(pStmt);
120034   }
120035   return rc;
120036 }
120037
120038 /*
120039 ** Set *ppStmt to a statement handle that may be used to iterate through
120040 ** all rows in the %_segdir table, from oldest to newest. If successful,
120041 ** return SQLITE_OK. If an error occurs while preparing the statement, 
120042 ** return an SQLite error code.
120043 **
120044 ** There is only ever one instance of this SQL statement compiled for
120045 ** each FTS3 table.
120046 **
120047 ** The statement returns the following columns from the %_segdir table:
120048 **
120049 **   0: idx
120050 **   1: start_block
120051 **   2: leaves_end_block
120052 **   3: end_block
120053 **   4: root
120054 */
120055 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
120056   Fts3Table *p,                   /* FTS3 table */
120057   int iIndex,                     /* Index for p->aIndex[] */
120058   int iLevel,                     /* Level to select */
120059   sqlite3_stmt **ppStmt           /* OUT: Compiled statement */
120060 ){
120061   int rc;
120062   sqlite3_stmt *pStmt = 0;
120063
120064   assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
120065   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
120066   assert( iIndex>=0 && iIndex<p->nIndex );
120067
120068   if( iLevel<0 ){
120069     /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
120070     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
120071     if( rc==SQLITE_OK ){ 
120072       sqlite3_bind_int(pStmt, 1, iIndex*FTS3_SEGDIR_MAXLEVEL);
120073       sqlite3_bind_int(pStmt, 2, (iIndex+1)*FTS3_SEGDIR_MAXLEVEL-1);
120074     }
120075   }else{
120076     /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
120077     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
120078     if( rc==SQLITE_OK ){ 
120079       sqlite3_bind_int(pStmt, 1, iLevel+iIndex*FTS3_SEGDIR_MAXLEVEL);
120080     }
120081   }
120082   *ppStmt = pStmt;
120083   return rc;
120084 }
120085
120086
120087 /*
120088 ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
120089 ** if successful, or an SQLite error code otherwise.
120090 **
120091 ** This function also serves to allocate the PendingList structure itself.
120092 ** For example, to create a new PendingList structure containing two
120093 ** varints:
120094 **
120095 **   PendingList *p = 0;
120096 **   fts3PendingListAppendVarint(&p, 1);
120097 **   fts3PendingListAppendVarint(&p, 2);
120098 */
120099 static int fts3PendingListAppendVarint(
120100   PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
120101   sqlite3_int64 i                 /* Value to append to data */
120102 ){
120103   PendingList *p = *pp;
120104
120105   /* Allocate or grow the PendingList as required. */
120106   if( !p ){
120107     p = sqlite3_malloc(sizeof(*p) + 100);
120108     if( !p ){
120109       return SQLITE_NOMEM;
120110     }
120111     p->nSpace = 100;
120112     p->aData = (char *)&p[1];
120113     p->nData = 0;
120114   }
120115   else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
120116     int nNew = p->nSpace * 2;
120117     p = sqlite3_realloc(p, sizeof(*p) + nNew);
120118     if( !p ){
120119       sqlite3_free(*pp);
120120       *pp = 0;
120121       return SQLITE_NOMEM;
120122     }
120123     p->nSpace = nNew;
120124     p->aData = (char *)&p[1];
120125   }
120126
120127   /* Append the new serialized varint to the end of the list. */
120128   p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
120129   p->aData[p->nData] = '\0';
120130   *pp = p;
120131   return SQLITE_OK;
120132 }
120133
120134 /*
120135 ** Add a docid/column/position entry to a PendingList structure. Non-zero
120136 ** is returned if the structure is sqlite3_realloced as part of adding
120137 ** the entry. Otherwise, zero.
120138 **
120139 ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
120140 ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
120141 ** it is set to SQLITE_OK.
120142 */
120143 static int fts3PendingListAppend(
120144   PendingList **pp,               /* IN/OUT: PendingList structure */
120145   sqlite3_int64 iDocid,           /* Docid for entry to add */
120146   sqlite3_int64 iCol,             /* Column for entry to add */
120147   sqlite3_int64 iPos,             /* Position of term for entry to add */
120148   int *pRc                        /* OUT: Return code */
120149 ){
120150   PendingList *p = *pp;
120151   int rc = SQLITE_OK;
120152
120153   assert( !p || p->iLastDocid<=iDocid );
120154
120155   if( !p || p->iLastDocid!=iDocid ){
120156     sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
120157     if( p ){
120158       assert( p->nData<p->nSpace );
120159       assert( p->aData[p->nData]==0 );
120160       p->nData++;
120161     }
120162     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
120163       goto pendinglistappend_out;
120164     }
120165     p->iLastCol = -1;
120166     p->iLastPos = 0;
120167     p->iLastDocid = iDocid;
120168   }
120169   if( iCol>0 && p->iLastCol!=iCol ){
120170     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
120171      || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
120172     ){
120173       goto pendinglistappend_out;
120174     }
120175     p->iLastCol = iCol;
120176     p->iLastPos = 0;
120177   }
120178   if( iCol>=0 ){
120179     assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
120180     rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
120181     if( rc==SQLITE_OK ){
120182       p->iLastPos = iPos;
120183     }
120184   }
120185
120186  pendinglistappend_out:
120187   *pRc = rc;
120188   if( p!=*pp ){
120189     *pp = p;
120190     return 1;
120191   }
120192   return 0;
120193 }
120194
120195 /*
120196 ** Free a PendingList object allocated by fts3PendingListAppend().
120197 */
120198 static void fts3PendingListDelete(PendingList *pList){
120199   sqlite3_free(pList);
120200 }
120201
120202 /*
120203 ** Add an entry to one of the pending-terms hash tables.
120204 */
120205 static int fts3PendingTermsAddOne(
120206   Fts3Table *p,
120207   int iCol,
120208   int iPos,
120209   Fts3Hash *pHash,                /* Pending terms hash table to add entry to */
120210   const char *zToken,
120211   int nToken
120212 ){
120213   PendingList *pList;
120214   int rc = SQLITE_OK;
120215
120216   pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
120217   if( pList ){
120218     p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
120219   }
120220   if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
120221     if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
120222       /* Malloc failed while inserting the new entry. This can only 
120223       ** happen if there was no previous entry for this token.
120224       */
120225       assert( 0==fts3HashFind(pHash, zToken, nToken) );
120226       sqlite3_free(pList);
120227       rc = SQLITE_NOMEM;
120228     }
120229   }
120230   if( rc==SQLITE_OK ){
120231     p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
120232   }
120233   return rc;
120234 }
120235
120236 /*
120237 ** Tokenize the nul-terminated string zText and add all tokens to the
120238 ** pending-terms hash-table. The docid used is that currently stored in
120239 ** p->iPrevDocid, and the column is specified by argument iCol.
120240 **
120241 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
120242 */
120243 static int fts3PendingTermsAdd(
120244   Fts3Table *p,                   /* Table into which text will be inserted */
120245   const char *zText,              /* Text of document to be inserted */
120246   int iCol,                       /* Column into which text is being inserted */
120247   u32 *pnWord                     /* OUT: Number of tokens inserted */
120248 ){
120249   int rc;
120250   int iStart;
120251   int iEnd;
120252   int iPos;
120253   int nWord = 0;
120254
120255   char const *zToken;
120256   int nToken;
120257
120258   sqlite3_tokenizer *pTokenizer = p->pTokenizer;
120259   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
120260   sqlite3_tokenizer_cursor *pCsr;
120261   int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
120262       const char**,int*,int*,int*,int*);
120263
120264   assert( pTokenizer && pModule );
120265
120266   /* If the user has inserted a NULL value, this function may be called with
120267   ** zText==0. In this case, add zero token entries to the hash table and 
120268   ** return early. */
120269   if( zText==0 ){
120270     *pnWord = 0;
120271     return SQLITE_OK;
120272   }
120273
120274   rc = pModule->xOpen(pTokenizer, zText, -1, &pCsr);
120275   if( rc!=SQLITE_OK ){
120276     return rc;
120277   }
120278   pCsr->pTokenizer = pTokenizer;
120279
120280   xNext = pModule->xNext;
120281   while( SQLITE_OK==rc
120282       && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
120283   ){
120284     int i;
120285     if( iPos>=nWord ) nWord = iPos+1;
120286
120287     /* Positions cannot be negative; we use -1 as a terminator internally.
120288     ** Tokens must have a non-zero length.
120289     */
120290     if( iPos<0 || !zToken || nToken<=0 ){
120291       rc = SQLITE_ERROR;
120292       break;
120293     }
120294
120295     /* Add the term to the terms index */
120296     rc = fts3PendingTermsAddOne(
120297         p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
120298     );
120299     
120300     /* Add the term to each of the prefix indexes that it is not too 
120301     ** short for. */
120302     for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
120303       struct Fts3Index *pIndex = &p->aIndex[i];
120304       if( nToken<pIndex->nPrefix ) continue;
120305       rc = fts3PendingTermsAddOne(
120306           p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
120307       );
120308     }
120309   }
120310
120311   pModule->xClose(pCsr);
120312   *pnWord = nWord;
120313   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
120314 }
120315
120316 /* 
120317 ** Calling this function indicates that subsequent calls to 
120318 ** fts3PendingTermsAdd() are to add term/position-list pairs for the
120319 ** contents of the document with docid iDocid.
120320 */
120321 static int fts3PendingTermsDocid(Fts3Table *p, sqlite_int64 iDocid){
120322   /* TODO(shess) Explore whether partially flushing the buffer on
120323   ** forced-flush would provide better performance.  I suspect that if
120324   ** we ordered the doclists by size and flushed the largest until the
120325   ** buffer was half empty, that would let the less frequent terms
120326   ** generate longer doclists.
120327   */
120328   if( iDocid<=p->iPrevDocid || p->nPendingData>p->nMaxPendingData ){
120329     int rc = sqlite3Fts3PendingTermsFlush(p);
120330     if( rc!=SQLITE_OK ) return rc;
120331   }
120332   p->iPrevDocid = iDocid;
120333   return SQLITE_OK;
120334 }
120335
120336 /*
120337 ** Discard the contents of the pending-terms hash tables. 
120338 */
120339 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
120340   int i;
120341   for(i=0; i<p->nIndex; i++){
120342     Fts3HashElem *pElem;
120343     Fts3Hash *pHash = &p->aIndex[i].hPending;
120344     for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
120345       PendingList *pList = (PendingList *)fts3HashData(pElem);
120346       fts3PendingListDelete(pList);
120347     }
120348     fts3HashClear(pHash);
120349   }
120350   p->nPendingData = 0;
120351 }
120352
120353 /*
120354 ** This function is called by the xUpdate() method as part of an INSERT
120355 ** operation. It adds entries for each term in the new record to the
120356 ** pendingTerms hash table.
120357 **
120358 ** Argument apVal is the same as the similarly named argument passed to
120359 ** fts3InsertData(). Parameter iDocid is the docid of the new row.
120360 */
120361 static int fts3InsertTerms(Fts3Table *p, sqlite3_value **apVal, u32 *aSz){
120362   int i;                          /* Iterator variable */
120363   for(i=2; i<p->nColumn+2; i++){
120364     const char *zText = (const char *)sqlite3_value_text(apVal[i]);
120365     int rc = fts3PendingTermsAdd(p, zText, i-2, &aSz[i-2]);
120366     if( rc!=SQLITE_OK ){
120367       return rc;
120368     }
120369     aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
120370   }
120371   return SQLITE_OK;
120372 }
120373
120374 /*
120375 ** This function is called by the xUpdate() method for an INSERT operation.
120376 ** The apVal parameter is passed a copy of the apVal argument passed by
120377 ** SQLite to the xUpdate() method. i.e:
120378 **
120379 **   apVal[0]                Not used for INSERT.
120380 **   apVal[1]                rowid
120381 **   apVal[2]                Left-most user-defined column
120382 **   ...
120383 **   apVal[p->nColumn+1]     Right-most user-defined column
120384 **   apVal[p->nColumn+2]     Hidden column with same name as table
120385 **   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
120386 */
120387 static int fts3InsertData(
120388   Fts3Table *p,                   /* Full-text table */
120389   sqlite3_value **apVal,          /* Array of values to insert */
120390   sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
120391 ){
120392   int rc;                         /* Return code */
120393   sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
120394
120395   /* Locate the statement handle used to insert data into the %_content
120396   ** table. The SQL for this statement is:
120397   **
120398   **   INSERT INTO %_content VALUES(?, ?, ?, ...)
120399   **
120400   ** The statement features N '?' variables, where N is the number of user
120401   ** defined columns in the FTS3 table, plus one for the docid field.
120402   */
120403   rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
120404   if( rc!=SQLITE_OK ){
120405     return rc;
120406   }
120407
120408   /* There is a quirk here. The users INSERT statement may have specified
120409   ** a value for the "rowid" field, for the "docid" field, or for both.
120410   ** Which is a problem, since "rowid" and "docid" are aliases for the
120411   ** same value. For example:
120412   **
120413   **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
120414   **
120415   ** In FTS3, this is an error. It is an error to specify non-NULL values
120416   ** for both docid and some other rowid alias.
120417   */
120418   if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
120419     if( SQLITE_NULL==sqlite3_value_type(apVal[0])
120420      && SQLITE_NULL!=sqlite3_value_type(apVal[1])
120421     ){
120422       /* A rowid/docid conflict. */
120423       return SQLITE_ERROR;
120424     }
120425     rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
120426     if( rc!=SQLITE_OK ) return rc;
120427   }
120428
120429   /* Execute the statement to insert the record. Set *piDocid to the 
120430   ** new docid value. 
120431   */
120432   sqlite3_step(pContentInsert);
120433   rc = sqlite3_reset(pContentInsert);
120434
120435   *piDocid = sqlite3_last_insert_rowid(p->db);
120436   return rc;
120437 }
120438
120439
120440
120441 /*
120442 ** Remove all data from the FTS3 table. Clear the hash table containing
120443 ** pending terms.
120444 */
120445 static int fts3DeleteAll(Fts3Table *p){
120446   int rc = SQLITE_OK;             /* Return code */
120447
120448   /* Discard the contents of the pending-terms hash table. */
120449   sqlite3Fts3PendingTermsClear(p);
120450
120451   /* Delete everything from the %_content, %_segments and %_segdir tables. */
120452   fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
120453   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
120454   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
120455   if( p->bHasDocsize ){
120456     fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
120457   }
120458   if( p->bHasStat ){
120459     fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
120460   }
120461   return rc;
120462 }
120463
120464 /*
120465 ** The first element in the apVal[] array is assumed to contain the docid
120466 ** (an integer) of a row about to be deleted. Remove all terms from the
120467 ** full-text index.
120468 */
120469 static void fts3DeleteTerms( 
120470   int *pRC,               /* Result code */
120471   Fts3Table *p,           /* The FTS table to delete from */
120472   sqlite3_value *pRowid,  /* The docid to be deleted */
120473   u32 *aSz                /* Sizes of deleted document written here */
120474 ){
120475   int rc;
120476   sqlite3_stmt *pSelect;
120477
120478   if( *pRC ) return;
120479   rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
120480   if( rc==SQLITE_OK ){
120481     if( SQLITE_ROW==sqlite3_step(pSelect) ){
120482       int i;
120483       for(i=1; i<=p->nColumn; i++){
120484         const char *zText = (const char *)sqlite3_column_text(pSelect, i);
120485         rc = fts3PendingTermsAdd(p, zText, -1, &aSz[i-1]);
120486         if( rc!=SQLITE_OK ){
120487           sqlite3_reset(pSelect);
120488           *pRC = rc;
120489           return;
120490         }
120491         aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
120492       }
120493     }
120494     rc = sqlite3_reset(pSelect);
120495   }else{
120496     sqlite3_reset(pSelect);
120497   }
120498   *pRC = rc;
120499 }
120500
120501 /*
120502 ** Forward declaration to account for the circular dependency between
120503 ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
120504 */
120505 static int fts3SegmentMerge(Fts3Table *, int, int);
120506
120507 /* 
120508 ** This function allocates a new level iLevel index in the segdir table.
120509 ** Usually, indexes are allocated within a level sequentially starting
120510 ** with 0, so the allocated index is one greater than the value returned
120511 ** by:
120512 **
120513 **   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
120514 **
120515 ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
120516 ** level, they are merged into a single level (iLevel+1) segment and the 
120517 ** allocated index is 0.
120518 **
120519 ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
120520 ** returned. Otherwise, an SQLite error code is returned.
120521 */
120522 static int fts3AllocateSegdirIdx(
120523   Fts3Table *p, 
120524   int iIndex,                     /* Index for p->aIndex */
120525   int iLevel, 
120526   int *piIdx
120527 ){
120528   int rc;                         /* Return Code */
120529   sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
120530   int iNext = 0;                  /* Result of query pNextIdx */
120531
120532   /* Set variable iNext to the next available segdir index at level iLevel. */
120533   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
120534   if( rc==SQLITE_OK ){
120535     sqlite3_bind_int(pNextIdx, 1, iIndex*FTS3_SEGDIR_MAXLEVEL + iLevel);
120536     if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
120537       iNext = sqlite3_column_int(pNextIdx, 0);
120538     }
120539     rc = sqlite3_reset(pNextIdx);
120540   }
120541
120542   if( rc==SQLITE_OK ){
120543     /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
120544     ** full, merge all segments in level iLevel into a single iLevel+1
120545     ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
120546     ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
120547     */
120548     if( iNext>=FTS3_MERGE_COUNT ){
120549       rc = fts3SegmentMerge(p, iIndex, iLevel);
120550       *piIdx = 0;
120551     }else{
120552       *piIdx = iNext;
120553     }
120554   }
120555
120556   return rc;
120557 }
120558
120559 /*
120560 ** The %_segments table is declared as follows:
120561 **
120562 **   CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
120563 **
120564 ** This function reads data from a single row of the %_segments table. The
120565 ** specific row is identified by the iBlockid parameter. If paBlob is not
120566 ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
120567 ** with the contents of the blob stored in the "block" column of the 
120568 ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
120569 ** to the size of the blob in bytes before returning.
120570 **
120571 ** If an error occurs, or the table does not contain the specified row,
120572 ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
120573 ** paBlob is non-NULL, then it is the responsibility of the caller to
120574 ** eventually free the returned buffer.
120575 **
120576 ** This function may leave an open sqlite3_blob* handle in the
120577 ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
120578 ** to this function. The handle may be closed by calling the
120579 ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
120580 ** performance improvement, but the blob handle should always be closed
120581 ** before control is returned to the user (to prevent a lock being held
120582 ** on the database file for longer than necessary). Thus, any virtual table
120583 ** method (xFilter etc.) that may directly or indirectly call this function
120584 ** must call sqlite3Fts3SegmentsClose() before returning.
120585 */
120586 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
120587   Fts3Table *p,                   /* FTS3 table handle */
120588   sqlite3_int64 iBlockid,         /* Access the row with blockid=$iBlockid */
120589   char **paBlob,                  /* OUT: Blob data in malloc'd buffer */
120590   int *pnBlob,                    /* OUT: Size of blob data */
120591   int *pnLoad                     /* OUT: Bytes actually loaded */
120592 ){
120593   int rc;                         /* Return code */
120594
120595   /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
120596   assert( pnBlob);
120597
120598   if( p->pSegments ){
120599     rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
120600   }else{
120601     if( 0==p->zSegmentsTbl ){
120602       p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
120603       if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
120604     }
120605     rc = sqlite3_blob_open(
120606        p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
120607     );
120608   }
120609
120610   if( rc==SQLITE_OK ){
120611     int nByte = sqlite3_blob_bytes(p->pSegments);
120612     *pnBlob = nByte;
120613     if( paBlob ){
120614       char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
120615       if( !aByte ){
120616         rc = SQLITE_NOMEM;
120617       }else{
120618         if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
120619           nByte = FTS3_NODE_CHUNKSIZE;
120620           *pnLoad = nByte;
120621         }
120622         rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
120623         memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
120624         if( rc!=SQLITE_OK ){
120625           sqlite3_free(aByte);
120626           aByte = 0;
120627         }
120628       }
120629       *paBlob = aByte;
120630     }
120631   }
120632
120633   return rc;
120634 }
120635
120636 /*
120637 ** Close the blob handle at p->pSegments, if it is open. See comments above
120638 ** the sqlite3Fts3ReadBlock() function for details.
120639 */
120640 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
120641   sqlite3_blob_close(p->pSegments);
120642   p->pSegments = 0;
120643 }
120644     
120645 static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
120646   int nRead;                      /* Number of bytes to read */
120647   int rc;                         /* Return code */
120648
120649   nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
120650   rc = sqlite3_blob_read(
120651       pReader->pBlob, 
120652       &pReader->aNode[pReader->nPopulate],
120653       nRead,
120654       pReader->nPopulate
120655   );
120656
120657   if( rc==SQLITE_OK ){
120658     pReader->nPopulate += nRead;
120659     memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
120660     if( pReader->nPopulate==pReader->nNode ){
120661       sqlite3_blob_close(pReader->pBlob);
120662       pReader->pBlob = 0;
120663       pReader->nPopulate = 0;
120664     }
120665   }
120666   return rc;
120667 }
120668
120669 static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
120670   int rc = SQLITE_OK;
120671   assert( !pReader->pBlob 
120672        || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
120673   );
120674   while( pReader->pBlob && rc==SQLITE_OK 
120675      &&  (pFrom - pReader->aNode + nByte)>pReader->nPopulate
120676   ){
120677     rc = fts3SegReaderIncrRead(pReader);
120678   }
120679   return rc;
120680 }
120681
120682 /*
120683 ** Move the iterator passed as the first argument to the next term in the
120684 ** segment. If successful, SQLITE_OK is returned. If there is no next term,
120685 ** SQLITE_DONE. Otherwise, an SQLite error code.
120686 */
120687 static int fts3SegReaderNext(
120688   Fts3Table *p, 
120689   Fts3SegReader *pReader,
120690   int bIncr
120691 ){
120692   int rc;                         /* Return code of various sub-routines */
120693   char *pNext;                    /* Cursor variable */
120694   int nPrefix;                    /* Number of bytes in term prefix */
120695   int nSuffix;                    /* Number of bytes in term suffix */
120696
120697   if( !pReader->aDoclist ){
120698     pNext = pReader->aNode;
120699   }else{
120700     pNext = &pReader->aDoclist[pReader->nDoclist];
120701   }
120702
120703   if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
120704
120705     if( fts3SegReaderIsPending(pReader) ){
120706       Fts3HashElem *pElem = *(pReader->ppNextElem);
120707       if( pElem==0 ){
120708         pReader->aNode = 0;
120709       }else{
120710         PendingList *pList = (PendingList *)fts3HashData(pElem);
120711         pReader->zTerm = (char *)fts3HashKey(pElem);
120712         pReader->nTerm = fts3HashKeysize(pElem);
120713         pReader->nNode = pReader->nDoclist = pList->nData + 1;
120714         pReader->aNode = pReader->aDoclist = pList->aData;
120715         pReader->ppNextElem++;
120716         assert( pReader->aNode );
120717       }
120718       return SQLITE_OK;
120719     }
120720
120721     if( !fts3SegReaderIsRootOnly(pReader) ){
120722       sqlite3_free(pReader->aNode);
120723       sqlite3_blob_close(pReader->pBlob);
120724       pReader->pBlob = 0;
120725     }
120726     pReader->aNode = 0;
120727
120728     /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf 
120729     ** blocks have already been traversed.  */
120730     assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
120731     if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
120732       return SQLITE_OK;
120733     }
120734
120735     rc = sqlite3Fts3ReadBlock(
120736         p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode, 
120737         (bIncr ? &pReader->nPopulate : 0)
120738     );
120739     if( rc!=SQLITE_OK ) return rc;
120740     assert( pReader->pBlob==0 );
120741     if( bIncr && pReader->nPopulate<pReader->nNode ){
120742       pReader->pBlob = p->pSegments;
120743       p->pSegments = 0;
120744     }
120745     pNext = pReader->aNode;
120746   }
120747
120748   assert( !fts3SegReaderIsPending(pReader) );
120749
120750   rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
120751   if( rc!=SQLITE_OK ) return rc;
120752   
120753   /* Because of the FTS3_NODE_PADDING bytes of padding, the following is 
120754   ** safe (no risk of overread) even if the node data is corrupted. */
120755   pNext += sqlite3Fts3GetVarint32(pNext, &nPrefix);
120756   pNext += sqlite3Fts3GetVarint32(pNext, &nSuffix);
120757   if( nPrefix<0 || nSuffix<=0 
120758    || &pNext[nSuffix]>&pReader->aNode[pReader->nNode] 
120759   ){
120760     return SQLITE_CORRUPT_VTAB;
120761   }
120762
120763   if( nPrefix+nSuffix>pReader->nTermAlloc ){
120764     int nNew = (nPrefix+nSuffix)*2;
120765     char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
120766     if( !zNew ){
120767       return SQLITE_NOMEM;
120768     }
120769     pReader->zTerm = zNew;
120770     pReader->nTermAlloc = nNew;
120771   }
120772
120773   rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
120774   if( rc!=SQLITE_OK ) return rc;
120775
120776   memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
120777   pReader->nTerm = nPrefix+nSuffix;
120778   pNext += nSuffix;
120779   pNext += sqlite3Fts3GetVarint32(pNext, &pReader->nDoclist);
120780   pReader->aDoclist = pNext;
120781   pReader->pOffsetList = 0;
120782
120783   /* Check that the doclist does not appear to extend past the end of the
120784   ** b-tree node. And that the final byte of the doclist is 0x00. If either 
120785   ** of these statements is untrue, then the data structure is corrupt.
120786   */
120787   if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode] 
120788    || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
120789   ){
120790     return SQLITE_CORRUPT_VTAB;
120791   }
120792   return SQLITE_OK;
120793 }
120794
120795 /*
120796 ** Set the SegReader to point to the first docid in the doclist associated
120797 ** with the current term.
120798 */
120799 static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
120800   int rc = SQLITE_OK;
120801   assert( pReader->aDoclist );
120802   assert( !pReader->pOffsetList );
120803   if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
120804     u8 bEof = 0;
120805     pReader->iDocid = 0;
120806     pReader->nOffsetList = 0;
120807     sqlite3Fts3DoclistPrev(0,
120808         pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList, 
120809         &pReader->iDocid, &pReader->nOffsetList, &bEof
120810     );
120811   }else{
120812     rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
120813     if( rc==SQLITE_OK ){
120814       int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
120815       pReader->pOffsetList = &pReader->aDoclist[n];
120816     }
120817   }
120818   return rc;
120819 }
120820
120821 /*
120822 ** Advance the SegReader to point to the next docid in the doclist
120823 ** associated with the current term.
120824 ** 
120825 ** If arguments ppOffsetList and pnOffsetList are not NULL, then 
120826 ** *ppOffsetList is set to point to the first column-offset list
120827 ** in the doclist entry (i.e. immediately past the docid varint).
120828 ** *pnOffsetList is set to the length of the set of column-offset
120829 ** lists, not including the nul-terminator byte. For example:
120830 */
120831 static int fts3SegReaderNextDocid(
120832   Fts3Table *pTab,
120833   Fts3SegReader *pReader,         /* Reader to advance to next docid */
120834   char **ppOffsetList,            /* OUT: Pointer to current position-list */
120835   int *pnOffsetList               /* OUT: Length of *ppOffsetList in bytes */
120836 ){
120837   int rc = SQLITE_OK;
120838   char *p = pReader->pOffsetList;
120839   char c = 0;
120840
120841   assert( p );
120842
120843   if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
120844     /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
120845     ** Pending-terms doclists are always built up in ascending order, so
120846     ** we have to iterate through them backwards here. */
120847     u8 bEof = 0;
120848     if( ppOffsetList ){
120849       *ppOffsetList = pReader->pOffsetList;
120850       *pnOffsetList = pReader->nOffsetList - 1;
120851     }
120852     sqlite3Fts3DoclistPrev(0,
120853         pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
120854         &pReader->nOffsetList, &bEof
120855     );
120856     if( bEof ){
120857       pReader->pOffsetList = 0;
120858     }else{
120859       pReader->pOffsetList = p;
120860     }
120861   }else{
120862     char *pEnd = &pReader->aDoclist[pReader->nDoclist];
120863
120864     /* Pointer p currently points at the first byte of an offset list. The
120865     ** following block advances it to point one byte past the end of
120866     ** the same offset list. */
120867     while( 1 ){
120868   
120869       /* The following line of code (and the "p++" below the while() loop) is
120870       ** normally all that is required to move pointer p to the desired 
120871       ** position. The exception is if this node is being loaded from disk
120872       ** incrementally and pointer "p" now points to the first byte passed
120873       ** the populated part of pReader->aNode[].
120874       */
120875       while( *p | c ) c = *p++ & 0x80;
120876       assert( *p==0 );
120877   
120878       if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
120879       rc = fts3SegReaderIncrRead(pReader);
120880       if( rc!=SQLITE_OK ) return rc;
120881     }
120882     p++;
120883   
120884     /* If required, populate the output variables with a pointer to and the
120885     ** size of the previous offset-list.
120886     */
120887     if( ppOffsetList ){
120888       *ppOffsetList = pReader->pOffsetList;
120889       *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
120890     }
120891
120892     while( p<pEnd && *p==0 ) p++;
120893   
120894     /* If there are no more entries in the doclist, set pOffsetList to
120895     ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
120896     ** Fts3SegReader.pOffsetList to point to the next offset list before
120897     ** returning.
120898     */
120899     if( p>=pEnd ){
120900       pReader->pOffsetList = 0;
120901     }else{
120902       rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
120903       if( rc==SQLITE_OK ){
120904         sqlite3_int64 iDelta;
120905         pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
120906         if( pTab->bDescIdx ){
120907           pReader->iDocid -= iDelta;
120908         }else{
120909           pReader->iDocid += iDelta;
120910         }
120911       }
120912     }
120913   }
120914
120915   return SQLITE_OK;
120916 }
120917
120918
120919 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
120920   Fts3Cursor *pCsr, 
120921   Fts3MultiSegReader *pMsr,
120922   int *pnOvfl
120923 ){
120924   Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
120925   int nOvfl = 0;
120926   int ii;
120927   int rc = SQLITE_OK;
120928   int pgsz = p->nPgsz;
120929
120930   assert( p->bHasStat );
120931   assert( pgsz>0 );
120932
120933   for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
120934     Fts3SegReader *pReader = pMsr->apSegment[ii];
120935     if( !fts3SegReaderIsPending(pReader) 
120936      && !fts3SegReaderIsRootOnly(pReader) 
120937     ){
120938       sqlite3_int64 jj;
120939       for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
120940         int nBlob;
120941         rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
120942         if( rc!=SQLITE_OK ) break;
120943         if( (nBlob+35)>pgsz ){
120944           nOvfl += (nBlob + 34)/pgsz;
120945         }
120946       }
120947     }
120948   }
120949   *pnOvfl = nOvfl;
120950   return rc;
120951 }
120952
120953 /*
120954 ** Free all allocations associated with the iterator passed as the 
120955 ** second argument.
120956 */
120957 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
120958   if( pReader && !fts3SegReaderIsPending(pReader) ){
120959     sqlite3_free(pReader->zTerm);
120960     if( !fts3SegReaderIsRootOnly(pReader) ){
120961       sqlite3_free(pReader->aNode);
120962       sqlite3_blob_close(pReader->pBlob);
120963     }
120964   }
120965   sqlite3_free(pReader);
120966 }
120967
120968 /*
120969 ** Allocate a new SegReader object.
120970 */
120971 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
120972   int iAge,                       /* Segment "age". */
120973   sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
120974   sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
120975   sqlite3_int64 iEndBlock,        /* Final block of segment */
120976   const char *zRoot,              /* Buffer containing root node */
120977   int nRoot,                      /* Size of buffer containing root node */
120978   Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
120979 ){
120980   int rc = SQLITE_OK;             /* Return code */
120981   Fts3SegReader *pReader;         /* Newly allocated SegReader object */
120982   int nExtra = 0;                 /* Bytes to allocate segment root node */
120983
120984   assert( iStartLeaf<=iEndLeaf );
120985   if( iStartLeaf==0 ){
120986     nExtra = nRoot + FTS3_NODE_PADDING;
120987   }
120988
120989   pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
120990   if( !pReader ){
120991     return SQLITE_NOMEM;
120992   }
120993   memset(pReader, 0, sizeof(Fts3SegReader));
120994   pReader->iIdx = iAge;
120995   pReader->iStartBlock = iStartLeaf;
120996   pReader->iLeafEndBlock = iEndLeaf;
120997   pReader->iEndBlock = iEndBlock;
120998
120999   if( nExtra ){
121000     /* The entire segment is stored in the root node. */
121001     pReader->aNode = (char *)&pReader[1];
121002     pReader->nNode = nRoot;
121003     memcpy(pReader->aNode, zRoot, nRoot);
121004     memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
121005   }else{
121006     pReader->iCurrentBlock = iStartLeaf-1;
121007   }
121008
121009   if( rc==SQLITE_OK ){
121010     *ppReader = pReader;
121011   }else{
121012     sqlite3Fts3SegReaderFree(pReader);
121013   }
121014   return rc;
121015 }
121016
121017 /*
121018 ** This is a comparison function used as a qsort() callback when sorting
121019 ** an array of pending terms by term. This occurs as part of flushing
121020 ** the contents of the pending-terms hash table to the database.
121021 */
121022 static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
121023   char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
121024   char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
121025   int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
121026   int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
121027
121028   int n = (n1<n2 ? n1 : n2);
121029   int c = memcmp(z1, z2, n);
121030   if( c==0 ){
121031     c = n1 - n2;
121032   }
121033   return c;
121034 }
121035
121036 /*
121037 ** This function is used to allocate an Fts3SegReader that iterates through
121038 ** a subset of the terms stored in the Fts3Table.pendingTerms array.
121039 **
121040 ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
121041 ** through each term in the pending-terms table. Or, if isPrefixIter is
121042 ** non-zero, it iterates through each term and its prefixes. For example, if
121043 ** the pending terms hash table contains the terms "sqlite", "mysql" and
121044 ** "firebird", then the iterator visits the following 'terms' (in the order
121045 ** shown):
121046 **
121047 **   f fi fir fire fireb firebi firebir firebird
121048 **   m my mys mysq mysql
121049 **   s sq sql sqli sqlit sqlite
121050 **
121051 ** Whereas if isPrefixIter is zero, the terms visited are:
121052 **
121053 **   firebird mysql sqlite
121054 */
121055 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
121056   Fts3Table *p,                   /* Virtual table handle */
121057   int iIndex,                     /* Index for p->aIndex */
121058   const char *zTerm,              /* Term to search for */
121059   int nTerm,                      /* Size of buffer zTerm */
121060   int bPrefix,                    /* True for a prefix iterator */
121061   Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
121062 ){
121063   Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
121064   Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
121065   int nElem = 0;                  /* Size of array at aElem */
121066   int rc = SQLITE_OK;             /* Return Code */
121067   Fts3Hash *pHash;
121068
121069   pHash = &p->aIndex[iIndex].hPending;
121070   if( bPrefix ){
121071     int nAlloc = 0;               /* Size of allocated array at aElem */
121072     Fts3HashElem *pE = 0;         /* Iterator variable */
121073
121074     for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
121075       char *zKey = (char *)fts3HashKey(pE);
121076       int nKey = fts3HashKeysize(pE);
121077       if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
121078         if( nElem==nAlloc ){
121079           Fts3HashElem **aElem2;
121080           nAlloc += 16;
121081           aElem2 = (Fts3HashElem **)sqlite3_realloc(
121082               aElem, nAlloc*sizeof(Fts3HashElem *)
121083           );
121084           if( !aElem2 ){
121085             rc = SQLITE_NOMEM;
121086             nElem = 0;
121087             break;
121088           }
121089           aElem = aElem2;
121090         }
121091
121092         aElem[nElem++] = pE;
121093       }
121094     }
121095
121096     /* If more than one term matches the prefix, sort the Fts3HashElem
121097     ** objects in term order using qsort(). This uses the same comparison
121098     ** callback as is used when flushing terms to disk.
121099     */
121100     if( nElem>1 ){
121101       qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
121102     }
121103
121104   }else{
121105     /* The query is a simple term lookup that matches at most one term in
121106     ** the index. All that is required is a straight hash-lookup. */
121107     Fts3HashElem *pE = fts3HashFindElem(pHash, zTerm, nTerm);
121108     if( pE ){
121109       aElem = &pE;
121110       nElem = 1;
121111     }
121112   }
121113
121114   if( nElem>0 ){
121115     int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
121116     pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
121117     if( !pReader ){
121118       rc = SQLITE_NOMEM;
121119     }else{
121120       memset(pReader, 0, nByte);
121121       pReader->iIdx = 0x7FFFFFFF;
121122       pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
121123       memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
121124     }
121125   }
121126
121127   if( bPrefix ){
121128     sqlite3_free(aElem);
121129   }
121130   *ppReader = pReader;
121131   return rc;
121132 }
121133
121134 /*
121135 ** Compare the entries pointed to by two Fts3SegReader structures. 
121136 ** Comparison is as follows:
121137 **
121138 **   1) EOF is greater than not EOF.
121139 **
121140 **   2) The current terms (if any) are compared using memcmp(). If one
121141 **      term is a prefix of another, the longer term is considered the
121142 **      larger.
121143 **
121144 **   3) By segment age. An older segment is considered larger.
121145 */
121146 static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
121147   int rc;
121148   if( pLhs->aNode && pRhs->aNode ){
121149     int rc2 = pLhs->nTerm - pRhs->nTerm;
121150     if( rc2<0 ){
121151       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
121152     }else{
121153       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
121154     }
121155     if( rc==0 ){
121156       rc = rc2;
121157     }
121158   }else{
121159     rc = (pLhs->aNode==0) - (pRhs->aNode==0);
121160   }
121161   if( rc==0 ){
121162     rc = pRhs->iIdx - pLhs->iIdx;
121163   }
121164   assert( rc!=0 );
121165   return rc;
121166 }
121167
121168 /*
121169 ** A different comparison function for SegReader structures. In this
121170 ** version, it is assumed that each SegReader points to an entry in
121171 ** a doclist for identical terms. Comparison is made as follows:
121172 **
121173 **   1) EOF (end of doclist in this case) is greater than not EOF.
121174 **
121175 **   2) By current docid.
121176 **
121177 **   3) By segment age. An older segment is considered larger.
121178 */
121179 static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
121180   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
121181   if( rc==0 ){
121182     if( pLhs->iDocid==pRhs->iDocid ){
121183       rc = pRhs->iIdx - pLhs->iIdx;
121184     }else{
121185       rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
121186     }
121187   }
121188   assert( pLhs->aNode && pRhs->aNode );
121189   return rc;
121190 }
121191 static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
121192   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
121193   if( rc==0 ){
121194     if( pLhs->iDocid==pRhs->iDocid ){
121195       rc = pRhs->iIdx - pLhs->iIdx;
121196     }else{
121197       rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
121198     }
121199   }
121200   assert( pLhs->aNode && pRhs->aNode );
121201   return rc;
121202 }
121203
121204 /*
121205 ** Compare the term that the Fts3SegReader object passed as the first argument
121206 ** points to with the term specified by arguments zTerm and nTerm. 
121207 **
121208 ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
121209 ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
121210 ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
121211 */
121212 static int fts3SegReaderTermCmp(
121213   Fts3SegReader *pSeg,            /* Segment reader object */
121214   const char *zTerm,              /* Term to compare to */
121215   int nTerm                       /* Size of term zTerm in bytes */
121216 ){
121217   int res = 0;
121218   if( pSeg->aNode ){
121219     if( pSeg->nTerm>nTerm ){
121220       res = memcmp(pSeg->zTerm, zTerm, nTerm);
121221     }else{
121222       res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
121223     }
121224     if( res==0 ){
121225       res = pSeg->nTerm-nTerm;
121226     }
121227   }
121228   return res;
121229 }
121230
121231 /*
121232 ** Argument apSegment is an array of nSegment elements. It is known that
121233 ** the final (nSegment-nSuspect) members are already in sorted order
121234 ** (according to the comparison function provided). This function shuffles
121235 ** the array around until all entries are in sorted order.
121236 */
121237 static void fts3SegReaderSort(
121238   Fts3SegReader **apSegment,                     /* Array to sort entries of */
121239   int nSegment,                                  /* Size of apSegment array */
121240   int nSuspect,                                  /* Unsorted entry count */
121241   int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
121242 ){
121243   int i;                          /* Iterator variable */
121244
121245   assert( nSuspect<=nSegment );
121246
121247   if( nSuspect==nSegment ) nSuspect--;
121248   for(i=nSuspect-1; i>=0; i--){
121249     int j;
121250     for(j=i; j<(nSegment-1); j++){
121251       Fts3SegReader *pTmp;
121252       if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
121253       pTmp = apSegment[j+1];
121254       apSegment[j+1] = apSegment[j];
121255       apSegment[j] = pTmp;
121256     }
121257   }
121258
121259 #ifndef NDEBUG
121260   /* Check that the list really is sorted now. */
121261   for(i=0; i<(nSuspect-1); i++){
121262     assert( xCmp(apSegment[i], apSegment[i+1])<0 );
121263   }
121264 #endif
121265 }
121266
121267 /* 
121268 ** Insert a record into the %_segments table.
121269 */
121270 static int fts3WriteSegment(
121271   Fts3Table *p,                   /* Virtual table handle */
121272   sqlite3_int64 iBlock,           /* Block id for new block */
121273   char *z,                        /* Pointer to buffer containing block data */
121274   int n                           /* Size of buffer z in bytes */
121275 ){
121276   sqlite3_stmt *pStmt;
121277   int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
121278   if( rc==SQLITE_OK ){
121279     sqlite3_bind_int64(pStmt, 1, iBlock);
121280     sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
121281     sqlite3_step(pStmt);
121282     rc = sqlite3_reset(pStmt);
121283   }
121284   return rc;
121285 }
121286
121287 /* 
121288 ** Insert a record into the %_segdir table.
121289 */
121290 static int fts3WriteSegdir(
121291   Fts3Table *p,                   /* Virtual table handle */
121292   int iLevel,                     /* Value for "level" field */
121293   int iIdx,                       /* Value for "idx" field */
121294   sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
121295   sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
121296   sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
121297   char *zRoot,                    /* Blob value for "root" field */
121298   int nRoot                       /* Number of bytes in buffer zRoot */
121299 ){
121300   sqlite3_stmt *pStmt;
121301   int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
121302   if( rc==SQLITE_OK ){
121303     sqlite3_bind_int(pStmt, 1, iLevel);
121304     sqlite3_bind_int(pStmt, 2, iIdx);
121305     sqlite3_bind_int64(pStmt, 3, iStartBlock);
121306     sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
121307     sqlite3_bind_int64(pStmt, 5, iEndBlock);
121308     sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
121309     sqlite3_step(pStmt);
121310     rc = sqlite3_reset(pStmt);
121311   }
121312   return rc;
121313 }
121314
121315 /*
121316 ** Return the size of the common prefix (if any) shared by zPrev and
121317 ** zNext, in bytes. For example, 
121318 **
121319 **   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
121320 **   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
121321 **   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
121322 */
121323 static int fts3PrefixCompress(
121324   const char *zPrev,              /* Buffer containing previous term */
121325   int nPrev,                      /* Size of buffer zPrev in bytes */
121326   const char *zNext,              /* Buffer containing next term */
121327   int nNext                       /* Size of buffer zNext in bytes */
121328 ){
121329   int n;
121330   UNUSED_PARAMETER(nNext);
121331   for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
121332   return n;
121333 }
121334
121335 /*
121336 ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
121337 ** (according to memcmp) than the previous term.
121338 */
121339 static int fts3NodeAddTerm(
121340   Fts3Table *p,                   /* Virtual table handle */
121341   SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */ 
121342   int isCopyTerm,                 /* True if zTerm/nTerm is transient */
121343   const char *zTerm,              /* Pointer to buffer containing term */
121344   int nTerm                       /* Size of term in bytes */
121345 ){
121346   SegmentNode *pTree = *ppTree;
121347   int rc;
121348   SegmentNode *pNew;
121349
121350   /* First try to append the term to the current node. Return early if 
121351   ** this is possible.
121352   */
121353   if( pTree ){
121354     int nData = pTree->nData;     /* Current size of node in bytes */
121355     int nReq = nData;             /* Required space after adding zTerm */
121356     int nPrefix;                  /* Number of bytes of prefix compression */
121357     int nSuffix;                  /* Suffix length */
121358
121359     nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
121360     nSuffix = nTerm-nPrefix;
121361
121362     nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
121363     if( nReq<=p->nNodeSize || !pTree->zTerm ){
121364
121365       if( nReq>p->nNodeSize ){
121366         /* An unusual case: this is the first term to be added to the node
121367         ** and the static node buffer (p->nNodeSize bytes) is not large
121368         ** enough. Use a separately malloced buffer instead This wastes
121369         ** p->nNodeSize bytes, but since this scenario only comes about when
121370         ** the database contain two terms that share a prefix of almost 2KB, 
121371         ** this is not expected to be a serious problem. 
121372         */
121373         assert( pTree->aData==(char *)&pTree[1] );
121374         pTree->aData = (char *)sqlite3_malloc(nReq);
121375         if( !pTree->aData ){
121376           return SQLITE_NOMEM;
121377         }
121378       }
121379
121380       if( pTree->zTerm ){
121381         /* There is no prefix-length field for first term in a node */
121382         nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
121383       }
121384
121385       nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
121386       memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
121387       pTree->nData = nData + nSuffix;
121388       pTree->nEntry++;
121389
121390       if( isCopyTerm ){
121391         if( pTree->nMalloc<nTerm ){
121392           char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
121393           if( !zNew ){
121394             return SQLITE_NOMEM;
121395           }
121396           pTree->nMalloc = nTerm*2;
121397           pTree->zMalloc = zNew;
121398         }
121399         pTree->zTerm = pTree->zMalloc;
121400         memcpy(pTree->zTerm, zTerm, nTerm);
121401         pTree->nTerm = nTerm;
121402       }else{
121403         pTree->zTerm = (char *)zTerm;
121404         pTree->nTerm = nTerm;
121405       }
121406       return SQLITE_OK;
121407     }
121408   }
121409
121410   /* If control flows to here, it was not possible to append zTerm to the
121411   ** current node. Create a new node (a right-sibling of the current node).
121412   ** If this is the first node in the tree, the term is added to it.
121413   **
121414   ** Otherwise, the term is not added to the new node, it is left empty for
121415   ** now. Instead, the term is inserted into the parent of pTree. If pTree 
121416   ** has no parent, one is created here.
121417   */
121418   pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
121419   if( !pNew ){
121420     return SQLITE_NOMEM;
121421   }
121422   memset(pNew, 0, sizeof(SegmentNode));
121423   pNew->nData = 1 + FTS3_VARINT_MAX;
121424   pNew->aData = (char *)&pNew[1];
121425
121426   if( pTree ){
121427     SegmentNode *pParent = pTree->pParent;
121428     rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
121429     if( pTree->pParent==0 ){
121430       pTree->pParent = pParent;
121431     }
121432     pTree->pRight = pNew;
121433     pNew->pLeftmost = pTree->pLeftmost;
121434     pNew->pParent = pParent;
121435     pNew->zMalloc = pTree->zMalloc;
121436     pNew->nMalloc = pTree->nMalloc;
121437     pTree->zMalloc = 0;
121438   }else{
121439     pNew->pLeftmost = pNew;
121440     rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm); 
121441   }
121442
121443   *ppTree = pNew;
121444   return rc;
121445 }
121446
121447 /*
121448 ** Helper function for fts3NodeWrite().
121449 */
121450 static int fts3TreeFinishNode(
121451   SegmentNode *pTree, 
121452   int iHeight, 
121453   sqlite3_int64 iLeftChild
121454 ){
121455   int nStart;
121456   assert( iHeight>=1 && iHeight<128 );
121457   nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
121458   pTree->aData[nStart] = (char)iHeight;
121459   sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
121460   return nStart;
121461 }
121462
121463 /*
121464 ** Write the buffer for the segment node pTree and all of its peers to the
121465 ** database. Then call this function recursively to write the parent of 
121466 ** pTree and its peers to the database. 
121467 **
121468 ** Except, if pTree is a root node, do not write it to the database. Instead,
121469 ** set output variables *paRoot and *pnRoot to contain the root node.
121470 **
121471 ** If successful, SQLITE_OK is returned and output variable *piLast is
121472 ** set to the largest blockid written to the database (or zero if no
121473 ** blocks were written to the db). Otherwise, an SQLite error code is 
121474 ** returned.
121475 */
121476 static int fts3NodeWrite(
121477   Fts3Table *p,                   /* Virtual table handle */
121478   SegmentNode *pTree,             /* SegmentNode handle */
121479   int iHeight,                    /* Height of this node in tree */
121480   sqlite3_int64 iLeaf,            /* Block id of first leaf node */
121481   sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
121482   sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
121483   char **paRoot,                  /* OUT: Data for root node */
121484   int *pnRoot                     /* OUT: Size of root node in bytes */
121485 ){
121486   int rc = SQLITE_OK;
121487
121488   if( !pTree->pParent ){
121489     /* Root node of the tree. */
121490     int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
121491     *piLast = iFree-1;
121492     *pnRoot = pTree->nData - nStart;
121493     *paRoot = &pTree->aData[nStart];
121494   }else{
121495     SegmentNode *pIter;
121496     sqlite3_int64 iNextFree = iFree;
121497     sqlite3_int64 iNextLeaf = iLeaf;
121498     for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
121499       int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
121500       int nWrite = pIter->nData - nStart;
121501   
121502       rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
121503       iNextFree++;
121504       iNextLeaf += (pIter->nEntry+1);
121505     }
121506     if( rc==SQLITE_OK ){
121507       assert( iNextLeaf==iFree );
121508       rc = fts3NodeWrite(
121509           p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
121510       );
121511     }
121512   }
121513
121514   return rc;
121515 }
121516
121517 /*
121518 ** Free all memory allocations associated with the tree pTree.
121519 */
121520 static void fts3NodeFree(SegmentNode *pTree){
121521   if( pTree ){
121522     SegmentNode *p = pTree->pLeftmost;
121523     fts3NodeFree(p->pParent);
121524     while( p ){
121525       SegmentNode *pRight = p->pRight;
121526       if( p->aData!=(char *)&p[1] ){
121527         sqlite3_free(p->aData);
121528       }
121529       assert( pRight==0 || p->zMalloc==0 );
121530       sqlite3_free(p->zMalloc);
121531       sqlite3_free(p);
121532       p = pRight;
121533     }
121534   }
121535 }
121536
121537 /*
121538 ** Add a term to the segment being constructed by the SegmentWriter object
121539 ** *ppWriter. When adding the first term to a segment, *ppWriter should
121540 ** be passed NULL. This function will allocate a new SegmentWriter object
121541 ** and return it via the input/output variable *ppWriter in this case.
121542 **
121543 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
121544 */
121545 static int fts3SegWriterAdd(
121546   Fts3Table *p,                   /* Virtual table handle */
121547   SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */ 
121548   int isCopyTerm,                 /* True if buffer zTerm must be copied */
121549   const char *zTerm,              /* Pointer to buffer containing term */
121550   int nTerm,                      /* Size of term in bytes */
121551   const char *aDoclist,           /* Pointer to buffer containing doclist */
121552   int nDoclist                    /* Size of doclist in bytes */
121553 ){
121554   int nPrefix;                    /* Size of term prefix in bytes */
121555   int nSuffix;                    /* Size of term suffix in bytes */
121556   int nReq;                       /* Number of bytes required on leaf page */
121557   int nData;
121558   SegmentWriter *pWriter = *ppWriter;
121559
121560   if( !pWriter ){
121561     int rc;
121562     sqlite3_stmt *pStmt;
121563
121564     /* Allocate the SegmentWriter structure */
121565     pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
121566     if( !pWriter ) return SQLITE_NOMEM;
121567     memset(pWriter, 0, sizeof(SegmentWriter));
121568     *ppWriter = pWriter;
121569
121570     /* Allocate a buffer in which to accumulate data */
121571     pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
121572     if( !pWriter->aData ) return SQLITE_NOMEM;
121573     pWriter->nSize = p->nNodeSize;
121574
121575     /* Find the next free blockid in the %_segments table */
121576     rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
121577     if( rc!=SQLITE_OK ) return rc;
121578     if( SQLITE_ROW==sqlite3_step(pStmt) ){
121579       pWriter->iFree = sqlite3_column_int64(pStmt, 0);
121580       pWriter->iFirst = pWriter->iFree;
121581     }
121582     rc = sqlite3_reset(pStmt);
121583     if( rc!=SQLITE_OK ) return rc;
121584   }
121585   nData = pWriter->nData;
121586
121587   nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
121588   nSuffix = nTerm-nPrefix;
121589
121590   /* Figure out how many bytes are required by this new entry */
121591   nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
121592     sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
121593     nSuffix +                               /* Term suffix */
121594     sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
121595     nDoclist;                               /* Doclist data */
121596
121597   if( nData>0 && nData+nReq>p->nNodeSize ){
121598     int rc;
121599
121600     /* The current leaf node is full. Write it out to the database. */
121601     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
121602     if( rc!=SQLITE_OK ) return rc;
121603
121604     /* Add the current term to the interior node tree. The term added to
121605     ** the interior tree must:
121606     **
121607     **   a) be greater than the largest term on the leaf node just written
121608     **      to the database (still available in pWriter->zTerm), and
121609     **
121610     **   b) be less than or equal to the term about to be added to the new
121611     **      leaf node (zTerm/nTerm).
121612     **
121613     ** In other words, it must be the prefix of zTerm 1 byte longer than
121614     ** the common prefix (if any) of zTerm and pWriter->zTerm.
121615     */
121616     assert( nPrefix<nTerm );
121617     rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
121618     if( rc!=SQLITE_OK ) return rc;
121619
121620     nData = 0;
121621     pWriter->nTerm = 0;
121622
121623     nPrefix = 0;
121624     nSuffix = nTerm;
121625     nReq = 1 +                              /* varint containing prefix size */
121626       sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
121627       nTerm +                               /* Term suffix */
121628       sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
121629       nDoclist;                             /* Doclist data */
121630   }
121631
121632   /* If the buffer currently allocated is too small for this entry, realloc
121633   ** the buffer to make it large enough.
121634   */
121635   if( nReq>pWriter->nSize ){
121636     char *aNew = sqlite3_realloc(pWriter->aData, nReq);
121637     if( !aNew ) return SQLITE_NOMEM;
121638     pWriter->aData = aNew;
121639     pWriter->nSize = nReq;
121640   }
121641   assert( nData+nReq<=pWriter->nSize );
121642
121643   /* Append the prefix-compressed term and doclist to the buffer. */
121644   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
121645   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
121646   memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
121647   nData += nSuffix;
121648   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
121649   memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
121650   pWriter->nData = nData + nDoclist;
121651
121652   /* Save the current term so that it can be used to prefix-compress the next.
121653   ** If the isCopyTerm parameter is true, then the buffer pointed to by
121654   ** zTerm is transient, so take a copy of the term data. Otherwise, just
121655   ** store a copy of the pointer.
121656   */
121657   if( isCopyTerm ){
121658     if( nTerm>pWriter->nMalloc ){
121659       char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
121660       if( !zNew ){
121661         return SQLITE_NOMEM;
121662       }
121663       pWriter->nMalloc = nTerm*2;
121664       pWriter->zMalloc = zNew;
121665       pWriter->zTerm = zNew;
121666     }
121667     assert( pWriter->zTerm==pWriter->zMalloc );
121668     memcpy(pWriter->zTerm, zTerm, nTerm);
121669   }else{
121670     pWriter->zTerm = (char *)zTerm;
121671   }
121672   pWriter->nTerm = nTerm;
121673
121674   return SQLITE_OK;
121675 }
121676
121677 /*
121678 ** Flush all data associated with the SegmentWriter object pWriter to the
121679 ** database. This function must be called after all terms have been added
121680 ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
121681 ** returned. Otherwise, an SQLite error code.
121682 */
121683 static int fts3SegWriterFlush(
121684   Fts3Table *p,                   /* Virtual table handle */
121685   SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
121686   int iLevel,                     /* Value for 'level' column of %_segdir */
121687   int iIdx                        /* Value for 'idx' column of %_segdir */
121688 ){
121689   int rc;                         /* Return code */
121690   if( pWriter->pTree ){
121691     sqlite3_int64 iLast = 0;      /* Largest block id written to database */
121692     sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
121693     char *zRoot = NULL;           /* Pointer to buffer containing root node */
121694     int nRoot = 0;                /* Size of buffer zRoot */
121695
121696     iLastLeaf = pWriter->iFree;
121697     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
121698     if( rc==SQLITE_OK ){
121699       rc = fts3NodeWrite(p, pWriter->pTree, 1,
121700           pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
121701     }
121702     if( rc==SQLITE_OK ){
121703       rc = fts3WriteSegdir(
121704           p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot);
121705     }
121706   }else{
121707     /* The entire tree fits on the root node. Write it to the segdir table. */
121708     rc = fts3WriteSegdir(
121709         p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData);
121710   }
121711   return rc;
121712 }
121713
121714 /*
121715 ** Release all memory held by the SegmentWriter object passed as the 
121716 ** first argument.
121717 */
121718 static void fts3SegWriterFree(SegmentWriter *pWriter){
121719   if( pWriter ){
121720     sqlite3_free(pWriter->aData);
121721     sqlite3_free(pWriter->zMalloc);
121722     fts3NodeFree(pWriter->pTree);
121723     sqlite3_free(pWriter);
121724   }
121725 }
121726
121727 /*
121728 ** The first value in the apVal[] array is assumed to contain an integer.
121729 ** This function tests if there exist any documents with docid values that
121730 ** are different from that integer. i.e. if deleting the document with docid
121731 ** pRowid would mean the FTS3 table were empty.
121732 **
121733 ** If successful, *pisEmpty is set to true if the table is empty except for
121734 ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
121735 ** error occurs, an SQLite error code is returned.
121736 */
121737 static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
121738   sqlite3_stmt *pStmt;
121739   int rc;
121740   rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
121741   if( rc==SQLITE_OK ){
121742     if( SQLITE_ROW==sqlite3_step(pStmt) ){
121743       *pisEmpty = sqlite3_column_int(pStmt, 0);
121744     }
121745     rc = sqlite3_reset(pStmt);
121746   }
121747   return rc;
121748 }
121749
121750 /*
121751 ** Set *pnMax to the largest segment level in the database for the index
121752 ** iIndex.
121753 **
121754 ** Segment levels are stored in the 'level' column of the %_segdir table.
121755 **
121756 ** Return SQLITE_OK if successful, or an SQLite error code if not.
121757 */
121758 static int fts3SegmentMaxLevel(Fts3Table *p, int iIndex, int *pnMax){
121759   sqlite3_stmt *pStmt;
121760   int rc;
121761   assert( iIndex>=0 && iIndex<p->nIndex );
121762
121763   /* Set pStmt to the compiled version of:
121764   **
121765   **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
121766   **
121767   ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
121768   */
121769   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
121770   if( rc!=SQLITE_OK ) return rc;
121771   sqlite3_bind_int(pStmt, 1, iIndex*FTS3_SEGDIR_MAXLEVEL);
121772   sqlite3_bind_int(pStmt, 2, (iIndex+1)*FTS3_SEGDIR_MAXLEVEL - 1);
121773   if( SQLITE_ROW==sqlite3_step(pStmt) ){
121774     *pnMax = sqlite3_column_int(pStmt, 0);
121775   }
121776   return sqlite3_reset(pStmt);
121777 }
121778
121779 /*
121780 ** This function is used after merging multiple segments into a single large
121781 ** segment to delete the old, now redundant, segment b-trees. Specifically,
121782 ** it:
121783 ** 
121784 **   1) Deletes all %_segments entries for the segments associated with 
121785 **      each of the SegReader objects in the array passed as the third 
121786 **      argument, and
121787 **
121788 **   2) deletes all %_segdir entries with level iLevel, or all %_segdir
121789 **      entries regardless of level if (iLevel<0).
121790 **
121791 ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
121792 */
121793 static int fts3DeleteSegdir(
121794   Fts3Table *p,                   /* Virtual table handle */
121795   int iIndex,                     /* Index for p->aIndex */
121796   int iLevel,                     /* Level of %_segdir entries to delete */
121797   Fts3SegReader **apSegment,      /* Array of SegReader objects */
121798   int nReader                     /* Size of array apSegment */
121799 ){
121800   int rc;                         /* Return Code */
121801   int i;                          /* Iterator variable */
121802   sqlite3_stmt *pDelete;          /* SQL statement to delete rows */
121803
121804   rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
121805   for(i=0; rc==SQLITE_OK && i<nReader; i++){
121806     Fts3SegReader *pSegment = apSegment[i];
121807     if( pSegment->iStartBlock ){
121808       sqlite3_bind_int64(pDelete, 1, pSegment->iStartBlock);
121809       sqlite3_bind_int64(pDelete, 2, pSegment->iEndBlock);
121810       sqlite3_step(pDelete);
121811       rc = sqlite3_reset(pDelete);
121812     }
121813   }
121814   if( rc!=SQLITE_OK ){
121815     return rc;
121816   }
121817
121818   assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
121819   if( iLevel==FTS3_SEGCURSOR_ALL ){
121820     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
121821     if( rc==SQLITE_OK ){
121822       sqlite3_bind_int(pDelete, 1, iIndex*FTS3_SEGDIR_MAXLEVEL);
121823       sqlite3_bind_int(pDelete, 2, (iIndex+1) * FTS3_SEGDIR_MAXLEVEL - 1);
121824     }
121825   }else{
121826     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
121827     if( rc==SQLITE_OK ){
121828       sqlite3_bind_int(pDelete, 1, iIndex*FTS3_SEGDIR_MAXLEVEL + iLevel);
121829     }
121830   }
121831
121832   if( rc==SQLITE_OK ){
121833     sqlite3_step(pDelete);
121834     rc = sqlite3_reset(pDelete);
121835   }
121836
121837   return rc;
121838 }
121839
121840 /*
121841 ** When this function is called, buffer *ppList (size *pnList bytes) contains 
121842 ** a position list that may (or may not) feature multiple columns. This
121843 ** function adjusts the pointer *ppList and the length *pnList so that they
121844 ** identify the subset of the position list that corresponds to column iCol.
121845 **
121846 ** If there are no entries in the input position list for column iCol, then
121847 ** *pnList is set to zero before returning.
121848 */
121849 static void fts3ColumnFilter(
121850   int iCol,                       /* Column to filter on */
121851   char **ppList,                  /* IN/OUT: Pointer to position list */
121852   int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
121853 ){
121854   char *pList = *ppList;
121855   int nList = *pnList;
121856   char *pEnd = &pList[nList];
121857   int iCurrent = 0;
121858   char *p = pList;
121859
121860   assert( iCol>=0 );
121861   while( 1 ){
121862     char c = 0;
121863     while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
121864   
121865     if( iCol==iCurrent ){
121866       nList = (int)(p - pList);
121867       break;
121868     }
121869
121870     nList -= (int)(p - pList);
121871     pList = p;
121872     if( nList==0 ){
121873       break;
121874     }
121875     p = &pList[1];
121876     p += sqlite3Fts3GetVarint32(p, &iCurrent);
121877   }
121878
121879   *ppList = pList;
121880   *pnList = nList;
121881 }
121882
121883 /*
121884 ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
121885 ** existing data). Grow the buffer if required.
121886 **
121887 ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
121888 ** trying to resize the buffer, return SQLITE_NOMEM.
121889 */
121890 static int fts3MsrBufferData(
121891   Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
121892   char *pList,
121893   int nList
121894 ){
121895   if( nList>pMsr->nBuffer ){
121896     char *pNew;
121897     pMsr->nBuffer = nList*2;
121898     pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
121899     if( !pNew ) return SQLITE_NOMEM;
121900     pMsr->aBuffer = pNew;
121901   }
121902
121903   memcpy(pMsr->aBuffer, pList, nList);
121904   return SQLITE_OK;
121905 }
121906
121907 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
121908   Fts3Table *p,                   /* Virtual table handle */
121909   Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
121910   sqlite3_int64 *piDocid,         /* OUT: Docid value */
121911   char **paPoslist,               /* OUT: Pointer to position list */
121912   int *pnPoslist                  /* OUT: Size of position list in bytes */
121913 ){
121914   int nMerge = pMsr->nAdvance;
121915   Fts3SegReader **apSegment = pMsr->apSegment;
121916   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
121917     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
121918   );
121919
121920   if( nMerge==0 ){
121921     *paPoslist = 0;
121922     return SQLITE_OK;
121923   }
121924
121925   while( 1 ){
121926     Fts3SegReader *pSeg;
121927     pSeg = pMsr->apSegment[0];
121928
121929     if( pSeg->pOffsetList==0 ){
121930       *paPoslist = 0;
121931       break;
121932     }else{
121933       int rc;
121934       char *pList;
121935       int nList;
121936       int j;
121937       sqlite3_int64 iDocid = apSegment[0]->iDocid;
121938
121939       rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
121940       j = 1;
121941       while( rc==SQLITE_OK 
121942         && j<nMerge
121943         && apSegment[j]->pOffsetList
121944         && apSegment[j]->iDocid==iDocid
121945       ){
121946         rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
121947         j++;
121948       }
121949       if( rc!=SQLITE_OK ) return rc;
121950       fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
121951
121952       if( pMsr->iColFilter>=0 ){
121953         fts3ColumnFilter(pMsr->iColFilter, &pList, &nList);
121954       }
121955
121956       if( nList>0 ){
121957         if( fts3SegReaderIsPending(apSegment[0]) ){
121958           rc = fts3MsrBufferData(pMsr, pList, nList+1);
121959           if( rc!=SQLITE_OK ) return rc;
121960           *paPoslist = pMsr->aBuffer;
121961           assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
121962         }else{
121963           *paPoslist = pList;
121964         }
121965         *piDocid = iDocid;
121966         *pnPoslist = nList;
121967         break;
121968       }
121969     }
121970   }
121971
121972   return SQLITE_OK;
121973 }
121974
121975 static int fts3SegReaderStart(
121976   Fts3Table *p,                   /* Virtual table handle */
121977   Fts3MultiSegReader *pCsr,       /* Cursor object */
121978   const char *zTerm,              /* Term searched for (or NULL) */
121979   int nTerm                       /* Length of zTerm in bytes */
121980 ){
121981   int i;
121982   int nSeg = pCsr->nSegment;
121983
121984   /* If the Fts3SegFilter defines a specific term (or term prefix) to search 
121985   ** for, then advance each segment iterator until it points to a term of
121986   ** equal or greater value than the specified term. This prevents many
121987   ** unnecessary merge/sort operations for the case where single segment
121988   ** b-tree leaf nodes contain more than one term.
121989   */
121990   for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
121991     Fts3SegReader *pSeg = pCsr->apSegment[i];
121992     do {
121993       int rc = fts3SegReaderNext(p, pSeg, 0);
121994       if( rc!=SQLITE_OK ) return rc;
121995     }while( zTerm && fts3SegReaderTermCmp(pSeg, zTerm, nTerm)<0 );
121996   }
121997   fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
121998
121999   return SQLITE_OK;
122000 }
122001
122002 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
122003   Fts3Table *p,                   /* Virtual table handle */
122004   Fts3MultiSegReader *pCsr,       /* Cursor object */
122005   Fts3SegFilter *pFilter          /* Restrictions on range of iteration */
122006 ){
122007   pCsr->pFilter = pFilter;
122008   return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
122009 }
122010
122011 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
122012   Fts3Table *p,                   /* Virtual table handle */
122013   Fts3MultiSegReader *pCsr,       /* Cursor object */
122014   int iCol,                       /* Column to match on. */
122015   const char *zTerm,              /* Term to iterate through a doclist for */
122016   int nTerm                       /* Number of bytes in zTerm */
122017 ){
122018   int i;
122019   int rc;
122020   int nSegment = pCsr->nSegment;
122021   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
122022     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
122023   );
122024
122025   assert( pCsr->pFilter==0 );
122026   assert( zTerm && nTerm>0 );
122027
122028   /* Advance each segment iterator until it points to the term zTerm/nTerm. */
122029   rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
122030   if( rc!=SQLITE_OK ) return rc;
122031
122032   /* Determine how many of the segments actually point to zTerm/nTerm. */
122033   for(i=0; i<nSegment; i++){
122034     Fts3SegReader *pSeg = pCsr->apSegment[i];
122035     if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
122036       break;
122037     }
122038   }
122039   pCsr->nAdvance = i;
122040
122041   /* Advance each of the segments to point to the first docid. */
122042   for(i=0; i<pCsr->nAdvance; i++){
122043     rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
122044     if( rc!=SQLITE_OK ) return rc;
122045   }
122046   fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
122047
122048   assert( iCol<0 || iCol<p->nColumn );
122049   pCsr->iColFilter = iCol;
122050
122051   return SQLITE_OK;
122052 }
122053
122054 /*
122055 ** This function is called on a MultiSegReader that has been started using
122056 ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
122057 ** have been made. Calling this function puts the MultiSegReader in such
122058 ** a state that if the next two calls are:
122059 **
122060 **   sqlite3Fts3SegReaderStart()
122061 **   sqlite3Fts3SegReaderStep()
122062 **
122063 ** then the entire doclist for the term is available in 
122064 ** MultiSegReader.aDoclist/nDoclist.
122065 */
122066 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
122067   int i;                          /* Used to iterate through segment-readers */
122068
122069   assert( pCsr->zTerm==0 );
122070   assert( pCsr->nTerm==0 );
122071   assert( pCsr->aDoclist==0 );
122072   assert( pCsr->nDoclist==0 );
122073
122074   pCsr->nAdvance = 0;
122075   pCsr->bRestart = 1;
122076   for(i=0; i<pCsr->nSegment; i++){
122077     pCsr->apSegment[i]->pOffsetList = 0;
122078     pCsr->apSegment[i]->nOffsetList = 0;
122079     pCsr->apSegment[i]->iDocid = 0;
122080   }
122081
122082   return SQLITE_OK;
122083 }
122084
122085
122086 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
122087   Fts3Table *p,                   /* Virtual table handle */
122088   Fts3MultiSegReader *pCsr        /* Cursor object */
122089 ){
122090   int rc = SQLITE_OK;
122091
122092   int isIgnoreEmpty =  (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
122093   int isRequirePos =   (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
122094   int isColFilter =    (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
122095   int isPrefix =       (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
122096   int isScan =         (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
122097
122098   Fts3SegReader **apSegment = pCsr->apSegment;
122099   int nSegment = pCsr->nSegment;
122100   Fts3SegFilter *pFilter = pCsr->pFilter;
122101   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
122102     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
122103   );
122104
122105   if( pCsr->nSegment==0 ) return SQLITE_OK;
122106
122107   do {
122108     int nMerge;
122109     int i;
122110   
122111     /* Advance the first pCsr->nAdvance entries in the apSegment[] array
122112     ** forward. Then sort the list in order of current term again.  
122113     */
122114     for(i=0; i<pCsr->nAdvance; i++){
122115       rc = fts3SegReaderNext(p, apSegment[i], 0);
122116       if( rc!=SQLITE_OK ) return rc;
122117     }
122118     fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
122119     pCsr->nAdvance = 0;
122120
122121     /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
122122     assert( rc==SQLITE_OK );
122123     if( apSegment[0]->aNode==0 ) break;
122124
122125     pCsr->nTerm = apSegment[0]->nTerm;
122126     pCsr->zTerm = apSegment[0]->zTerm;
122127
122128     /* If this is a prefix-search, and if the term that apSegment[0] points
122129     ** to does not share a suffix with pFilter->zTerm/nTerm, then all 
122130     ** required callbacks have been made. In this case exit early.
122131     **
122132     ** Similarly, if this is a search for an exact match, and the first term
122133     ** of segment apSegment[0] is not a match, exit early.
122134     */
122135     if( pFilter->zTerm && !isScan ){
122136       if( pCsr->nTerm<pFilter->nTerm 
122137        || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
122138        || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm) 
122139       ){
122140         break;
122141       }
122142     }
122143
122144     nMerge = 1;
122145     while( nMerge<nSegment 
122146         && apSegment[nMerge]->aNode
122147         && apSegment[nMerge]->nTerm==pCsr->nTerm 
122148         && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
122149     ){
122150       nMerge++;
122151     }
122152
122153     assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
122154     if( nMerge==1 
122155      && !isIgnoreEmpty 
122156      && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
122157     ){
122158       pCsr->nDoclist = apSegment[0]->nDoclist;
122159       if( fts3SegReaderIsPending(apSegment[0]) ){
122160         rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
122161         pCsr->aDoclist = pCsr->aBuffer;
122162       }else{
122163         pCsr->aDoclist = apSegment[0]->aDoclist;
122164       }
122165       if( rc==SQLITE_OK ) rc = SQLITE_ROW;
122166     }else{
122167       int nDoclist = 0;           /* Size of doclist */
122168       sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
122169
122170       /* The current term of the first nMerge entries in the array
122171       ** of Fts3SegReader objects is the same. The doclists must be merged
122172       ** and a single term returned with the merged doclist.
122173       */
122174       for(i=0; i<nMerge; i++){
122175         fts3SegReaderFirstDocid(p, apSegment[i]);
122176       }
122177       fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
122178       while( apSegment[0]->pOffsetList ){
122179         int j;                    /* Number of segments that share a docid */
122180         char *pList;
122181         int nList;
122182         int nByte;
122183         sqlite3_int64 iDocid = apSegment[0]->iDocid;
122184         fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
122185         j = 1;
122186         while( j<nMerge
122187             && apSegment[j]->pOffsetList
122188             && apSegment[j]->iDocid==iDocid
122189         ){
122190           fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
122191           j++;
122192         }
122193
122194         if( isColFilter ){
122195           fts3ColumnFilter(pFilter->iCol, &pList, &nList);
122196         }
122197
122198         if( !isIgnoreEmpty || nList>0 ){
122199
122200           /* Calculate the 'docid' delta value to write into the merged 
122201           ** doclist. */
122202           sqlite3_int64 iDelta;
122203           if( p->bDescIdx && nDoclist>0 ){
122204             iDelta = iPrev - iDocid;
122205           }else{
122206             iDelta = iDocid - iPrev;
122207           }
122208           assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
122209           assert( nDoclist>0 || iDelta==iDocid );
122210
122211           nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
122212           if( nDoclist+nByte>pCsr->nBuffer ){
122213             char *aNew;
122214             pCsr->nBuffer = (nDoclist+nByte)*2;
122215             aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
122216             if( !aNew ){
122217               return SQLITE_NOMEM;
122218             }
122219             pCsr->aBuffer = aNew;
122220           }
122221           nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
122222           iPrev = iDocid;
122223           if( isRequirePos ){
122224             memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
122225             nDoclist += nList;
122226             pCsr->aBuffer[nDoclist++] = '\0';
122227           }
122228         }
122229
122230         fts3SegReaderSort(apSegment, nMerge, j, xCmp);
122231       }
122232       if( nDoclist>0 ){
122233         pCsr->aDoclist = pCsr->aBuffer;
122234         pCsr->nDoclist = nDoclist;
122235         rc = SQLITE_ROW;
122236       }
122237     }
122238     pCsr->nAdvance = nMerge;
122239   }while( rc==SQLITE_OK );
122240
122241   return rc;
122242 }
122243
122244
122245 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
122246   Fts3MultiSegReader *pCsr       /* Cursor object */
122247 ){
122248   if( pCsr ){
122249     int i;
122250     for(i=0; i<pCsr->nSegment; i++){
122251       sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
122252     }
122253     sqlite3_free(pCsr->apSegment);
122254     sqlite3_free(pCsr->aBuffer);
122255
122256     pCsr->nSegment = 0;
122257     pCsr->apSegment = 0;
122258     pCsr->aBuffer = 0;
122259   }
122260 }
122261
122262 /*
122263 ** Merge all level iLevel segments in the database into a single 
122264 ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
122265 ** single segment with a level equal to the numerically largest level 
122266 ** currently present in the database.
122267 **
122268 ** If this function is called with iLevel<0, but there is only one
122269 ** segment in the database, SQLITE_DONE is returned immediately. 
122270 ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs, 
122271 ** an SQLite error code is returned.
122272 */
122273 static int fts3SegmentMerge(Fts3Table *p, int iIndex, int iLevel){
122274   int rc;                         /* Return code */
122275   int iIdx = 0;                   /* Index of new segment */
122276   int iNewLevel = 0;              /* Level/index to create new segment at */
122277   SegmentWriter *pWriter = 0;     /* Used to write the new, merged, segment */
122278   Fts3SegFilter filter;           /* Segment term filter condition */
122279   Fts3MultiSegReader csr;        /* Cursor to iterate through level(s) */
122280   int bIgnoreEmpty = 0;           /* True to ignore empty segments */
122281
122282   assert( iLevel==FTS3_SEGCURSOR_ALL
122283        || iLevel==FTS3_SEGCURSOR_PENDING
122284        || iLevel>=0
122285   );
122286   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
122287   assert( iIndex>=0 && iIndex<p->nIndex );
122288
122289   rc = sqlite3Fts3SegReaderCursor(p, iIndex, iLevel, 0, 0, 1, 0, &csr);
122290   if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
122291
122292   if( iLevel==FTS3_SEGCURSOR_ALL ){
122293     /* This call is to merge all segments in the database to a single
122294     ** segment. The level of the new segment is equal to the the numerically 
122295     ** greatest segment level currently present in the database for this
122296     ** index. The idx of the new segment is always 0.  */
122297     if( csr.nSegment==1 ){
122298       rc = SQLITE_DONE;
122299       goto finished;
122300     }
122301     rc = fts3SegmentMaxLevel(p, iIndex, &iNewLevel);
122302     bIgnoreEmpty = 1;
122303
122304   }else if( iLevel==FTS3_SEGCURSOR_PENDING ){
122305     iNewLevel = iIndex * FTS3_SEGDIR_MAXLEVEL; 
122306     rc = fts3AllocateSegdirIdx(p, iIndex, 0, &iIdx);
122307   }else{
122308     /* This call is to merge all segments at level iLevel. find the next
122309     ** available segment index at level iLevel+1. The call to
122310     ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to 
122311     ** a single iLevel+2 segment if necessary.  */
122312     rc = fts3AllocateSegdirIdx(p, iIndex, iLevel+1, &iIdx);
122313     iNewLevel = iIndex * FTS3_SEGDIR_MAXLEVEL + iLevel+1;
122314   }
122315   if( rc!=SQLITE_OK ) goto finished;
122316   assert( csr.nSegment>0 );
122317   assert( iNewLevel>=(iIndex*FTS3_SEGDIR_MAXLEVEL) );
122318   assert( iNewLevel<((iIndex+1)*FTS3_SEGDIR_MAXLEVEL) );
122319
122320   memset(&filter, 0, sizeof(Fts3SegFilter));
122321   filter.flags = FTS3_SEGMENT_REQUIRE_POS;
122322   filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
122323
122324   rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
122325   while( SQLITE_OK==rc ){
122326     rc = sqlite3Fts3SegReaderStep(p, &csr);
122327     if( rc!=SQLITE_ROW ) break;
122328     rc = fts3SegWriterAdd(p, &pWriter, 1, 
122329         csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
122330   }
122331   if( rc!=SQLITE_OK ) goto finished;
122332   assert( pWriter );
122333
122334   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
122335     rc = fts3DeleteSegdir(p, iIndex, iLevel, csr.apSegment, csr.nSegment);
122336     if( rc!=SQLITE_OK ) goto finished;
122337   }
122338   rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
122339
122340  finished:
122341   fts3SegWriterFree(pWriter);
122342   sqlite3Fts3SegReaderFinish(&csr);
122343   return rc;
122344 }
122345
122346
122347 /* 
122348 ** Flush the contents of pendingTerms to level 0 segments.
122349 */
122350 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
122351   int rc = SQLITE_OK;
122352   int i;
122353   for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
122354     rc = fts3SegmentMerge(p, i, FTS3_SEGCURSOR_PENDING);
122355     if( rc==SQLITE_DONE ) rc = SQLITE_OK;
122356   }
122357   sqlite3Fts3PendingTermsClear(p);
122358   return rc;
122359 }
122360
122361 /*
122362 ** Encode N integers as varints into a blob.
122363 */
122364 static void fts3EncodeIntArray(
122365   int N,             /* The number of integers to encode */
122366   u32 *a,            /* The integer values */
122367   char *zBuf,        /* Write the BLOB here */
122368   int *pNBuf         /* Write number of bytes if zBuf[] used here */
122369 ){
122370   int i, j;
122371   for(i=j=0; i<N; i++){
122372     j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
122373   }
122374   *pNBuf = j;
122375 }
122376
122377 /*
122378 ** Decode a blob of varints into N integers
122379 */
122380 static void fts3DecodeIntArray(
122381   int N,             /* The number of integers to decode */
122382   u32 *a,            /* Write the integer values */
122383   const char *zBuf,  /* The BLOB containing the varints */
122384   int nBuf           /* size of the BLOB */
122385 ){
122386   int i, j;
122387   UNUSED_PARAMETER(nBuf);
122388   for(i=j=0; i<N; i++){
122389     sqlite3_int64 x;
122390     j += sqlite3Fts3GetVarint(&zBuf[j], &x);
122391     assert(j<=nBuf);
122392     a[i] = (u32)(x & 0xffffffff);
122393   }
122394 }
122395
122396 /*
122397 ** Insert the sizes (in tokens) for each column of the document
122398 ** with docid equal to p->iPrevDocid.  The sizes are encoded as
122399 ** a blob of varints.
122400 */
122401 static void fts3InsertDocsize(
122402   int *pRC,         /* Result code */
122403   Fts3Table *p,     /* Table into which to insert */
122404   u32 *aSz          /* Sizes of each column */
122405 ){
122406   char *pBlob;             /* The BLOB encoding of the document size */
122407   int nBlob;               /* Number of bytes in the BLOB */
122408   sqlite3_stmt *pStmt;     /* Statement used to insert the encoding */
122409   int rc;                  /* Result code from subfunctions */
122410
122411   if( *pRC ) return;
122412   pBlob = sqlite3_malloc( 10*p->nColumn );
122413   if( pBlob==0 ){
122414     *pRC = SQLITE_NOMEM;
122415     return;
122416   }
122417   fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
122418   rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
122419   if( rc ){
122420     sqlite3_free(pBlob);
122421     *pRC = rc;
122422     return;
122423   }
122424   sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
122425   sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
122426   sqlite3_step(pStmt);
122427   *pRC = sqlite3_reset(pStmt);
122428 }
122429
122430 /*
122431 ** Record 0 of the %_stat table contains a blob consisting of N varints,
122432 ** where N is the number of user defined columns in the fts3 table plus
122433 ** two. If nCol is the number of user defined columns, then values of the 
122434 ** varints are set as follows:
122435 **
122436 **   Varint 0:       Total number of rows in the table.
122437 **
122438 **   Varint 1..nCol: For each column, the total number of tokens stored in
122439 **                   the column for all rows of the table.
122440 **
122441 **   Varint 1+nCol:  The total size, in bytes, of all text values in all
122442 **                   columns of all rows of the table.
122443 **
122444 */
122445 static void fts3UpdateDocTotals(
122446   int *pRC,                       /* The result code */
122447   Fts3Table *p,                   /* Table being updated */
122448   u32 *aSzIns,                    /* Size increases */
122449   u32 *aSzDel,                    /* Size decreases */
122450   int nChng                       /* Change in the number of documents */
122451 ){
122452   char *pBlob;             /* Storage for BLOB written into %_stat */
122453   int nBlob;               /* Size of BLOB written into %_stat */
122454   u32 *a;                  /* Array of integers that becomes the BLOB */
122455   sqlite3_stmt *pStmt;     /* Statement for reading and writing */
122456   int i;                   /* Loop counter */
122457   int rc;                  /* Result code from subfunctions */
122458
122459   const int nStat = p->nColumn+2;
122460
122461   if( *pRC ) return;
122462   a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
122463   if( a==0 ){
122464     *pRC = SQLITE_NOMEM;
122465     return;
122466   }
122467   pBlob = (char*)&a[nStat];
122468   rc = fts3SqlStmt(p, SQL_SELECT_DOCTOTAL, &pStmt, 0);
122469   if( rc ){
122470     sqlite3_free(a);
122471     *pRC = rc;
122472     return;
122473   }
122474   if( sqlite3_step(pStmt)==SQLITE_ROW ){
122475     fts3DecodeIntArray(nStat, a,
122476          sqlite3_column_blob(pStmt, 0),
122477          sqlite3_column_bytes(pStmt, 0));
122478   }else{
122479     memset(a, 0, sizeof(u32)*(nStat) );
122480   }
122481   sqlite3_reset(pStmt);
122482   if( nChng<0 && a[0]<(u32)(-nChng) ){
122483     a[0] = 0;
122484   }else{
122485     a[0] += nChng;
122486   }
122487   for(i=0; i<p->nColumn+1; i++){
122488     u32 x = a[i+1];
122489     if( x+aSzIns[i] < aSzDel[i] ){
122490       x = 0;
122491     }else{
122492       x = x + aSzIns[i] - aSzDel[i];
122493     }
122494     a[i+1] = x;
122495   }
122496   fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
122497   rc = fts3SqlStmt(p, SQL_REPLACE_DOCTOTAL, &pStmt, 0);
122498   if( rc ){
122499     sqlite3_free(a);
122500     *pRC = rc;
122501     return;
122502   }
122503   sqlite3_bind_blob(pStmt, 1, pBlob, nBlob, SQLITE_STATIC);
122504   sqlite3_step(pStmt);
122505   *pRC = sqlite3_reset(pStmt);
122506   sqlite3_free(a);
122507 }
122508
122509 static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
122510   int i;
122511   int bSeenDone = 0;
122512   int rc = SQLITE_OK;
122513   for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
122514     rc = fts3SegmentMerge(p, i, FTS3_SEGCURSOR_ALL);
122515     if( rc==SQLITE_DONE ){
122516       bSeenDone = 1;
122517       rc = SQLITE_OK;
122518     }
122519   }
122520   sqlite3Fts3SegmentsClose(p);
122521   sqlite3Fts3PendingTermsClear(p);
122522
122523   return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
122524 }
122525
122526 /*
122527 ** Handle a 'special' INSERT of the form:
122528 **
122529 **   "INSERT INTO tbl(tbl) VALUES(<expr>)"
122530 **
122531 ** Argument pVal contains the result of <expr>. Currently the only 
122532 ** meaningful value to insert is the text 'optimize'.
122533 */
122534 static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
122535   int rc;                         /* Return Code */
122536   const char *zVal = (const char *)sqlite3_value_text(pVal);
122537   int nVal = sqlite3_value_bytes(pVal);
122538
122539   if( !zVal ){
122540     return SQLITE_NOMEM;
122541   }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
122542     rc = fts3DoOptimize(p, 0);
122543 #ifdef SQLITE_TEST
122544   }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
122545     p->nNodeSize = atoi(&zVal[9]);
122546     rc = SQLITE_OK;
122547   }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
122548     p->nMaxPendingData = atoi(&zVal[11]);
122549     rc = SQLITE_OK;
122550 #endif
122551   }else{
122552     rc = SQLITE_ERROR;
122553   }
122554
122555   return rc;
122556 }
122557
122558 /*
122559 ** Delete all cached deferred doclists. Deferred doclists are cached
122560 ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
122561 */
122562 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
122563   Fts3DeferredToken *pDef;
122564   for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
122565     fts3PendingListDelete(pDef->pList);
122566     pDef->pList = 0;
122567   }
122568 }
122569
122570 /*
122571 ** Free all entries in the pCsr->pDeffered list. Entries are added to 
122572 ** this list using sqlite3Fts3DeferToken().
122573 */
122574 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
122575   Fts3DeferredToken *pDef;
122576   Fts3DeferredToken *pNext;
122577   for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
122578     pNext = pDef->pNext;
122579     fts3PendingListDelete(pDef->pList);
122580     sqlite3_free(pDef);
122581   }
122582   pCsr->pDeferred = 0;
122583 }
122584
122585 /*
122586 ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
122587 ** based on the row that pCsr currently points to.
122588 **
122589 ** A deferred-doclist is like any other doclist with position information
122590 ** included, except that it only contains entries for a single row of the
122591 ** table, not for all rows.
122592 */
122593 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
122594   int rc = SQLITE_OK;             /* Return code */
122595   if( pCsr->pDeferred ){
122596     int i;                        /* Used to iterate through table columns */
122597     sqlite3_int64 iDocid;         /* Docid of the row pCsr points to */
122598     Fts3DeferredToken *pDef;      /* Used to iterate through deferred tokens */
122599   
122600     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
122601     sqlite3_tokenizer *pT = p->pTokenizer;
122602     sqlite3_tokenizer_module const *pModule = pT->pModule;
122603    
122604     assert( pCsr->isRequireSeek==0 );
122605     iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
122606   
122607     for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
122608       const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
122609       sqlite3_tokenizer_cursor *pTC = 0;
122610   
122611       rc = pModule->xOpen(pT, zText, -1, &pTC);
122612       while( rc==SQLITE_OK ){
122613         char const *zToken;       /* Buffer containing token */
122614         int nToken;               /* Number of bytes in token */
122615         int iDum1, iDum2;         /* Dummy variables */
122616         int iPos;                 /* Position of token in zText */
122617   
122618         pTC->pTokenizer = pT;
122619         rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
122620         for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
122621           Fts3PhraseToken *pPT = pDef->pToken;
122622           if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
122623            && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
122624            && (0==memcmp(zToken, pPT->z, pPT->n))
122625           ){
122626             fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
122627           }
122628         }
122629       }
122630       if( pTC ) pModule->xClose(pTC);
122631       if( rc==SQLITE_DONE ) rc = SQLITE_OK;
122632     }
122633   
122634     for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
122635       if( pDef->pList ){
122636         rc = fts3PendingListAppendVarint(&pDef->pList, 0);
122637       }
122638     }
122639   }
122640
122641   return rc;
122642 }
122643
122644 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
122645   Fts3DeferredToken *p, 
122646   char **ppData, 
122647   int *pnData
122648 ){
122649   char *pRet;
122650   int nSkip;
122651   sqlite3_int64 dummy;
122652
122653   *ppData = 0;
122654   *pnData = 0;
122655
122656   if( p->pList==0 ){
122657     return SQLITE_OK;
122658   }
122659
122660   pRet = (char *)sqlite3_malloc(p->pList->nData);
122661   if( !pRet ) return SQLITE_NOMEM;
122662
122663   nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
122664   *pnData = p->pList->nData - nSkip;
122665   *ppData = pRet;
122666   
122667   memcpy(pRet, &p->pList->aData[nSkip], *pnData);
122668   return SQLITE_OK;
122669 }
122670
122671 /*
122672 ** Add an entry for token pToken to the pCsr->pDeferred list.
122673 */
122674 SQLITE_PRIVATE int sqlite3Fts3DeferToken(
122675   Fts3Cursor *pCsr,               /* Fts3 table cursor */
122676   Fts3PhraseToken *pToken,        /* Token to defer */
122677   int iCol                        /* Column that token must appear in (or -1) */
122678 ){
122679   Fts3DeferredToken *pDeferred;
122680   pDeferred = sqlite3_malloc(sizeof(*pDeferred));
122681   if( !pDeferred ){
122682     return SQLITE_NOMEM;
122683   }
122684   memset(pDeferred, 0, sizeof(*pDeferred));
122685   pDeferred->pToken = pToken;
122686   pDeferred->pNext = pCsr->pDeferred; 
122687   pDeferred->iCol = iCol;
122688   pCsr->pDeferred = pDeferred;
122689
122690   assert( pToken->pDeferred==0 );
122691   pToken->pDeferred = pDeferred;
122692
122693   return SQLITE_OK;
122694 }
122695
122696 /*
122697 ** SQLite value pRowid contains the rowid of a row that may or may not be
122698 ** present in the FTS3 table. If it is, delete it and adjust the contents
122699 ** of subsiduary data structures accordingly.
122700 */
122701 static int fts3DeleteByRowid(
122702   Fts3Table *p, 
122703   sqlite3_value *pRowid, 
122704   int *pnDoc,
122705   u32 *aSzDel
122706 ){
122707   int isEmpty = 0;
122708   int rc = fts3IsEmpty(p, pRowid, &isEmpty);
122709   if( rc==SQLITE_OK ){
122710     if( isEmpty ){
122711       /* Deleting this row means the whole table is empty. In this case
122712       ** delete the contents of all three tables and throw away any
122713       ** data in the pendingTerms hash table.  */
122714       rc = fts3DeleteAll(p);
122715       *pnDoc = *pnDoc - 1;
122716     }else{
122717       sqlite3_int64 iRemove = sqlite3_value_int64(pRowid);
122718       rc = fts3PendingTermsDocid(p, iRemove);
122719       fts3DeleteTerms(&rc, p, pRowid, aSzDel);
122720       fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
122721       if( sqlite3_changes(p->db) ) *pnDoc = *pnDoc - 1;
122722       if( p->bHasDocsize ){
122723         fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
122724       }
122725     }
122726   }
122727
122728   return rc;
122729 }
122730
122731 /*
122732 ** This function does the work for the xUpdate method of FTS3 virtual
122733 ** tables.
122734 */
122735 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
122736   sqlite3_vtab *pVtab,            /* FTS3 vtab object */
122737   int nArg,                       /* Size of argument array */
122738   sqlite3_value **apVal,          /* Array of arguments */
122739   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
122740 ){
122741   Fts3Table *p = (Fts3Table *)pVtab;
122742   int rc = SQLITE_OK;             /* Return Code */
122743   int isRemove = 0;               /* True for an UPDATE or DELETE */
122744   sqlite3_int64 iRemove = 0;      /* Rowid removed by UPDATE or DELETE */
122745   u32 *aSzIns = 0;                /* Sizes of inserted documents */
122746   u32 *aSzDel;                    /* Sizes of deleted documents */
122747   int nChng = 0;                  /* Net change in number of documents */
122748   int bInsertDone = 0;
122749
122750   assert( p->pSegments==0 );
122751
122752   /* Check for a "special" INSERT operation. One of the form:
122753   **
122754   **   INSERT INTO xyz(xyz) VALUES('command');
122755   */
122756   if( nArg>1 
122757    && sqlite3_value_type(apVal[0])==SQLITE_NULL 
122758    && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL 
122759   ){
122760     rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
122761     goto update_out;
122762   }
122763
122764   /* Allocate space to hold the change in document sizes */
122765   aSzIns = sqlite3_malloc( sizeof(aSzIns[0])*(p->nColumn+1)*2 );
122766   if( aSzIns==0 ){
122767     rc = SQLITE_NOMEM;
122768     goto update_out;
122769   }
122770   aSzDel = &aSzIns[p->nColumn+1];
122771   memset(aSzIns, 0, sizeof(aSzIns[0])*(p->nColumn+1)*2);
122772
122773   /* If this is an INSERT operation, or an UPDATE that modifies the rowid
122774   ** value, then this operation requires constraint handling.
122775   **
122776   ** If the on-conflict mode is REPLACE, this means that the existing row
122777   ** should be deleted from the database before inserting the new row. Or,
122778   ** if the on-conflict mode is other than REPLACE, then this method must
122779   ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
122780   ** modify the database file.
122781   */
122782   if( nArg>1 ){
122783     /* Find the value object that holds the new rowid value. */
122784     sqlite3_value *pNewRowid = apVal[3+p->nColumn];
122785     if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
122786       pNewRowid = apVal[1];
122787     }
122788
122789     if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && ( 
122790         sqlite3_value_type(apVal[0])==SQLITE_NULL
122791      || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
122792     )){
122793       /* The new rowid is not NULL (in this case the rowid will be
122794       ** automatically assigned and there is no chance of a conflict), and 
122795       ** the statement is either an INSERT or an UPDATE that modifies the
122796       ** rowid column. So if the conflict mode is REPLACE, then delete any
122797       ** existing row with rowid=pNewRowid. 
122798       **
122799       ** Or, if the conflict mode is not REPLACE, insert the new record into 
122800       ** the %_content table. If we hit the duplicate rowid constraint (or any
122801       ** other error) while doing so, return immediately.
122802       **
122803       ** This branch may also run if pNewRowid contains a value that cannot
122804       ** be losslessly converted to an integer. In this case, the eventual 
122805       ** call to fts3InsertData() (either just below or further on in this
122806       ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is 
122807       ** invoked, it will delete zero rows (since no row will have
122808       ** docid=$pNewRowid if $pNewRowid is not an integer value).
122809       */
122810       if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
122811         rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
122812       }else{
122813         rc = fts3InsertData(p, apVal, pRowid);
122814         bInsertDone = 1;
122815       }
122816     }
122817   }
122818   if( rc!=SQLITE_OK ){
122819     goto update_out;
122820   }
122821
122822   /* If this is a DELETE or UPDATE operation, remove the old record. */
122823   if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
122824     assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
122825     rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
122826     isRemove = 1;
122827     iRemove = sqlite3_value_int64(apVal[0]);
122828   }
122829   
122830   /* If this is an INSERT or UPDATE operation, insert the new record. */
122831   if( nArg>1 && rc==SQLITE_OK ){
122832     if( bInsertDone==0 ){
122833       rc = fts3InsertData(p, apVal, pRowid);
122834       if( rc==SQLITE_CONSTRAINT ) rc = SQLITE_CORRUPT_VTAB;
122835     }
122836     if( rc==SQLITE_OK && (!isRemove || *pRowid!=iRemove) ){
122837       rc = fts3PendingTermsDocid(p, *pRowid);
122838     }
122839     if( rc==SQLITE_OK ){
122840       rc = fts3InsertTerms(p, apVal, aSzIns);
122841     }
122842     if( p->bHasDocsize ){
122843       fts3InsertDocsize(&rc, p, aSzIns);
122844     }
122845     nChng++;
122846   }
122847
122848   if( p->bHasStat ){
122849     fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
122850   }
122851
122852  update_out:
122853   sqlite3_free(aSzIns);
122854   sqlite3Fts3SegmentsClose(p);
122855   return rc;
122856 }
122857
122858 /* 
122859 ** Flush any data in the pending-terms hash table to disk. If successful,
122860 ** merge all segments in the database (including the new segment, if 
122861 ** there was any data to flush) into a single segment. 
122862 */
122863 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
122864   int rc;
122865   rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
122866   if( rc==SQLITE_OK ){
122867     rc = fts3DoOptimize(p, 1);
122868     if( rc==SQLITE_OK || rc==SQLITE_DONE ){
122869       int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
122870       if( rc2!=SQLITE_OK ) rc = rc2;
122871     }else{
122872       sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
122873       sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
122874     }
122875   }
122876   sqlite3Fts3SegmentsClose(p);
122877   return rc;
122878 }
122879
122880 #endif
122881
122882 /************** End of fts3_write.c ******************************************/
122883 /************** Begin file fts3_snippet.c ************************************/
122884 /*
122885 ** 2009 Oct 23
122886 **
122887 ** The author disclaims copyright to this source code.  In place of
122888 ** a legal notice, here is a blessing:
122889 **
122890 **    May you do good and not evil.
122891 **    May you find forgiveness for yourself and forgive others.
122892 **    May you share freely, never taking more than you give.
122893 **
122894 ******************************************************************************
122895 */
122896
122897 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
122898
122899
122900 /*
122901 ** Characters that may appear in the second argument to matchinfo().
122902 */
122903 #define FTS3_MATCHINFO_NPHRASE   'p'        /* 1 value */
122904 #define FTS3_MATCHINFO_NCOL      'c'        /* 1 value */
122905 #define FTS3_MATCHINFO_NDOC      'n'        /* 1 value */
122906 #define FTS3_MATCHINFO_AVGLENGTH 'a'        /* nCol values */
122907 #define FTS3_MATCHINFO_LENGTH    'l'        /* nCol values */
122908 #define FTS3_MATCHINFO_LCS       's'        /* nCol values */
122909 #define FTS3_MATCHINFO_HITS      'x'        /* 3*nCol*nPhrase values */
122910
122911 /*
122912 ** The default value for the second argument to matchinfo(). 
122913 */
122914 #define FTS3_MATCHINFO_DEFAULT   "pcx"
122915
122916
122917 /*
122918 ** Used as an fts3ExprIterate() context when loading phrase doclists to
122919 ** Fts3Expr.aDoclist[]/nDoclist.
122920 */
122921 typedef struct LoadDoclistCtx LoadDoclistCtx;
122922 struct LoadDoclistCtx {
122923   Fts3Cursor *pCsr;               /* FTS3 Cursor */
122924   int nPhrase;                    /* Number of phrases seen so far */
122925   int nToken;                     /* Number of tokens seen so far */
122926 };
122927
122928 /*
122929 ** The following types are used as part of the implementation of the 
122930 ** fts3BestSnippet() routine.
122931 */
122932 typedef struct SnippetIter SnippetIter;
122933 typedef struct SnippetPhrase SnippetPhrase;
122934 typedef struct SnippetFragment SnippetFragment;
122935
122936 struct SnippetIter {
122937   Fts3Cursor *pCsr;               /* Cursor snippet is being generated from */
122938   int iCol;                       /* Extract snippet from this column */
122939   int nSnippet;                   /* Requested snippet length (in tokens) */
122940   int nPhrase;                    /* Number of phrases in query */
122941   SnippetPhrase *aPhrase;         /* Array of size nPhrase */
122942   int iCurrent;                   /* First token of current snippet */
122943 };
122944
122945 struct SnippetPhrase {
122946   int nToken;                     /* Number of tokens in phrase */
122947   char *pList;                    /* Pointer to start of phrase position list */
122948   int iHead;                      /* Next value in position list */
122949   char *pHead;                    /* Position list data following iHead */
122950   int iTail;                      /* Next value in trailing position list */
122951   char *pTail;                    /* Position list data following iTail */
122952 };
122953
122954 struct SnippetFragment {
122955   int iCol;                       /* Column snippet is extracted from */
122956   int iPos;                       /* Index of first token in snippet */
122957   u64 covered;                    /* Mask of query phrases covered */
122958   u64 hlmask;                     /* Mask of snippet terms to highlight */
122959 };
122960
122961 /*
122962 ** This type is used as an fts3ExprIterate() context object while 
122963 ** accumulating the data returned by the matchinfo() function.
122964 */
122965 typedef struct MatchInfo MatchInfo;
122966 struct MatchInfo {
122967   Fts3Cursor *pCursor;            /* FTS3 Cursor */
122968   int nCol;                       /* Number of columns in table */
122969   int nPhrase;                    /* Number of matchable phrases in query */
122970   sqlite3_int64 nDoc;             /* Number of docs in database */
122971   u32 *aMatchinfo;                /* Pre-allocated buffer */
122972 };
122973
122974
122975
122976 /*
122977 ** The snippet() and offsets() functions both return text values. An instance
122978 ** of the following structure is used to accumulate those values while the
122979 ** functions are running. See fts3StringAppend() for details.
122980 */
122981 typedef struct StrBuffer StrBuffer;
122982 struct StrBuffer {
122983   char *z;                        /* Pointer to buffer containing string */
122984   int n;                          /* Length of z in bytes (excl. nul-term) */
122985   int nAlloc;                     /* Allocated size of buffer z in bytes */
122986 };
122987
122988
122989 /*
122990 ** This function is used to help iterate through a position-list. A position
122991 ** list is a list of unique integers, sorted from smallest to largest. Each
122992 ** element of the list is represented by an FTS3 varint that takes the value
122993 ** of the difference between the current element and the previous one plus
122994 ** two. For example, to store the position-list:
122995 **
122996 **     4 9 113
122997 **
122998 ** the three varints:
122999 **
123000 **     6 7 106
123001 **
123002 ** are encoded.
123003 **
123004 ** When this function is called, *pp points to the start of an element of
123005 ** the list. *piPos contains the value of the previous entry in the list.
123006 ** After it returns, *piPos contains the value of the next element of the
123007 ** list and *pp is advanced to the following varint.
123008 */
123009 static void fts3GetDeltaPosition(char **pp, int *piPos){
123010   int iVal;
123011   *pp += sqlite3Fts3GetVarint32(*pp, &iVal);
123012   *piPos += (iVal-2);
123013 }
123014
123015 /*
123016 ** Helper function for fts3ExprIterate() (see below).
123017 */
123018 static int fts3ExprIterate2(
123019   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
123020   int *piPhrase,                  /* Pointer to phrase counter */
123021   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
123022   void *pCtx                      /* Second argument to pass to callback */
123023 ){
123024   int rc;                         /* Return code */
123025   int eType = pExpr->eType;       /* Type of expression node pExpr */
123026
123027   if( eType!=FTSQUERY_PHRASE ){
123028     assert( pExpr->pLeft && pExpr->pRight );
123029     rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
123030     if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
123031       rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
123032     }
123033   }else{
123034     rc = x(pExpr, *piPhrase, pCtx);
123035     (*piPhrase)++;
123036   }
123037   return rc;
123038 }
123039
123040 /*
123041 ** Iterate through all phrase nodes in an FTS3 query, except those that
123042 ** are part of a sub-tree that is the right-hand-side of a NOT operator.
123043 ** For each phrase node found, the supplied callback function is invoked.
123044 **
123045 ** If the callback function returns anything other than SQLITE_OK, 
123046 ** the iteration is abandoned and the error code returned immediately.
123047 ** Otherwise, SQLITE_OK is returned after a callback has been made for
123048 ** all eligible phrase nodes.
123049 */
123050 static int fts3ExprIterate(
123051   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
123052   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
123053   void *pCtx                      /* Second argument to pass to callback */
123054 ){
123055   int iPhrase = 0;                /* Variable used as the phrase counter */
123056   return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
123057 }
123058
123059 /*
123060 ** This is an fts3ExprIterate() callback used while loading the doclists
123061 ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
123062 ** fts3ExprLoadDoclists().
123063 */
123064 static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
123065   int rc = SQLITE_OK;
123066   Fts3Phrase *pPhrase = pExpr->pPhrase;
123067   LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
123068
123069   UNUSED_PARAMETER(iPhrase);
123070
123071   p->nPhrase++;
123072   p->nToken += pPhrase->nToken;
123073
123074   return rc;
123075 }
123076
123077 /*
123078 ** Load the doclists for each phrase in the query associated with FTS3 cursor
123079 ** pCsr. 
123080 **
123081 ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable 
123082 ** phrases in the expression (all phrases except those directly or 
123083 ** indirectly descended from the right-hand-side of a NOT operator). If 
123084 ** pnToken is not NULL, then it is set to the number of tokens in all
123085 ** matchable phrases of the expression.
123086 */
123087 static int fts3ExprLoadDoclists(
123088   Fts3Cursor *pCsr,               /* Fts3 cursor for current query */
123089   int *pnPhrase,                  /* OUT: Number of phrases in query */
123090   int *pnToken                    /* OUT: Number of tokens in query */
123091 ){
123092   int rc;                         /* Return Code */
123093   LoadDoclistCtx sCtx = {0,0,0};  /* Context for fts3ExprIterate() */
123094   sCtx.pCsr = pCsr;
123095   rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
123096   if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
123097   if( pnToken ) *pnToken = sCtx.nToken;
123098   return rc;
123099 }
123100
123101 static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
123102   (*(int *)ctx)++;
123103   UNUSED_PARAMETER(pExpr);
123104   UNUSED_PARAMETER(iPhrase);
123105   return SQLITE_OK;
123106 }
123107 static int fts3ExprPhraseCount(Fts3Expr *pExpr){
123108   int nPhrase = 0;
123109   (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
123110   return nPhrase;
123111 }
123112
123113 /*
123114 ** Advance the position list iterator specified by the first two 
123115 ** arguments so that it points to the first element with a value greater
123116 ** than or equal to parameter iNext.
123117 */
123118 static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
123119   char *pIter = *ppIter;
123120   if( pIter ){
123121     int iIter = *piIter;
123122
123123     while( iIter<iNext ){
123124       if( 0==(*pIter & 0xFE) ){
123125         iIter = -1;
123126         pIter = 0;
123127         break;
123128       }
123129       fts3GetDeltaPosition(&pIter, &iIter);
123130     }
123131
123132     *piIter = iIter;
123133     *ppIter = pIter;
123134   }
123135 }
123136
123137 /*
123138 ** Advance the snippet iterator to the next candidate snippet.
123139 */
123140 static int fts3SnippetNextCandidate(SnippetIter *pIter){
123141   int i;                          /* Loop counter */
123142
123143   if( pIter->iCurrent<0 ){
123144     /* The SnippetIter object has just been initialized. The first snippet
123145     ** candidate always starts at offset 0 (even if this candidate has a
123146     ** score of 0.0).
123147     */
123148     pIter->iCurrent = 0;
123149
123150     /* Advance the 'head' iterator of each phrase to the first offset that
123151     ** is greater than or equal to (iNext+nSnippet).
123152     */
123153     for(i=0; i<pIter->nPhrase; i++){
123154       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
123155       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
123156     }
123157   }else{
123158     int iStart;
123159     int iEnd = 0x7FFFFFFF;
123160
123161     for(i=0; i<pIter->nPhrase; i++){
123162       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
123163       if( pPhrase->pHead && pPhrase->iHead<iEnd ){
123164         iEnd = pPhrase->iHead;
123165       }
123166     }
123167     if( iEnd==0x7FFFFFFF ){
123168       return 1;
123169     }
123170
123171     pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
123172     for(i=0; i<pIter->nPhrase; i++){
123173       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
123174       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
123175       fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
123176     }
123177   }
123178
123179   return 0;
123180 }
123181
123182 /*
123183 ** Retrieve information about the current candidate snippet of snippet 
123184 ** iterator pIter.
123185 */
123186 static void fts3SnippetDetails(
123187   SnippetIter *pIter,             /* Snippet iterator */
123188   u64 mCovered,                   /* Bitmask of phrases already covered */
123189   int *piToken,                   /* OUT: First token of proposed snippet */
123190   int *piScore,                   /* OUT: "Score" for this snippet */
123191   u64 *pmCover,                   /* OUT: Bitmask of phrases covered */
123192   u64 *pmHighlight                /* OUT: Bitmask of terms to highlight */
123193 ){
123194   int iStart = pIter->iCurrent;   /* First token of snippet */
123195   int iScore = 0;                 /* Score of this snippet */
123196   int i;                          /* Loop counter */
123197   u64 mCover = 0;                 /* Mask of phrases covered by this snippet */
123198   u64 mHighlight = 0;             /* Mask of tokens to highlight in snippet */
123199
123200   for(i=0; i<pIter->nPhrase; i++){
123201     SnippetPhrase *pPhrase = &pIter->aPhrase[i];
123202     if( pPhrase->pTail ){
123203       char *pCsr = pPhrase->pTail;
123204       int iCsr = pPhrase->iTail;
123205
123206       while( iCsr<(iStart+pIter->nSnippet) ){
123207         int j;
123208         u64 mPhrase = (u64)1 << i;
123209         u64 mPos = (u64)1 << (iCsr - iStart);
123210         assert( iCsr>=iStart );
123211         if( (mCover|mCovered)&mPhrase ){
123212           iScore++;
123213         }else{
123214           iScore += 1000;
123215         }
123216         mCover |= mPhrase;
123217
123218         for(j=0; j<pPhrase->nToken; j++){
123219           mHighlight |= (mPos>>j);
123220         }
123221
123222         if( 0==(*pCsr & 0x0FE) ) break;
123223         fts3GetDeltaPosition(&pCsr, &iCsr);
123224       }
123225     }
123226   }
123227
123228   /* Set the output variables before returning. */
123229   *piToken = iStart;
123230   *piScore = iScore;
123231   *pmCover = mCover;
123232   *pmHighlight = mHighlight;
123233 }
123234
123235 /*
123236 ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
123237 ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
123238 */
123239 static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
123240   SnippetIter *p = (SnippetIter *)ctx;
123241   SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
123242   char *pCsr;
123243
123244   pPhrase->nToken = pExpr->pPhrase->nToken;
123245
123246   pCsr = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol);
123247   if( pCsr ){
123248     int iFirst = 0;
123249     pPhrase->pList = pCsr;
123250     fts3GetDeltaPosition(&pCsr, &iFirst);
123251     pPhrase->pHead = pCsr;
123252     pPhrase->pTail = pCsr;
123253     pPhrase->iHead = iFirst;
123254     pPhrase->iTail = iFirst;
123255   }else{
123256     assert( pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0 );
123257   }
123258
123259   return SQLITE_OK;
123260 }
123261
123262 /*
123263 ** Select the fragment of text consisting of nFragment contiguous tokens 
123264 ** from column iCol that represent the "best" snippet. The best snippet
123265 ** is the snippet with the highest score, where scores are calculated
123266 ** by adding:
123267 **
123268 **   (a) +1 point for each occurence of a matchable phrase in the snippet.
123269 **
123270 **   (b) +1000 points for the first occurence of each matchable phrase in 
123271 **       the snippet for which the corresponding mCovered bit is not set.
123272 **
123273 ** The selected snippet parameters are stored in structure *pFragment before
123274 ** returning. The score of the selected snippet is stored in *piScore
123275 ** before returning.
123276 */
123277 static int fts3BestSnippet(
123278   int nSnippet,                   /* Desired snippet length */
123279   Fts3Cursor *pCsr,               /* Cursor to create snippet for */
123280   int iCol,                       /* Index of column to create snippet from */
123281   u64 mCovered,                   /* Mask of phrases already covered */
123282   u64 *pmSeen,                    /* IN/OUT: Mask of phrases seen */
123283   SnippetFragment *pFragment,     /* OUT: Best snippet found */
123284   int *piScore                    /* OUT: Score of snippet pFragment */
123285 ){
123286   int rc;                         /* Return Code */
123287   int nList;                      /* Number of phrases in expression */
123288   SnippetIter sIter;              /* Iterates through snippet candidates */
123289   int nByte;                      /* Number of bytes of space to allocate */
123290   int iBestScore = -1;            /* Best snippet score found so far */
123291   int i;                          /* Loop counter */
123292
123293   memset(&sIter, 0, sizeof(sIter));
123294
123295   /* Iterate through the phrases in the expression to count them. The same
123296   ** callback makes sure the doclists are loaded for each phrase.
123297   */
123298   rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
123299   if( rc!=SQLITE_OK ){
123300     return rc;
123301   }
123302
123303   /* Now that it is known how many phrases there are, allocate and zero
123304   ** the required space using malloc().
123305   */
123306   nByte = sizeof(SnippetPhrase) * nList;
123307   sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
123308   if( !sIter.aPhrase ){
123309     return SQLITE_NOMEM;
123310   }
123311   memset(sIter.aPhrase, 0, nByte);
123312
123313   /* Initialize the contents of the SnippetIter object. Then iterate through
123314   ** the set of phrases in the expression to populate the aPhrase[] array.
123315   */
123316   sIter.pCsr = pCsr;
123317   sIter.iCol = iCol;
123318   sIter.nSnippet = nSnippet;
123319   sIter.nPhrase = nList;
123320   sIter.iCurrent = -1;
123321   (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
123322
123323   /* Set the *pmSeen output variable. */
123324   for(i=0; i<nList; i++){
123325     if( sIter.aPhrase[i].pHead ){
123326       *pmSeen |= (u64)1 << i;
123327     }
123328   }
123329
123330   /* Loop through all candidate snippets. Store the best snippet in 
123331   ** *pFragment. Store its associated 'score' in iBestScore.
123332   */
123333   pFragment->iCol = iCol;
123334   while( !fts3SnippetNextCandidate(&sIter) ){
123335     int iPos;
123336     int iScore;
123337     u64 mCover;
123338     u64 mHighlight;
123339     fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);
123340     assert( iScore>=0 );
123341     if( iScore>iBestScore ){
123342       pFragment->iPos = iPos;
123343       pFragment->hlmask = mHighlight;
123344       pFragment->covered = mCover;
123345       iBestScore = iScore;
123346     }
123347   }
123348
123349   sqlite3_free(sIter.aPhrase);
123350   *piScore = iBestScore;
123351   return SQLITE_OK;
123352 }
123353
123354
123355 /*
123356 ** Append a string to the string-buffer passed as the first argument.
123357 **
123358 ** If nAppend is negative, then the length of the string zAppend is
123359 ** determined using strlen().
123360 */
123361 static int fts3StringAppend(
123362   StrBuffer *pStr,                /* Buffer to append to */
123363   const char *zAppend,            /* Pointer to data to append to buffer */
123364   int nAppend                     /* Size of zAppend in bytes (or -1) */
123365 ){
123366   if( nAppend<0 ){
123367     nAppend = (int)strlen(zAppend);
123368   }
123369
123370   /* If there is insufficient space allocated at StrBuffer.z, use realloc()
123371   ** to grow the buffer until so that it is big enough to accomadate the
123372   ** appended data.
123373   */
123374   if( pStr->n+nAppend+1>=pStr->nAlloc ){
123375     int nAlloc = pStr->nAlloc+nAppend+100;
123376     char *zNew = sqlite3_realloc(pStr->z, nAlloc);
123377     if( !zNew ){
123378       return SQLITE_NOMEM;
123379     }
123380     pStr->z = zNew;
123381     pStr->nAlloc = nAlloc;
123382   }
123383
123384   /* Append the data to the string buffer. */
123385   memcpy(&pStr->z[pStr->n], zAppend, nAppend);
123386   pStr->n += nAppend;
123387   pStr->z[pStr->n] = '\0';
123388
123389   return SQLITE_OK;
123390 }
123391
123392 /*
123393 ** The fts3BestSnippet() function often selects snippets that end with a
123394 ** query term. That is, the final term of the snippet is always a term
123395 ** that requires highlighting. For example, if 'X' is a highlighted term
123396 ** and '.' is a non-highlighted term, BestSnippet() may select:
123397 **
123398 **     ........X.....X
123399 **
123400 ** This function "shifts" the beginning of the snippet forward in the 
123401 ** document so that there are approximately the same number of 
123402 ** non-highlighted terms to the right of the final highlighted term as there
123403 ** are to the left of the first highlighted term. For example, to this:
123404 **
123405 **     ....X.....X....
123406 **
123407 ** This is done as part of extracting the snippet text, not when selecting
123408 ** the snippet. Snippet selection is done based on doclists only, so there
123409 ** is no way for fts3BestSnippet() to know whether or not the document 
123410 ** actually contains terms that follow the final highlighted term. 
123411 */
123412 static int fts3SnippetShift(
123413   Fts3Table *pTab,                /* FTS3 table snippet comes from */
123414   int nSnippet,                   /* Number of tokens desired for snippet */
123415   const char *zDoc,               /* Document text to extract snippet from */
123416   int nDoc,                       /* Size of buffer zDoc in bytes */
123417   int *piPos,                     /* IN/OUT: First token of snippet */
123418   u64 *pHlmask                    /* IN/OUT: Mask of tokens to highlight */
123419 ){
123420   u64 hlmask = *pHlmask;          /* Local copy of initial highlight-mask */
123421
123422   if( hlmask ){
123423     int nLeft;                    /* Tokens to the left of first highlight */
123424     int nRight;                   /* Tokens to the right of last highlight */
123425     int nDesired;                 /* Ideal number of tokens to shift forward */
123426
123427     for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
123428     for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
123429     nDesired = (nLeft-nRight)/2;
123430
123431     /* Ideally, the start of the snippet should be pushed forward in the
123432     ** document nDesired tokens. This block checks if there are actually
123433     ** nDesired tokens to the right of the snippet. If so, *piPos and
123434     ** *pHlMask are updated to shift the snippet nDesired tokens to the
123435     ** right. Otherwise, the snippet is shifted by the number of tokens
123436     ** available.
123437     */
123438     if( nDesired>0 ){
123439       int nShift;                 /* Number of tokens to shift snippet by */
123440       int iCurrent = 0;           /* Token counter */
123441       int rc;                     /* Return Code */
123442       sqlite3_tokenizer_module *pMod;
123443       sqlite3_tokenizer_cursor *pC;
123444       pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
123445
123446       /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
123447       ** or more tokens in zDoc/nDoc.
123448       */
123449       rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
123450       if( rc!=SQLITE_OK ){
123451         return rc;
123452       }
123453       pC->pTokenizer = pTab->pTokenizer;
123454       while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
123455         const char *ZDUMMY; int DUMMY1, DUMMY2, DUMMY3;
123456         rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
123457       }
123458       pMod->xClose(pC);
123459       if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
123460
123461       nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
123462       assert( nShift<=nDesired );
123463       if( nShift>0 ){
123464         *piPos += nShift;
123465         *pHlmask = hlmask >> nShift;
123466       }
123467     }
123468   }
123469   return SQLITE_OK;
123470 }
123471
123472 /*
123473 ** Extract the snippet text for fragment pFragment from cursor pCsr and
123474 ** append it to string buffer pOut.
123475 */
123476 static int fts3SnippetText(
123477   Fts3Cursor *pCsr,               /* FTS3 Cursor */
123478   SnippetFragment *pFragment,     /* Snippet to extract */
123479   int iFragment,                  /* Fragment number */
123480   int isLast,                     /* True for final fragment in snippet */
123481   int nSnippet,                   /* Number of tokens in extracted snippet */
123482   const char *zOpen,              /* String inserted before highlighted term */
123483   const char *zClose,             /* String inserted after highlighted term */
123484   const char *zEllipsis,          /* String inserted between snippets */
123485   StrBuffer *pOut                 /* Write output here */
123486 ){
123487   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
123488   int rc;                         /* Return code */
123489   const char *zDoc;               /* Document text to extract snippet from */
123490   int nDoc;                       /* Size of zDoc in bytes */
123491   int iCurrent = 0;               /* Current token number of document */
123492   int iEnd = 0;                   /* Byte offset of end of current token */
123493   int isShiftDone = 0;            /* True after snippet is shifted */
123494   int iPos = pFragment->iPos;     /* First token of snippet */
123495   u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
123496   int iCol = pFragment->iCol+1;   /* Query column to extract text from */
123497   sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
123498   sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
123499   const char *ZDUMMY;             /* Dummy argument used with tokenizer */
123500   int DUMMY1;                     /* Dummy argument used with tokenizer */
123501   
123502   zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
123503   if( zDoc==0 ){
123504     if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
123505       return SQLITE_NOMEM;
123506     }
123507     return SQLITE_OK;
123508   }
123509   nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
123510
123511   /* Open a token cursor on the document. */
123512   pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
123513   rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
123514   if( rc!=SQLITE_OK ){
123515     return rc;
123516   }
123517   pC->pTokenizer = pTab->pTokenizer;
123518
123519   while( rc==SQLITE_OK ){
123520     int iBegin;                   /* Offset in zDoc of start of token */
123521     int iFin;                     /* Offset in zDoc of end of token */
123522     int isHighlight;              /* True for highlighted terms */
123523
123524     rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
123525     if( rc!=SQLITE_OK ){
123526       if( rc==SQLITE_DONE ){
123527         /* Special case - the last token of the snippet is also the last token
123528         ** of the column. Append any punctuation that occurred between the end
123529         ** of the previous token and the end of the document to the output. 
123530         ** Then break out of the loop. */
123531         rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
123532       }
123533       break;
123534     }
123535     if( iCurrent<iPos ){ continue; }
123536
123537     if( !isShiftDone ){
123538       int n = nDoc - iBegin;
123539       rc = fts3SnippetShift(pTab, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask);
123540       isShiftDone = 1;
123541
123542       /* Now that the shift has been done, check if the initial "..." are
123543       ** required. They are required if (a) this is not the first fragment,
123544       ** or (b) this fragment does not begin at position 0 of its column. 
123545       */
123546       if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){
123547         rc = fts3StringAppend(pOut, zEllipsis, -1);
123548       }
123549       if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
123550     }
123551
123552     if( iCurrent>=(iPos+nSnippet) ){
123553       if( isLast ){
123554         rc = fts3StringAppend(pOut, zEllipsis, -1);
123555       }
123556       break;
123557     }
123558
123559     /* Set isHighlight to true if this term should be highlighted. */
123560     isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
123561
123562     if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
123563     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
123564     if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
123565     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
123566
123567     iEnd = iFin;
123568   }
123569
123570   pMod->xClose(pC);
123571   return rc;
123572 }
123573
123574
123575 /*
123576 ** This function is used to count the entries in a column-list (a 
123577 ** delta-encoded list of term offsets within a single column of a single 
123578 ** row). When this function is called, *ppCollist should point to the
123579 ** beginning of the first varint in the column-list (the varint that
123580 ** contains the position of the first matching term in the column data).
123581 ** Before returning, *ppCollist is set to point to the first byte after
123582 ** the last varint in the column-list (either the 0x00 signifying the end
123583 ** of the position-list, or the 0x01 that precedes the column number of
123584 ** the next column in the position-list).
123585 **
123586 ** The number of elements in the column-list is returned.
123587 */
123588 static int fts3ColumnlistCount(char **ppCollist){
123589   char *pEnd = *ppCollist;
123590   char c = 0;
123591   int nEntry = 0;
123592
123593   /* A column-list is terminated by either a 0x01 or 0x00. */
123594   while( 0xFE & (*pEnd | c) ){
123595     c = *pEnd++ & 0x80;
123596     if( !c ) nEntry++;
123597   }
123598
123599   *ppCollist = pEnd;
123600   return nEntry;
123601 }
123602
123603 /*
123604 ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
123605 ** for a single query. 
123606 **
123607 ** fts3ExprIterate() callback to load the 'global' elements of a
123608 ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements 
123609 ** of the matchinfo array that are constant for all rows returned by the 
123610 ** current query.
123611 **
123612 ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
123613 ** function populates Matchinfo.aMatchinfo[] as follows:
123614 **
123615 **   for(iCol=0; iCol<nCol; iCol++){
123616 **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
123617 **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
123618 **   }
123619 **
123620 ** where X is the number of matches for phrase iPhrase is column iCol of all
123621 ** rows of the table. Y is the number of rows for which column iCol contains
123622 ** at least one instance of phrase iPhrase.
123623 **
123624 ** If the phrase pExpr consists entirely of deferred tokens, then all X and
123625 ** Y values are set to nDoc, where nDoc is the number of documents in the 
123626 ** file system. This is done because the full-text index doclist is required
123627 ** to calculate these values properly, and the full-text index doclist is
123628 ** not available for deferred tokens.
123629 */
123630 static int fts3ExprGlobalHitsCb(
123631   Fts3Expr *pExpr,                /* Phrase expression node */
123632   int iPhrase,                    /* Phrase number (numbered from zero) */
123633   void *pCtx                      /* Pointer to MatchInfo structure */
123634 ){
123635   MatchInfo *p = (MatchInfo *)pCtx;
123636   return sqlite3Fts3EvalPhraseStats(
123637       p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
123638   );
123639 }
123640
123641 /*
123642 ** fts3ExprIterate() callback used to collect the "local" part of the
123643 ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the 
123644 ** array that are different for each row returned by the query.
123645 */
123646 static int fts3ExprLocalHitsCb(
123647   Fts3Expr *pExpr,                /* Phrase expression node */
123648   int iPhrase,                    /* Phrase number */
123649   void *pCtx                      /* Pointer to MatchInfo structure */
123650 ){
123651   MatchInfo *p = (MatchInfo *)pCtx;
123652   int iStart = iPhrase * p->nCol * 3;
123653   int i;
123654
123655   for(i=0; i<p->nCol; i++){
123656     char *pCsr;
123657     pCsr = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i);
123658     if( pCsr ){
123659       p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
123660     }else{
123661       p->aMatchinfo[iStart+i*3] = 0;
123662     }
123663   }
123664
123665   return SQLITE_OK;
123666 }
123667
123668 static int fts3MatchinfoCheck(
123669   Fts3Table *pTab, 
123670   char cArg,
123671   char **pzErr
123672 ){
123673   if( (cArg==FTS3_MATCHINFO_NPHRASE)
123674    || (cArg==FTS3_MATCHINFO_NCOL)
123675    || (cArg==FTS3_MATCHINFO_NDOC && pTab->bHasStat)
123676    || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bHasStat)
123677    || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
123678    || (cArg==FTS3_MATCHINFO_LCS)
123679    || (cArg==FTS3_MATCHINFO_HITS)
123680   ){
123681     return SQLITE_OK;
123682   }
123683   *pzErr = sqlite3_mprintf("unrecognized matchinfo request: %c", cArg);
123684   return SQLITE_ERROR;
123685 }
123686
123687 static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
123688   int nVal;                       /* Number of integers output by cArg */
123689
123690   switch( cArg ){
123691     case FTS3_MATCHINFO_NDOC:
123692     case FTS3_MATCHINFO_NPHRASE: 
123693     case FTS3_MATCHINFO_NCOL: 
123694       nVal = 1;
123695       break;
123696
123697     case FTS3_MATCHINFO_AVGLENGTH:
123698     case FTS3_MATCHINFO_LENGTH:
123699     case FTS3_MATCHINFO_LCS:
123700       nVal = pInfo->nCol;
123701       break;
123702
123703     default:
123704       assert( cArg==FTS3_MATCHINFO_HITS );
123705       nVal = pInfo->nCol * pInfo->nPhrase * 3;
123706       break;
123707   }
123708
123709   return nVal;
123710 }
123711
123712 static int fts3MatchinfoSelectDoctotal(
123713   Fts3Table *pTab,
123714   sqlite3_stmt **ppStmt,
123715   sqlite3_int64 *pnDoc,
123716   const char **paLen
123717 ){
123718   sqlite3_stmt *pStmt;
123719   const char *a;
123720   sqlite3_int64 nDoc;
123721
123722   if( !*ppStmt ){
123723     int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
123724     if( rc!=SQLITE_OK ) return rc;
123725   }
123726   pStmt = *ppStmt;
123727   assert( sqlite3_data_count(pStmt)==1 );
123728
123729   a = sqlite3_column_blob(pStmt, 0);
123730   a += sqlite3Fts3GetVarint(a, &nDoc);
123731   if( nDoc==0 ) return SQLITE_CORRUPT_VTAB;
123732   *pnDoc = (u32)nDoc;
123733
123734   if( paLen ) *paLen = a;
123735   return SQLITE_OK;
123736 }
123737
123738 /*
123739 ** An instance of the following structure is used to store state while 
123740 ** iterating through a multi-column position-list corresponding to the
123741 ** hits for a single phrase on a single row in order to calculate the
123742 ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
123743 */
123744 typedef struct LcsIterator LcsIterator;
123745 struct LcsIterator {
123746   Fts3Expr *pExpr;                /* Pointer to phrase expression */
123747   int iPosOffset;                 /* Tokens count up to end of this phrase */
123748   char *pRead;                    /* Cursor used to iterate through aDoclist */
123749   int iPos;                       /* Current position */
123750 };
123751
123752 /* 
123753 ** If LcsIterator.iCol is set to the following value, the iterator has
123754 ** finished iterating through all offsets for all columns.
123755 */
123756 #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
123757
123758 static int fts3MatchinfoLcsCb(
123759   Fts3Expr *pExpr,                /* Phrase expression node */
123760   int iPhrase,                    /* Phrase number (numbered from zero) */
123761   void *pCtx                      /* Pointer to MatchInfo structure */
123762 ){
123763   LcsIterator *aIter = (LcsIterator *)pCtx;
123764   aIter[iPhrase].pExpr = pExpr;
123765   return SQLITE_OK;
123766 }
123767
123768 /*
123769 ** Advance the iterator passed as an argument to the next position. Return
123770 ** 1 if the iterator is at EOF or if it now points to the start of the
123771 ** position list for the next column.
123772 */
123773 static int fts3LcsIteratorAdvance(LcsIterator *pIter){
123774   char *pRead = pIter->pRead;
123775   sqlite3_int64 iRead;
123776   int rc = 0;
123777
123778   pRead += sqlite3Fts3GetVarint(pRead, &iRead);
123779   if( iRead==0 || iRead==1 ){
123780     pRead = 0;
123781     rc = 1;
123782   }else{
123783     pIter->iPos += (int)(iRead-2);
123784   }
123785
123786   pIter->pRead = pRead;
123787   return rc;
123788 }
123789   
123790 /*
123791 ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag. 
123792 **
123793 ** If the call is successful, the longest-common-substring lengths for each
123794 ** column are written into the first nCol elements of the pInfo->aMatchinfo[] 
123795 ** array before returning. SQLITE_OK is returned in this case.
123796 **
123797 ** Otherwise, if an error occurs, an SQLite error code is returned and the
123798 ** data written to the first nCol elements of pInfo->aMatchinfo[] is 
123799 ** undefined.
123800 */
123801 static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
123802   LcsIterator *aIter;
123803   int i;
123804   int iCol;
123805   int nToken = 0;
123806
123807   /* Allocate and populate the array of LcsIterator objects. The array
123808   ** contains one element for each matchable phrase in the query.
123809   **/
123810   aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
123811   if( !aIter ) return SQLITE_NOMEM;
123812   memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
123813   (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
123814
123815   for(i=0; i<pInfo->nPhrase; i++){
123816     LcsIterator *pIter = &aIter[i];
123817     nToken -= pIter->pExpr->pPhrase->nToken;
123818     pIter->iPosOffset = nToken;
123819   }
123820
123821   for(iCol=0; iCol<pInfo->nCol; iCol++){
123822     int nLcs = 0;                 /* LCS value for this column */
123823     int nLive = 0;                /* Number of iterators in aIter not at EOF */
123824
123825     for(i=0; i<pInfo->nPhrase; i++){
123826       LcsIterator *pIt = &aIter[i];
123827       pIt->pRead = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol);
123828       if( pIt->pRead ){
123829         pIt->iPos = pIt->iPosOffset;
123830         fts3LcsIteratorAdvance(&aIter[i]);
123831         nLive++;
123832       }
123833     }
123834
123835     while( nLive>0 ){
123836       LcsIterator *pAdv = 0;      /* The iterator to advance by one position */
123837       int nThisLcs = 0;           /* LCS for the current iterator positions */
123838
123839       for(i=0; i<pInfo->nPhrase; i++){
123840         LcsIterator *pIter = &aIter[i];
123841         if( pIter->pRead==0 ){
123842           /* This iterator is already at EOF for this column. */
123843           nThisLcs = 0;
123844         }else{
123845           if( pAdv==0 || pIter->iPos<pAdv->iPos ){
123846             pAdv = pIter;
123847           }
123848           if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
123849             nThisLcs++;
123850           }else{
123851             nThisLcs = 1;
123852           }
123853           if( nThisLcs>nLcs ) nLcs = nThisLcs;
123854         }
123855       }
123856       if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
123857     }
123858
123859     pInfo->aMatchinfo[iCol] = nLcs;
123860   }
123861
123862   sqlite3_free(aIter);
123863   return SQLITE_OK;
123864 }
123865
123866 /*
123867 ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
123868 ** be returned by the matchinfo() function. Argument zArg contains the 
123869 ** format string passed as the second argument to matchinfo (or the
123870 ** default value "pcx" if no second argument was specified). The format
123871 ** string has already been validated and the pInfo->aMatchinfo[] array
123872 ** is guaranteed to be large enough for the output.
123873 **
123874 ** If bGlobal is true, then populate all fields of the matchinfo() output.
123875 ** If it is false, then assume that those fields that do not change between
123876 ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
123877 ** have already been populated.
123878 **
123879 ** Return SQLITE_OK if successful, or an SQLite error code if an error 
123880 ** occurs. If a value other than SQLITE_OK is returned, the state the
123881 ** pInfo->aMatchinfo[] buffer is left in is undefined.
123882 */
123883 static int fts3MatchinfoValues(
123884   Fts3Cursor *pCsr,               /* FTS3 cursor object */
123885   int bGlobal,                    /* True to grab the global stats */
123886   MatchInfo *pInfo,               /* Matchinfo context object */
123887   const char *zArg                /* Matchinfo format string */
123888 ){
123889   int rc = SQLITE_OK;
123890   int i;
123891   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
123892   sqlite3_stmt *pSelect = 0;
123893
123894   for(i=0; rc==SQLITE_OK && zArg[i]; i++){
123895
123896     switch( zArg[i] ){
123897       case FTS3_MATCHINFO_NPHRASE:
123898         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
123899         break;
123900
123901       case FTS3_MATCHINFO_NCOL:
123902         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
123903         break;
123904         
123905       case FTS3_MATCHINFO_NDOC:
123906         if( bGlobal ){
123907           sqlite3_int64 nDoc = 0;
123908           rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
123909           pInfo->aMatchinfo[0] = (u32)nDoc;
123910         }
123911         break;
123912
123913       case FTS3_MATCHINFO_AVGLENGTH: 
123914         if( bGlobal ){
123915           sqlite3_int64 nDoc;     /* Number of rows in table */
123916           const char *a;          /* Aggregate column length array */
123917
123918           rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
123919           if( rc==SQLITE_OK ){
123920             int iCol;
123921             for(iCol=0; iCol<pInfo->nCol; iCol++){
123922               u32 iVal;
123923               sqlite3_int64 nToken;
123924               a += sqlite3Fts3GetVarint(a, &nToken);
123925               iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
123926               pInfo->aMatchinfo[iCol] = iVal;
123927             }
123928           }
123929         }
123930         break;
123931
123932       case FTS3_MATCHINFO_LENGTH: {
123933         sqlite3_stmt *pSelectDocsize = 0;
123934         rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
123935         if( rc==SQLITE_OK ){
123936           int iCol;
123937           const char *a = sqlite3_column_blob(pSelectDocsize, 0);
123938           for(iCol=0; iCol<pInfo->nCol; iCol++){
123939             sqlite3_int64 nToken;
123940             a += sqlite3Fts3GetVarint(a, &nToken);
123941             pInfo->aMatchinfo[iCol] = (u32)nToken;
123942           }
123943         }
123944         sqlite3_reset(pSelectDocsize);
123945         break;
123946       }
123947
123948       case FTS3_MATCHINFO_LCS:
123949         rc = fts3ExprLoadDoclists(pCsr, 0, 0);
123950         if( rc==SQLITE_OK ){
123951           rc = fts3MatchinfoLcs(pCsr, pInfo);
123952         }
123953         break;
123954
123955       default: {
123956         Fts3Expr *pExpr;
123957         assert( zArg[i]==FTS3_MATCHINFO_HITS );
123958         pExpr = pCsr->pExpr;
123959         rc = fts3ExprLoadDoclists(pCsr, 0, 0);
123960         if( rc!=SQLITE_OK ) break;
123961         if( bGlobal ){
123962           if( pCsr->pDeferred ){
123963             rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
123964             if( rc!=SQLITE_OK ) break;
123965           }
123966           rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
123967           if( rc!=SQLITE_OK ) break;
123968         }
123969         (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
123970         break;
123971       }
123972     }
123973
123974     pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
123975   }
123976
123977   sqlite3_reset(pSelect);
123978   return rc;
123979 }
123980
123981
123982 /*
123983 ** Populate pCsr->aMatchinfo[] with data for the current row. The 
123984 ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
123985 */
123986 static int fts3GetMatchinfo(
123987   Fts3Cursor *pCsr,               /* FTS3 Cursor object */
123988   const char *zArg                /* Second argument to matchinfo() function */
123989 ){
123990   MatchInfo sInfo;
123991   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
123992   int rc = SQLITE_OK;
123993   int bGlobal = 0;                /* Collect 'global' stats as well as local */
123994
123995   memset(&sInfo, 0, sizeof(MatchInfo));
123996   sInfo.pCursor = pCsr;
123997   sInfo.nCol = pTab->nColumn;
123998
123999   /* If there is cached matchinfo() data, but the format string for the 
124000   ** cache does not match the format string for this request, discard 
124001   ** the cached data. */
124002   if( pCsr->zMatchinfo && strcmp(pCsr->zMatchinfo, zArg) ){
124003     assert( pCsr->aMatchinfo );
124004     sqlite3_free(pCsr->aMatchinfo);
124005     pCsr->zMatchinfo = 0;
124006     pCsr->aMatchinfo = 0;
124007   }
124008
124009   /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
124010   ** matchinfo function has been called for this query. In this case 
124011   ** allocate the array used to accumulate the matchinfo data and
124012   ** initialize those elements that are constant for every row.
124013   */
124014   if( pCsr->aMatchinfo==0 ){
124015     int nMatchinfo = 0;           /* Number of u32 elements in match-info */
124016     int nArg;                     /* Bytes in zArg */
124017     int i;                        /* Used to iterate through zArg */
124018
124019     /* Determine the number of phrases in the query */
124020     pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
124021     sInfo.nPhrase = pCsr->nPhrase;
124022
124023     /* Determine the number of integers in the buffer returned by this call. */
124024     for(i=0; zArg[i]; i++){
124025       nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
124026     }
124027
124028     /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
124029     nArg = (int)strlen(zArg);
124030     pCsr->aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo + nArg + 1);
124031     if( !pCsr->aMatchinfo ) return SQLITE_NOMEM;
124032
124033     pCsr->zMatchinfo = (char *)&pCsr->aMatchinfo[nMatchinfo];
124034     pCsr->nMatchinfo = nMatchinfo;
124035     memcpy(pCsr->zMatchinfo, zArg, nArg+1);
124036     memset(pCsr->aMatchinfo, 0, sizeof(u32)*nMatchinfo);
124037     pCsr->isMatchinfoNeeded = 1;
124038     bGlobal = 1;
124039   }
124040
124041   sInfo.aMatchinfo = pCsr->aMatchinfo;
124042   sInfo.nPhrase = pCsr->nPhrase;
124043   if( pCsr->isMatchinfoNeeded ){
124044     rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
124045     pCsr->isMatchinfoNeeded = 0;
124046   }
124047
124048   return rc;
124049 }
124050
124051 /*
124052 ** Implementation of snippet() function.
124053 */
124054 SQLITE_PRIVATE void sqlite3Fts3Snippet(
124055   sqlite3_context *pCtx,          /* SQLite function call context */
124056   Fts3Cursor *pCsr,               /* Cursor object */
124057   const char *zStart,             /* Snippet start text - "<b>" */
124058   const char *zEnd,               /* Snippet end text - "</b>" */
124059   const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
124060   int iCol,                       /* Extract snippet from this column */
124061   int nToken                      /* Approximate number of tokens in snippet */
124062 ){
124063   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
124064   int rc = SQLITE_OK;
124065   int i;
124066   StrBuffer res = {0, 0, 0};
124067
124068   /* The returned text includes up to four fragments of text extracted from
124069   ** the data in the current row. The first iteration of the for(...) loop
124070   ** below attempts to locate a single fragment of text nToken tokens in 
124071   ** size that contains at least one instance of all phrases in the query
124072   ** expression that appear in the current row. If such a fragment of text
124073   ** cannot be found, the second iteration of the loop attempts to locate
124074   ** a pair of fragments, and so on.
124075   */
124076   int nSnippet = 0;               /* Number of fragments in this snippet */
124077   SnippetFragment aSnippet[4];    /* Maximum of 4 fragments per snippet */
124078   int nFToken = -1;               /* Number of tokens in each fragment */
124079
124080   if( !pCsr->pExpr ){
124081     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
124082     return;
124083   }
124084
124085   for(nSnippet=1; 1; nSnippet++){
124086
124087     int iSnip;                    /* Loop counter 0..nSnippet-1 */
124088     u64 mCovered = 0;             /* Bitmask of phrases covered by snippet */
124089     u64 mSeen = 0;                /* Bitmask of phrases seen by BestSnippet() */
124090
124091     if( nToken>=0 ){
124092       nFToken = (nToken+nSnippet-1) / nSnippet;
124093     }else{
124094       nFToken = -1 * nToken;
124095     }
124096
124097     for(iSnip=0; iSnip<nSnippet; iSnip++){
124098       int iBestScore = -1;        /* Best score of columns checked so far */
124099       int iRead;                  /* Used to iterate through columns */
124100       SnippetFragment *pFragment = &aSnippet[iSnip];
124101
124102       memset(pFragment, 0, sizeof(*pFragment));
124103
124104       /* Loop through all columns of the table being considered for snippets.
124105       ** If the iCol argument to this function was negative, this means all
124106       ** columns of the FTS3 table. Otherwise, only column iCol is considered.
124107       */
124108       for(iRead=0; iRead<pTab->nColumn; iRead++){
124109         SnippetFragment sF = {0, 0, 0, 0};
124110         int iS;
124111         if( iCol>=0 && iRead!=iCol ) continue;
124112
124113         /* Find the best snippet of nFToken tokens in column iRead. */
124114         rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
124115         if( rc!=SQLITE_OK ){
124116           goto snippet_out;
124117         }
124118         if( iS>iBestScore ){
124119           *pFragment = sF;
124120           iBestScore = iS;
124121         }
124122       }
124123
124124       mCovered |= pFragment->covered;
124125     }
124126
124127     /* If all query phrases seen by fts3BestSnippet() are present in at least
124128     ** one of the nSnippet snippet fragments, break out of the loop.
124129     */
124130     assert( (mCovered&mSeen)==mCovered );
124131     if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
124132   }
124133
124134   assert( nFToken>0 );
124135
124136   for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
124137     rc = fts3SnippetText(pCsr, &aSnippet[i], 
124138         i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
124139     );
124140   }
124141
124142  snippet_out:
124143   sqlite3Fts3SegmentsClose(pTab);
124144   if( rc!=SQLITE_OK ){
124145     sqlite3_result_error_code(pCtx, rc);
124146     sqlite3_free(res.z);
124147   }else{
124148     sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
124149   }
124150 }
124151
124152
124153 typedef struct TermOffset TermOffset;
124154 typedef struct TermOffsetCtx TermOffsetCtx;
124155
124156 struct TermOffset {
124157   char *pList;                    /* Position-list */
124158   int iPos;                       /* Position just read from pList */
124159   int iOff;                       /* Offset of this term from read positions */
124160 };
124161
124162 struct TermOffsetCtx {
124163   Fts3Cursor *pCsr;
124164   int iCol;                       /* Column of table to populate aTerm for */
124165   int iTerm;
124166   sqlite3_int64 iDocid;
124167   TermOffset *aTerm;
124168 };
124169
124170 /*
124171 ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
124172 */
124173 static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
124174   TermOffsetCtx *p = (TermOffsetCtx *)ctx;
124175   int nTerm;                      /* Number of tokens in phrase */
124176   int iTerm;                      /* For looping through nTerm phrase terms */
124177   char *pList;                    /* Pointer to position list for phrase */
124178   int iPos = 0;                   /* First position in position-list */
124179
124180   UNUSED_PARAMETER(iPhrase);
124181   pList = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol);
124182   nTerm = pExpr->pPhrase->nToken;
124183   if( pList ){
124184     fts3GetDeltaPosition(&pList, &iPos);
124185     assert( iPos>=0 );
124186   }
124187
124188   for(iTerm=0; iTerm<nTerm; iTerm++){
124189     TermOffset *pT = &p->aTerm[p->iTerm++];
124190     pT->iOff = nTerm-iTerm-1;
124191     pT->pList = pList;
124192     pT->iPos = iPos;
124193   }
124194
124195   return SQLITE_OK;
124196 }
124197
124198 /*
124199 ** Implementation of offsets() function.
124200 */
124201 SQLITE_PRIVATE void sqlite3Fts3Offsets(
124202   sqlite3_context *pCtx,          /* SQLite function call context */
124203   Fts3Cursor *pCsr                /* Cursor object */
124204 ){
124205   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
124206   sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
124207   const char *ZDUMMY;             /* Dummy argument used with xNext() */
124208   int NDUMMY;                     /* Dummy argument used with xNext() */
124209   int rc;                         /* Return Code */
124210   int nToken;                     /* Number of tokens in query */
124211   int iCol;                       /* Column currently being processed */
124212   StrBuffer res = {0, 0, 0};      /* Result string */
124213   TermOffsetCtx sCtx;             /* Context for fts3ExprTermOffsetInit() */
124214
124215   if( !pCsr->pExpr ){
124216     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
124217     return;
124218   }
124219
124220   memset(&sCtx, 0, sizeof(sCtx));
124221   assert( pCsr->isRequireSeek==0 );
124222
124223   /* Count the number of terms in the query */
124224   rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
124225   if( rc!=SQLITE_OK ) goto offsets_out;
124226
124227   /* Allocate the array of TermOffset iterators. */
124228   sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
124229   if( 0==sCtx.aTerm ){
124230     rc = SQLITE_NOMEM;
124231     goto offsets_out;
124232   }
124233   sCtx.iDocid = pCsr->iPrevId;
124234   sCtx.pCsr = pCsr;
124235
124236   /* Loop through the table columns, appending offset information to 
124237   ** string-buffer res for each column.
124238   */
124239   for(iCol=0; iCol<pTab->nColumn; iCol++){
124240     sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
124241     int iStart;
124242     int iEnd;
124243     int iCurrent;
124244     const char *zDoc;
124245     int nDoc;
124246
124247     /* Initialize the contents of sCtx.aTerm[] for column iCol. There is 
124248     ** no way that this operation can fail, so the return code from
124249     ** fts3ExprIterate() can be discarded.
124250     */
124251     sCtx.iCol = iCol;
124252     sCtx.iTerm = 0;
124253     (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
124254
124255     /* Retreive the text stored in column iCol. If an SQL NULL is stored 
124256     ** in column iCol, jump immediately to the next iteration of the loop.
124257     ** If an OOM occurs while retrieving the data (this can happen if SQLite
124258     ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM 
124259     ** to the caller. 
124260     */
124261     zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
124262     nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
124263     if( zDoc==0 ){
124264       if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
124265         continue;
124266       }
124267       rc = SQLITE_NOMEM;
124268       goto offsets_out;
124269     }
124270
124271     /* Initialize a tokenizer iterator to iterate through column iCol. */
124272     rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
124273     if( rc!=SQLITE_OK ) goto offsets_out;
124274     pC->pTokenizer = pTab->pTokenizer;
124275
124276     rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
124277     while( rc==SQLITE_OK ){
124278       int i;                      /* Used to loop through terms */
124279       int iMinPos = 0x7FFFFFFF;   /* Position of next token */
124280       TermOffset *pTerm = 0;      /* TermOffset associated with next token */
124281
124282       for(i=0; i<nToken; i++){
124283         TermOffset *pT = &sCtx.aTerm[i];
124284         if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
124285           iMinPos = pT->iPos-pT->iOff;
124286           pTerm = pT;
124287         }
124288       }
124289
124290       if( !pTerm ){
124291         /* All offsets for this column have been gathered. */
124292         break;
124293       }else{
124294         assert( iCurrent<=iMinPos );
124295         if( 0==(0xFE&*pTerm->pList) ){
124296           pTerm->pList = 0;
124297         }else{
124298           fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
124299         }
124300         while( rc==SQLITE_OK && iCurrent<iMinPos ){
124301           rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
124302         }
124303         if( rc==SQLITE_OK ){
124304           char aBuffer[64];
124305           sqlite3_snprintf(sizeof(aBuffer), aBuffer, 
124306               "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
124307           );
124308           rc = fts3StringAppend(&res, aBuffer, -1);
124309         }else if( rc==SQLITE_DONE ){
124310           rc = SQLITE_CORRUPT_VTAB;
124311         }
124312       }
124313     }
124314     if( rc==SQLITE_DONE ){
124315       rc = SQLITE_OK;
124316     }
124317
124318     pMod->xClose(pC);
124319     if( rc!=SQLITE_OK ) goto offsets_out;
124320   }
124321
124322  offsets_out:
124323   sqlite3_free(sCtx.aTerm);
124324   assert( rc!=SQLITE_DONE );
124325   sqlite3Fts3SegmentsClose(pTab);
124326   if( rc!=SQLITE_OK ){
124327     sqlite3_result_error_code(pCtx,  rc);
124328     sqlite3_free(res.z);
124329   }else{
124330     sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
124331   }
124332   return;
124333 }
124334
124335 /*
124336 ** Implementation of matchinfo() function.
124337 */
124338 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
124339   sqlite3_context *pContext,      /* Function call context */
124340   Fts3Cursor *pCsr,               /* FTS3 table cursor */
124341   const char *zArg                /* Second arg to matchinfo() function */
124342 ){
124343   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
124344   int rc;
124345   int i;
124346   const char *zFormat;
124347
124348   if( zArg ){
124349     for(i=0; zArg[i]; i++){
124350       char *zErr = 0;
124351       if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
124352         sqlite3_result_error(pContext, zErr, -1);
124353         sqlite3_free(zErr);
124354         return;
124355       }
124356     }
124357     zFormat = zArg;
124358   }else{
124359     zFormat = FTS3_MATCHINFO_DEFAULT;
124360   }
124361
124362   if( !pCsr->pExpr ){
124363     sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
124364     return;
124365   }
124366
124367   /* Retrieve matchinfo() data. */
124368   rc = fts3GetMatchinfo(pCsr, zFormat);
124369   sqlite3Fts3SegmentsClose(pTab);
124370
124371   if( rc!=SQLITE_OK ){
124372     sqlite3_result_error_code(pContext, rc);
124373   }else{
124374     int n = pCsr->nMatchinfo * sizeof(u32);
124375     sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
124376   }
124377 }
124378
124379 #endif
124380
124381 /************** End of fts3_snippet.c ****************************************/
124382 /************** Begin file rtree.c *******************************************/
124383 /*
124384 ** 2001 September 15
124385 **
124386 ** The author disclaims copyright to this source code.  In place of
124387 ** a legal notice, here is a blessing:
124388 **
124389 **    May you do good and not evil.
124390 **    May you find forgiveness for yourself and forgive others.
124391 **    May you share freely, never taking more than you give.
124392 **
124393 *************************************************************************
124394 ** This file contains code for implementations of the r-tree and r*-tree
124395 ** algorithms packaged as an SQLite virtual table module.
124396 */
124397
124398 /*
124399 ** Database Format of R-Tree Tables
124400 ** --------------------------------
124401 **
124402 ** The data structure for a single virtual r-tree table is stored in three 
124403 ** native SQLite tables declared as follows. In each case, the '%' character
124404 ** in the table name is replaced with the user-supplied name of the r-tree
124405 ** table.
124406 **
124407 **   CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
124408 **   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
124409 **   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
124410 **
124411 ** The data for each node of the r-tree structure is stored in the %_node
124412 ** table. For each node that is not the root node of the r-tree, there is
124413 ** an entry in the %_parent table associating the node with its parent.
124414 ** And for each row of data in the table, there is an entry in the %_rowid
124415 ** table that maps from the entries rowid to the id of the node that it
124416 ** is stored on.
124417 **
124418 ** The root node of an r-tree always exists, even if the r-tree table is
124419 ** empty. The nodeno of the root node is always 1. All other nodes in the
124420 ** table must be the same size as the root node. The content of each node
124421 ** is formatted as follows:
124422 **
124423 **   1. If the node is the root node (node 1), then the first 2 bytes
124424 **      of the node contain the tree depth as a big-endian integer.
124425 **      For non-root nodes, the first 2 bytes are left unused.
124426 **
124427 **   2. The next 2 bytes contain the number of entries currently 
124428 **      stored in the node.
124429 **
124430 **   3. The remainder of the node contains the node entries. Each entry
124431 **      consists of a single 8-byte integer followed by an even number
124432 **      of 4-byte coordinates. For leaf nodes the integer is the rowid
124433 **      of a record. For internal nodes it is the node number of a
124434 **      child page.
124435 */
124436
124437 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
124438
124439 /*
124440 ** This file contains an implementation of a couple of different variants
124441 ** of the r-tree algorithm. See the README file for further details. The 
124442 ** same data-structure is used for all, but the algorithms for insert and
124443 ** delete operations vary. The variants used are selected at compile time 
124444 ** by defining the following symbols:
124445 */
124446
124447 /* Either, both or none of the following may be set to activate 
124448 ** r*tree variant algorithms.
124449 */
124450 #define VARIANT_RSTARTREE_CHOOSESUBTREE 0
124451 #define VARIANT_RSTARTREE_REINSERT      1
124452
124453 /* 
124454 ** Exactly one of the following must be set to 1.
124455 */
124456 #define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
124457 #define VARIANT_GUTTMAN_LINEAR_SPLIT    0
124458 #define VARIANT_RSTARTREE_SPLIT         1
124459
124460 #define VARIANT_GUTTMAN_SPLIT \
124461         (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
124462
124463 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
124464   #define PickNext QuadraticPickNext
124465   #define PickSeeds QuadraticPickSeeds
124466   #define AssignCells splitNodeGuttman
124467 #endif
124468 #if VARIANT_GUTTMAN_LINEAR_SPLIT
124469   #define PickNext LinearPickNext
124470   #define PickSeeds LinearPickSeeds
124471   #define AssignCells splitNodeGuttman
124472 #endif
124473 #if VARIANT_RSTARTREE_SPLIT
124474   #define AssignCells splitNodeStartree
124475 #endif
124476
124477 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
124478 # define NDEBUG 1
124479 #endif
124480
124481 #ifndef SQLITE_CORE
124482   SQLITE_EXTENSION_INIT1
124483 #else
124484 #endif
124485
124486
124487 #ifndef SQLITE_AMALGAMATION
124488 #include "sqlite3rtree.h"
124489 typedef sqlite3_int64 i64;
124490 typedef unsigned char u8;
124491 typedef unsigned int u32;
124492 #endif
124493
124494 /*  The following macro is used to suppress compiler warnings.
124495 */
124496 #ifndef UNUSED_PARAMETER
124497 # define UNUSED_PARAMETER(x) (void)(x)
124498 #endif
124499
124500 typedef struct Rtree Rtree;
124501 typedef struct RtreeCursor RtreeCursor;
124502 typedef struct RtreeNode RtreeNode;
124503 typedef struct RtreeCell RtreeCell;
124504 typedef struct RtreeConstraint RtreeConstraint;
124505 typedef struct RtreeMatchArg RtreeMatchArg;
124506 typedef struct RtreeGeomCallback RtreeGeomCallback;
124507 typedef union RtreeCoord RtreeCoord;
124508
124509 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
124510 #define RTREE_MAX_DIMENSIONS 5
124511
124512 /* Size of hash table Rtree.aHash. This hash table is not expected to
124513 ** ever contain very many entries, so a fixed number of buckets is 
124514 ** used.
124515 */
124516 #define HASHSIZE 128
124517
124518 /* 
124519 ** An rtree virtual-table object.
124520 */
124521 struct Rtree {
124522   sqlite3_vtab base;
124523   sqlite3 *db;                /* Host database connection */
124524   int iNodeSize;              /* Size in bytes of each node in the node table */
124525   int nDim;                   /* Number of dimensions */
124526   int nBytesPerCell;          /* Bytes consumed per cell */
124527   int iDepth;                 /* Current depth of the r-tree structure */
124528   char *zDb;                  /* Name of database containing r-tree table */
124529   char *zName;                /* Name of r-tree table */ 
124530   RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */ 
124531   int nBusy;                  /* Current number of users of this structure */
124532
124533   /* List of nodes removed during a CondenseTree operation. List is
124534   ** linked together via the pointer normally used for hash chains -
124535   ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree 
124536   ** headed by the node (leaf nodes have RtreeNode.iNode==0).
124537   */
124538   RtreeNode *pDeleted;
124539   int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
124540
124541   /* Statements to read/write/delete a record from xxx_node */
124542   sqlite3_stmt *pReadNode;
124543   sqlite3_stmt *pWriteNode;
124544   sqlite3_stmt *pDeleteNode;
124545
124546   /* Statements to read/write/delete a record from xxx_rowid */
124547   sqlite3_stmt *pReadRowid;
124548   sqlite3_stmt *pWriteRowid;
124549   sqlite3_stmt *pDeleteRowid;
124550
124551   /* Statements to read/write/delete a record from xxx_parent */
124552   sqlite3_stmt *pReadParent;
124553   sqlite3_stmt *pWriteParent;
124554   sqlite3_stmt *pDeleteParent;
124555
124556   int eCoordType;
124557 };
124558
124559 /* Possible values for eCoordType: */
124560 #define RTREE_COORD_REAL32 0
124561 #define RTREE_COORD_INT32  1
124562
124563 /*
124564 ** The minimum number of cells allowed for a node is a third of the 
124565 ** maximum. In Gutman's notation:
124566 **
124567 **     m = M/3
124568 **
124569 ** If an R*-tree "Reinsert" operation is required, the same number of
124570 ** cells are removed from the overfull node and reinserted into the tree.
124571 */
124572 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
124573 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
124574 #define RTREE_MAXCELLS 51
124575
124576 /*
124577 ** The smallest possible node-size is (512-64)==448 bytes. And the largest
124578 ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
124579 ** Therefore all non-root nodes must contain at least 3 entries. Since 
124580 ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
124581 ** 40 or less.
124582 */
124583 #define RTREE_MAX_DEPTH 40
124584
124585 /* 
124586 ** An rtree cursor object.
124587 */
124588 struct RtreeCursor {
124589   sqlite3_vtab_cursor base;
124590   RtreeNode *pNode;                 /* Node cursor is currently pointing at */
124591   int iCell;                        /* Index of current cell in pNode */
124592   int iStrategy;                    /* Copy of idxNum search parameter */
124593   int nConstraint;                  /* Number of entries in aConstraint */
124594   RtreeConstraint *aConstraint;     /* Search constraints. */
124595 };
124596
124597 union RtreeCoord {
124598   float f;
124599   int i;
124600 };
124601
124602 /*
124603 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
124604 ** formatted as a double. This macro assumes that local variable pRtree points
124605 ** to the Rtree structure associated with the RtreeCoord.
124606 */
124607 #define DCOORD(coord) (                           \
124608   (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
124609     ((double)coord.f) :                           \
124610     ((double)coord.i)                             \
124611 )
124612
124613 /*
124614 ** A search constraint.
124615 */
124616 struct RtreeConstraint {
124617   int iCoord;                     /* Index of constrained coordinate */
124618   int op;                         /* Constraining operation */
124619   double rValue;                  /* Constraint value. */
124620   int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
124621   sqlite3_rtree_geometry *pGeom;  /* Constraint callback argument for a MATCH */
124622 };
124623
124624 /* Possible values for RtreeConstraint.op */
124625 #define RTREE_EQ    0x41
124626 #define RTREE_LE    0x42
124627 #define RTREE_LT    0x43
124628 #define RTREE_GE    0x44
124629 #define RTREE_GT    0x45
124630 #define RTREE_MATCH 0x46
124631
124632 /* 
124633 ** An rtree structure node.
124634 */
124635 struct RtreeNode {
124636   RtreeNode *pParent;               /* Parent node */
124637   i64 iNode;
124638   int nRef;
124639   int isDirty;
124640   u8 *zData;
124641   RtreeNode *pNext;                 /* Next node in this hash chain */
124642 };
124643 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
124644
124645 /* 
124646 ** Structure to store a deserialized rtree record.
124647 */
124648 struct RtreeCell {
124649   i64 iRowid;
124650   RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
124651 };
124652
124653
124654 /*
124655 ** Value for the first field of every RtreeMatchArg object. The MATCH
124656 ** operator tests that the first field of a blob operand matches this
124657 ** value to avoid operating on invalid blobs (which could cause a segfault).
124658 */
124659 #define RTREE_GEOMETRY_MAGIC 0x891245AB
124660
124661 /*
124662 ** An instance of this structure must be supplied as a blob argument to
124663 ** the right-hand-side of an SQL MATCH operator used to constrain an
124664 ** r-tree query.
124665 */
124666 struct RtreeMatchArg {
124667   u32 magic;                      /* Always RTREE_GEOMETRY_MAGIC */
124668   int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
124669   void *pContext;
124670   int nParam;
124671   double aParam[1];
124672 };
124673
124674 /*
124675 ** When a geometry callback is created (see sqlite3_rtree_geometry_callback),
124676 ** a single instance of the following structure is allocated. It is used
124677 ** as the context for the user-function created by by s_r_g_c(). The object
124678 ** is eventually deleted by the destructor mechanism provided by
124679 ** sqlite3_create_function_v2() (which is called by s_r_g_c() to create
124680 ** the geometry callback function).
124681 */
124682 struct RtreeGeomCallback {
124683   int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
124684   void *pContext;
124685 };
124686
124687 #ifndef MAX
124688 # define MAX(x,y) ((x) < (y) ? (y) : (x))
124689 #endif
124690 #ifndef MIN
124691 # define MIN(x,y) ((x) > (y) ? (y) : (x))
124692 #endif
124693
124694 /*
124695 ** Functions to deserialize a 16 bit integer, 32 bit real number and
124696 ** 64 bit integer. The deserialized value is returned.
124697 */
124698 static int readInt16(u8 *p){
124699   return (p[0]<<8) + p[1];
124700 }
124701 static void readCoord(u8 *p, RtreeCoord *pCoord){
124702   u32 i = (
124703     (((u32)p[0]) << 24) + 
124704     (((u32)p[1]) << 16) + 
124705     (((u32)p[2]) <<  8) + 
124706     (((u32)p[3]) <<  0)
124707   );
124708   *(u32 *)pCoord = i;
124709 }
124710 static i64 readInt64(u8 *p){
124711   return (
124712     (((i64)p[0]) << 56) + 
124713     (((i64)p[1]) << 48) + 
124714     (((i64)p[2]) << 40) + 
124715     (((i64)p[3]) << 32) + 
124716     (((i64)p[4]) << 24) + 
124717     (((i64)p[5]) << 16) + 
124718     (((i64)p[6]) <<  8) + 
124719     (((i64)p[7]) <<  0)
124720   );
124721 }
124722
124723 /*
124724 ** Functions to serialize a 16 bit integer, 32 bit real number and
124725 ** 64 bit integer. The value returned is the number of bytes written
124726 ** to the argument buffer (always 2, 4 and 8 respectively).
124727 */
124728 static int writeInt16(u8 *p, int i){
124729   p[0] = (i>> 8)&0xFF;
124730   p[1] = (i>> 0)&0xFF;
124731   return 2;
124732 }
124733 static int writeCoord(u8 *p, RtreeCoord *pCoord){
124734   u32 i;
124735   assert( sizeof(RtreeCoord)==4 );
124736   assert( sizeof(u32)==4 );
124737   i = *(u32 *)pCoord;
124738   p[0] = (i>>24)&0xFF;
124739   p[1] = (i>>16)&0xFF;
124740   p[2] = (i>> 8)&0xFF;
124741   p[3] = (i>> 0)&0xFF;
124742   return 4;
124743 }
124744 static int writeInt64(u8 *p, i64 i){
124745   p[0] = (i>>56)&0xFF;
124746   p[1] = (i>>48)&0xFF;
124747   p[2] = (i>>40)&0xFF;
124748   p[3] = (i>>32)&0xFF;
124749   p[4] = (i>>24)&0xFF;
124750   p[5] = (i>>16)&0xFF;
124751   p[6] = (i>> 8)&0xFF;
124752   p[7] = (i>> 0)&0xFF;
124753   return 8;
124754 }
124755
124756 /*
124757 ** Increment the reference count of node p.
124758 */
124759 static void nodeReference(RtreeNode *p){
124760   if( p ){
124761     p->nRef++;
124762   }
124763 }
124764
124765 /*
124766 ** Clear the content of node p (set all bytes to 0x00).
124767 */
124768 static void nodeZero(Rtree *pRtree, RtreeNode *p){
124769   memset(&p->zData[2], 0, pRtree->iNodeSize-2);
124770   p->isDirty = 1;
124771 }
124772
124773 /*
124774 ** Given a node number iNode, return the corresponding key to use
124775 ** in the Rtree.aHash table.
124776 */
124777 static int nodeHash(i64 iNode){
124778   return (
124779     (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^ 
124780     (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
124781   ) % HASHSIZE;
124782 }
124783
124784 /*
124785 ** Search the node hash table for node iNode. If found, return a pointer
124786 ** to it. Otherwise, return 0.
124787 */
124788 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
124789   RtreeNode *p;
124790   for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
124791   return p;
124792 }
124793
124794 /*
124795 ** Add node pNode to the node hash table.
124796 */
124797 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
124798   int iHash;
124799   assert( pNode->pNext==0 );
124800   iHash = nodeHash(pNode->iNode);
124801   pNode->pNext = pRtree->aHash[iHash];
124802   pRtree->aHash[iHash] = pNode;
124803 }
124804
124805 /*
124806 ** Remove node pNode from the node hash table.
124807 */
124808 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
124809   RtreeNode **pp;
124810   if( pNode->iNode!=0 ){
124811     pp = &pRtree->aHash[nodeHash(pNode->iNode)];
124812     for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
124813     *pp = pNode->pNext;
124814     pNode->pNext = 0;
124815   }
124816 }
124817
124818 /*
124819 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
124820 ** indicating that node has not yet been assigned a node number. It is
124821 ** assigned a node number when nodeWrite() is called to write the
124822 ** node contents out to the database.
124823 */
124824 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
124825   RtreeNode *pNode;
124826   pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
124827   if( pNode ){
124828     memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
124829     pNode->zData = (u8 *)&pNode[1];
124830     pNode->nRef = 1;
124831     pNode->pParent = pParent;
124832     pNode->isDirty = 1;
124833     nodeReference(pParent);
124834   }
124835   return pNode;
124836 }
124837
124838 /*
124839 ** Obtain a reference to an r-tree node.
124840 */
124841 static int
124842 nodeAcquire(
124843   Rtree *pRtree,             /* R-tree structure */
124844   i64 iNode,                 /* Node number to load */
124845   RtreeNode *pParent,        /* Either the parent node or NULL */
124846   RtreeNode **ppNode         /* OUT: Acquired node */
124847 ){
124848   int rc;
124849   int rc2 = SQLITE_OK;
124850   RtreeNode *pNode;
124851
124852   /* Check if the requested node is already in the hash table. If so,
124853   ** increase its reference count and return it.
124854   */
124855   if( (pNode = nodeHashLookup(pRtree, iNode)) ){
124856     assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
124857     if( pParent && !pNode->pParent ){
124858       nodeReference(pParent);
124859       pNode->pParent = pParent;
124860     }
124861     pNode->nRef++;
124862     *ppNode = pNode;
124863     return SQLITE_OK;
124864   }
124865
124866   sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
124867   rc = sqlite3_step(pRtree->pReadNode);
124868   if( rc==SQLITE_ROW ){
124869     const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
124870     if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
124871       pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
124872       if( !pNode ){
124873         rc2 = SQLITE_NOMEM;
124874       }else{
124875         pNode->pParent = pParent;
124876         pNode->zData = (u8 *)&pNode[1];
124877         pNode->nRef = 1;
124878         pNode->iNode = iNode;
124879         pNode->isDirty = 0;
124880         pNode->pNext = 0;
124881         memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
124882         nodeReference(pParent);
124883       }
124884     }
124885   }
124886   rc = sqlite3_reset(pRtree->pReadNode);
124887   if( rc==SQLITE_OK ) rc = rc2;
124888
124889   /* If the root node was just loaded, set pRtree->iDepth to the height
124890   ** of the r-tree structure. A height of zero means all data is stored on
124891   ** the root node. A height of one means the children of the root node
124892   ** are the leaves, and so on. If the depth as specified on the root node
124893   ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
124894   */
124895   if( pNode && iNode==1 ){
124896     pRtree->iDepth = readInt16(pNode->zData);
124897     if( pRtree->iDepth>RTREE_MAX_DEPTH ){
124898       rc = SQLITE_CORRUPT_VTAB;
124899     }
124900   }
124901
124902   /* If no error has occurred so far, check if the "number of entries"
124903   ** field on the node is too large. If so, set the return code to 
124904   ** SQLITE_CORRUPT_VTAB.
124905   */
124906   if( pNode && rc==SQLITE_OK ){
124907     if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
124908       rc = SQLITE_CORRUPT_VTAB;
124909     }
124910   }
124911
124912   if( rc==SQLITE_OK ){
124913     if( pNode!=0 ){
124914       nodeHashInsert(pRtree, pNode);
124915     }else{
124916       rc = SQLITE_CORRUPT_VTAB;
124917     }
124918     *ppNode = pNode;
124919   }else{
124920     sqlite3_free(pNode);
124921     *ppNode = 0;
124922   }
124923
124924   return rc;
124925 }
124926
124927 /*
124928 ** Overwrite cell iCell of node pNode with the contents of pCell.
124929 */
124930 static void nodeOverwriteCell(
124931   Rtree *pRtree, 
124932   RtreeNode *pNode,  
124933   RtreeCell *pCell, 
124934   int iCell
124935 ){
124936   int ii;
124937   u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
124938   p += writeInt64(p, pCell->iRowid);
124939   for(ii=0; ii<(pRtree->nDim*2); ii++){
124940     p += writeCoord(p, &pCell->aCoord[ii]);
124941   }
124942   pNode->isDirty = 1;
124943 }
124944
124945 /*
124946 ** Remove cell the cell with index iCell from node pNode.
124947 */
124948 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
124949   u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
124950   u8 *pSrc = &pDst[pRtree->nBytesPerCell];
124951   int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
124952   memmove(pDst, pSrc, nByte);
124953   writeInt16(&pNode->zData[2], NCELL(pNode)-1);
124954   pNode->isDirty = 1;
124955 }
124956
124957 /*
124958 ** Insert the contents of cell pCell into node pNode. If the insert
124959 ** is successful, return SQLITE_OK.
124960 **
124961 ** If there is not enough free space in pNode, return SQLITE_FULL.
124962 */
124963 static int
124964 nodeInsertCell(
124965   Rtree *pRtree, 
124966   RtreeNode *pNode, 
124967   RtreeCell *pCell 
124968 ){
124969   int nCell;                    /* Current number of cells in pNode */
124970   int nMaxCell;                 /* Maximum number of cells for pNode */
124971
124972   nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
124973   nCell = NCELL(pNode);
124974
124975   assert( nCell<=nMaxCell );
124976   if( nCell<nMaxCell ){
124977     nodeOverwriteCell(pRtree, pNode, pCell, nCell);
124978     writeInt16(&pNode->zData[2], nCell+1);
124979     pNode->isDirty = 1;
124980   }
124981
124982   return (nCell==nMaxCell);
124983 }
124984
124985 /*
124986 ** If the node is dirty, write it out to the database.
124987 */
124988 static int
124989 nodeWrite(Rtree *pRtree, RtreeNode *pNode){
124990   int rc = SQLITE_OK;
124991   if( pNode->isDirty ){
124992     sqlite3_stmt *p = pRtree->pWriteNode;
124993     if( pNode->iNode ){
124994       sqlite3_bind_int64(p, 1, pNode->iNode);
124995     }else{
124996       sqlite3_bind_null(p, 1);
124997     }
124998     sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
124999     sqlite3_step(p);
125000     pNode->isDirty = 0;
125001     rc = sqlite3_reset(p);
125002     if( pNode->iNode==0 && rc==SQLITE_OK ){
125003       pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
125004       nodeHashInsert(pRtree, pNode);
125005     }
125006   }
125007   return rc;
125008 }
125009
125010 /*
125011 ** Release a reference to a node. If the node is dirty and the reference
125012 ** count drops to zero, the node data is written to the database.
125013 */
125014 static int
125015 nodeRelease(Rtree *pRtree, RtreeNode *pNode){
125016   int rc = SQLITE_OK;
125017   if( pNode ){
125018     assert( pNode->nRef>0 );
125019     pNode->nRef--;
125020     if( pNode->nRef==0 ){
125021       if( pNode->iNode==1 ){
125022         pRtree->iDepth = -1;
125023       }
125024       if( pNode->pParent ){
125025         rc = nodeRelease(pRtree, pNode->pParent);
125026       }
125027       if( rc==SQLITE_OK ){
125028         rc = nodeWrite(pRtree, pNode);
125029       }
125030       nodeHashDelete(pRtree, pNode);
125031       sqlite3_free(pNode);
125032     }
125033   }
125034   return rc;
125035 }
125036
125037 /*
125038 ** Return the 64-bit integer value associated with cell iCell of
125039 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
125040 ** an internal node, then the 64-bit integer is a child page number.
125041 */
125042 static i64 nodeGetRowid(
125043   Rtree *pRtree, 
125044   RtreeNode *pNode, 
125045   int iCell
125046 ){
125047   assert( iCell<NCELL(pNode) );
125048   return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
125049 }
125050
125051 /*
125052 ** Return coordinate iCoord from cell iCell in node pNode.
125053 */
125054 static void nodeGetCoord(
125055   Rtree *pRtree, 
125056   RtreeNode *pNode, 
125057   int iCell,
125058   int iCoord,
125059   RtreeCoord *pCoord           /* Space to write result to */
125060 ){
125061   readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
125062 }
125063
125064 /*
125065 ** Deserialize cell iCell of node pNode. Populate the structure pointed
125066 ** to by pCell with the results.
125067 */
125068 static void nodeGetCell(
125069   Rtree *pRtree, 
125070   RtreeNode *pNode, 
125071   int iCell,
125072   RtreeCell *pCell
125073 ){
125074   int ii;
125075   pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
125076   for(ii=0; ii<pRtree->nDim*2; ii++){
125077     nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
125078   }
125079 }
125080
125081
125082 /* Forward declaration for the function that does the work of
125083 ** the virtual table module xCreate() and xConnect() methods.
125084 */
125085 static int rtreeInit(
125086   sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
125087 );
125088
125089 /* 
125090 ** Rtree virtual table module xCreate method.
125091 */
125092 static int rtreeCreate(
125093   sqlite3 *db,
125094   void *pAux,
125095   int argc, const char *const*argv,
125096   sqlite3_vtab **ppVtab,
125097   char **pzErr
125098 ){
125099   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
125100 }
125101
125102 /* 
125103 ** Rtree virtual table module xConnect method.
125104 */
125105 static int rtreeConnect(
125106   sqlite3 *db,
125107   void *pAux,
125108   int argc, const char *const*argv,
125109   sqlite3_vtab **ppVtab,
125110   char **pzErr
125111 ){
125112   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
125113 }
125114
125115 /*
125116 ** Increment the r-tree reference count.
125117 */
125118 static void rtreeReference(Rtree *pRtree){
125119   pRtree->nBusy++;
125120 }
125121
125122 /*
125123 ** Decrement the r-tree reference count. When the reference count reaches
125124 ** zero the structure is deleted.
125125 */
125126 static void rtreeRelease(Rtree *pRtree){
125127   pRtree->nBusy--;
125128   if( pRtree->nBusy==0 ){
125129     sqlite3_finalize(pRtree->pReadNode);
125130     sqlite3_finalize(pRtree->pWriteNode);
125131     sqlite3_finalize(pRtree->pDeleteNode);
125132     sqlite3_finalize(pRtree->pReadRowid);
125133     sqlite3_finalize(pRtree->pWriteRowid);
125134     sqlite3_finalize(pRtree->pDeleteRowid);
125135     sqlite3_finalize(pRtree->pReadParent);
125136     sqlite3_finalize(pRtree->pWriteParent);
125137     sqlite3_finalize(pRtree->pDeleteParent);
125138     sqlite3_free(pRtree);
125139   }
125140 }
125141
125142 /* 
125143 ** Rtree virtual table module xDisconnect method.
125144 */
125145 static int rtreeDisconnect(sqlite3_vtab *pVtab){
125146   rtreeRelease((Rtree *)pVtab);
125147   return SQLITE_OK;
125148 }
125149
125150 /* 
125151 ** Rtree virtual table module xDestroy method.
125152 */
125153 static int rtreeDestroy(sqlite3_vtab *pVtab){
125154   Rtree *pRtree = (Rtree *)pVtab;
125155   int rc;
125156   char *zCreate = sqlite3_mprintf(
125157     "DROP TABLE '%q'.'%q_node';"
125158     "DROP TABLE '%q'.'%q_rowid';"
125159     "DROP TABLE '%q'.'%q_parent';",
125160     pRtree->zDb, pRtree->zName, 
125161     pRtree->zDb, pRtree->zName,
125162     pRtree->zDb, pRtree->zName
125163   );
125164   if( !zCreate ){
125165     rc = SQLITE_NOMEM;
125166   }else{
125167     rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
125168     sqlite3_free(zCreate);
125169   }
125170   if( rc==SQLITE_OK ){
125171     rtreeRelease(pRtree);
125172   }
125173
125174   return rc;
125175 }
125176
125177 /* 
125178 ** Rtree virtual table module xOpen method.
125179 */
125180 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
125181   int rc = SQLITE_NOMEM;
125182   RtreeCursor *pCsr;
125183
125184   pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
125185   if( pCsr ){
125186     memset(pCsr, 0, sizeof(RtreeCursor));
125187     pCsr->base.pVtab = pVTab;
125188     rc = SQLITE_OK;
125189   }
125190   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
125191
125192   return rc;
125193 }
125194
125195
125196 /*
125197 ** Free the RtreeCursor.aConstraint[] array and its contents.
125198 */
125199 static void freeCursorConstraints(RtreeCursor *pCsr){
125200   if( pCsr->aConstraint ){
125201     int i;                        /* Used to iterate through constraint array */
125202     for(i=0; i<pCsr->nConstraint; i++){
125203       sqlite3_rtree_geometry *pGeom = pCsr->aConstraint[i].pGeom;
125204       if( pGeom ){
125205         if( pGeom->xDelUser ) pGeom->xDelUser(pGeom->pUser);
125206         sqlite3_free(pGeom);
125207       }
125208     }
125209     sqlite3_free(pCsr->aConstraint);
125210     pCsr->aConstraint = 0;
125211   }
125212 }
125213
125214 /* 
125215 ** Rtree virtual table module xClose method.
125216 */
125217 static int rtreeClose(sqlite3_vtab_cursor *cur){
125218   Rtree *pRtree = (Rtree *)(cur->pVtab);
125219   int rc;
125220   RtreeCursor *pCsr = (RtreeCursor *)cur;
125221   freeCursorConstraints(pCsr);
125222   rc = nodeRelease(pRtree, pCsr->pNode);
125223   sqlite3_free(pCsr);
125224   return rc;
125225 }
125226
125227 /*
125228 ** Rtree virtual table module xEof method.
125229 **
125230 ** Return non-zero if the cursor does not currently point to a valid 
125231 ** record (i.e if the scan has finished), or zero otherwise.
125232 */
125233 static int rtreeEof(sqlite3_vtab_cursor *cur){
125234   RtreeCursor *pCsr = (RtreeCursor *)cur;
125235   return (pCsr->pNode==0);
125236 }
125237
125238 /*
125239 ** The r-tree constraint passed as the second argument to this function is
125240 ** guaranteed to be a MATCH constraint.
125241 */
125242 static int testRtreeGeom(
125243   Rtree *pRtree,                  /* R-Tree object */
125244   RtreeConstraint *pConstraint,   /* MATCH constraint to test */
125245   RtreeCell *pCell,               /* Cell to test */
125246   int *pbRes                      /* OUT: Test result */
125247 ){
125248   int i;
125249   double aCoord[RTREE_MAX_DIMENSIONS*2];
125250   int nCoord = pRtree->nDim*2;
125251
125252   assert( pConstraint->op==RTREE_MATCH );
125253   assert( pConstraint->pGeom );
125254
125255   for(i=0; i<nCoord; i++){
125256     aCoord[i] = DCOORD(pCell->aCoord[i]);
125257   }
125258   return pConstraint->xGeom(pConstraint->pGeom, nCoord, aCoord, pbRes);
125259 }
125260
125261 /* 
125262 ** Cursor pCursor currently points to a cell in a non-leaf page.
125263 ** Set *pbEof to true if the sub-tree headed by the cell is filtered
125264 ** (excluded) by the constraints in the pCursor->aConstraint[] 
125265 ** array, or false otherwise.
125266 **
125267 ** Return SQLITE_OK if successful or an SQLite error code if an error
125268 ** occurs within a geometry callback.
125269 */
125270 static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
125271   RtreeCell cell;
125272   int ii;
125273   int bRes = 0;
125274   int rc = SQLITE_OK;
125275
125276   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
125277   for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
125278     RtreeConstraint *p = &pCursor->aConstraint[ii];
125279     double cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
125280     double cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
125281
125282     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
125283         || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
125284     );
125285
125286     switch( p->op ){
125287       case RTREE_LE: case RTREE_LT: 
125288         bRes = p->rValue<cell_min; 
125289         break;
125290
125291       case RTREE_GE: case RTREE_GT: 
125292         bRes = p->rValue>cell_max; 
125293         break;
125294
125295       case RTREE_EQ:
125296         bRes = (p->rValue>cell_max || p->rValue<cell_min);
125297         break;
125298
125299       default: {
125300         assert( p->op==RTREE_MATCH );
125301         rc = testRtreeGeom(pRtree, p, &cell, &bRes);
125302         bRes = !bRes;
125303         break;
125304       }
125305     }
125306   }
125307
125308   *pbEof = bRes;
125309   return rc;
125310 }
125311
125312 /* 
125313 ** Test if the cell that cursor pCursor currently points to
125314 ** would be filtered (excluded) by the constraints in the 
125315 ** pCursor->aConstraint[] array. If so, set *pbEof to true before
125316 ** returning. If the cell is not filtered (excluded) by the constraints,
125317 ** set pbEof to zero.
125318 **
125319 ** Return SQLITE_OK if successful or an SQLite error code if an error
125320 ** occurs within a geometry callback.
125321 **
125322 ** This function assumes that the cell is part of a leaf node.
125323 */
125324 static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
125325   RtreeCell cell;
125326   int ii;
125327   *pbEof = 0;
125328
125329   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
125330   for(ii=0; ii<pCursor->nConstraint; ii++){
125331     RtreeConstraint *p = &pCursor->aConstraint[ii];
125332     double coord = DCOORD(cell.aCoord[p->iCoord]);
125333     int res;
125334     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
125335         || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
125336     );
125337     switch( p->op ){
125338       case RTREE_LE: res = (coord<=p->rValue); break;
125339       case RTREE_LT: res = (coord<p->rValue);  break;
125340       case RTREE_GE: res = (coord>=p->rValue); break;
125341       case RTREE_GT: res = (coord>p->rValue);  break;
125342       case RTREE_EQ: res = (coord==p->rValue); break;
125343       default: {
125344         int rc;
125345         assert( p->op==RTREE_MATCH );
125346         rc = testRtreeGeom(pRtree, p, &cell, &res);
125347         if( rc!=SQLITE_OK ){
125348           return rc;
125349         }
125350         break;
125351       }
125352     }
125353
125354     if( !res ){
125355       *pbEof = 1;
125356       return SQLITE_OK;
125357     }
125358   }
125359
125360   return SQLITE_OK;
125361 }
125362
125363 /*
125364 ** Cursor pCursor currently points at a node that heads a sub-tree of
125365 ** height iHeight (if iHeight==0, then the node is a leaf). Descend
125366 ** to point to the left-most cell of the sub-tree that matches the 
125367 ** configured constraints.
125368 */
125369 static int descendToCell(
125370   Rtree *pRtree, 
125371   RtreeCursor *pCursor, 
125372   int iHeight,
125373   int *pEof                 /* OUT: Set to true if cannot descend */
125374 ){
125375   int isEof;
125376   int rc;
125377   int ii;
125378   RtreeNode *pChild;
125379   sqlite3_int64 iRowid;
125380
125381   RtreeNode *pSavedNode = pCursor->pNode;
125382   int iSavedCell = pCursor->iCell;
125383
125384   assert( iHeight>=0 );
125385
125386   if( iHeight==0 ){
125387     rc = testRtreeEntry(pRtree, pCursor, &isEof);
125388   }else{
125389     rc = testRtreeCell(pRtree, pCursor, &isEof);
125390   }
125391   if( rc!=SQLITE_OK || isEof || iHeight==0 ){
125392     goto descend_to_cell_out;
125393   }
125394
125395   iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
125396   rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
125397   if( rc!=SQLITE_OK ){
125398     goto descend_to_cell_out;
125399   }
125400
125401   nodeRelease(pRtree, pCursor->pNode);
125402   pCursor->pNode = pChild;
125403   isEof = 1;
125404   for(ii=0; isEof && ii<NCELL(pChild); ii++){
125405     pCursor->iCell = ii;
125406     rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
125407     if( rc!=SQLITE_OK ){
125408       goto descend_to_cell_out;
125409     }
125410   }
125411
125412   if( isEof ){
125413     assert( pCursor->pNode==pChild );
125414     nodeReference(pSavedNode);
125415     nodeRelease(pRtree, pChild);
125416     pCursor->pNode = pSavedNode;
125417     pCursor->iCell = iSavedCell;
125418   }
125419
125420 descend_to_cell_out:
125421   *pEof = isEof;
125422   return rc;
125423 }
125424
125425 /*
125426 ** One of the cells in node pNode is guaranteed to have a 64-bit 
125427 ** integer value equal to iRowid. Return the index of this cell.
125428 */
125429 static int nodeRowidIndex(
125430   Rtree *pRtree, 
125431   RtreeNode *pNode, 
125432   i64 iRowid,
125433   int *piIndex
125434 ){
125435   int ii;
125436   int nCell = NCELL(pNode);
125437   for(ii=0; ii<nCell; ii++){
125438     if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
125439       *piIndex = ii;
125440       return SQLITE_OK;
125441     }
125442   }
125443   return SQLITE_CORRUPT_VTAB;
125444 }
125445
125446 /*
125447 ** Return the index of the cell containing a pointer to node pNode
125448 ** in its parent. If pNode is the root node, return -1.
125449 */
125450 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
125451   RtreeNode *pParent = pNode->pParent;
125452   if( pParent ){
125453     return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
125454   }
125455   *piIndex = -1;
125456   return SQLITE_OK;
125457 }
125458
125459 /* 
125460 ** Rtree virtual table module xNext method.
125461 */
125462 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
125463   Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
125464   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
125465   int rc = SQLITE_OK;
125466
125467   /* RtreeCursor.pNode must not be NULL. If is is NULL, then this cursor is
125468   ** already at EOF. It is against the rules to call the xNext() method of
125469   ** a cursor that has already reached EOF.
125470   */
125471   assert( pCsr->pNode );
125472
125473   if( pCsr->iStrategy==1 ){
125474     /* This "scan" is a direct lookup by rowid. There is no next entry. */
125475     nodeRelease(pRtree, pCsr->pNode);
125476     pCsr->pNode = 0;
125477   }else{
125478     /* Move to the next entry that matches the configured constraints. */
125479     int iHeight = 0;
125480     while( pCsr->pNode ){
125481       RtreeNode *pNode = pCsr->pNode;
125482       int nCell = NCELL(pNode);
125483       for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
125484         int isEof;
125485         rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
125486         if( rc!=SQLITE_OK || !isEof ){
125487           return rc;
125488         }
125489       }
125490       pCsr->pNode = pNode->pParent;
125491       rc = nodeParentIndex(pRtree, pNode, &pCsr->iCell);
125492       if( rc!=SQLITE_OK ){
125493         return rc;
125494       }
125495       nodeReference(pCsr->pNode);
125496       nodeRelease(pRtree, pNode);
125497       iHeight++;
125498     }
125499   }
125500
125501   return rc;
125502 }
125503
125504 /* 
125505 ** Rtree virtual table module xRowid method.
125506 */
125507 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
125508   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
125509   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
125510
125511   assert(pCsr->pNode);
125512   *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
125513
125514   return SQLITE_OK;
125515 }
125516
125517 /* 
125518 ** Rtree virtual table module xColumn method.
125519 */
125520 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
125521   Rtree *pRtree = (Rtree *)cur->pVtab;
125522   RtreeCursor *pCsr = (RtreeCursor *)cur;
125523
125524   if( i==0 ){
125525     i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
125526     sqlite3_result_int64(ctx, iRowid);
125527   }else{
125528     RtreeCoord c;
125529     nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
125530     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
125531       sqlite3_result_double(ctx, c.f);
125532     }else{
125533       assert( pRtree->eCoordType==RTREE_COORD_INT32 );
125534       sqlite3_result_int(ctx, c.i);
125535     }
125536   }
125537
125538   return SQLITE_OK;
125539 }
125540
125541 /* 
125542 ** Use nodeAcquire() to obtain the leaf node containing the record with 
125543 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
125544 ** return SQLITE_OK. If there is no such record in the table, set
125545 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
125546 ** to zero and return an SQLite error code.
125547 */
125548 static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
125549   int rc;
125550   *ppLeaf = 0;
125551   sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
125552   if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
125553     i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
125554     rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
125555     sqlite3_reset(pRtree->pReadRowid);
125556   }else{
125557     rc = sqlite3_reset(pRtree->pReadRowid);
125558   }
125559   return rc;
125560 }
125561
125562 /*
125563 ** This function is called to configure the RtreeConstraint object passed
125564 ** as the second argument for a MATCH constraint. The value passed as the
125565 ** first argument to this function is the right-hand operand to the MATCH
125566 ** operator.
125567 */
125568 static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
125569   RtreeMatchArg *p;
125570   sqlite3_rtree_geometry *pGeom;
125571   int nBlob;
125572
125573   /* Check that value is actually a blob. */
125574   if( !sqlite3_value_type(pValue)==SQLITE_BLOB ) return SQLITE_ERROR;
125575
125576   /* Check that the blob is roughly the right size. */
125577   nBlob = sqlite3_value_bytes(pValue);
125578   if( nBlob<(int)sizeof(RtreeMatchArg) 
125579    || ((nBlob-sizeof(RtreeMatchArg))%sizeof(double))!=0
125580   ){
125581     return SQLITE_ERROR;
125582   }
125583
125584   pGeom = (sqlite3_rtree_geometry *)sqlite3_malloc(
125585       sizeof(sqlite3_rtree_geometry) + nBlob
125586   );
125587   if( !pGeom ) return SQLITE_NOMEM;
125588   memset(pGeom, 0, sizeof(sqlite3_rtree_geometry));
125589   p = (RtreeMatchArg *)&pGeom[1];
125590
125591   memcpy(p, sqlite3_value_blob(pValue), nBlob);
125592   if( p->magic!=RTREE_GEOMETRY_MAGIC 
125593    || nBlob!=(int)(sizeof(RtreeMatchArg) + (p->nParam-1)*sizeof(double))
125594   ){
125595     sqlite3_free(pGeom);
125596     return SQLITE_ERROR;
125597   }
125598
125599   pGeom->pContext = p->pContext;
125600   pGeom->nParam = p->nParam;
125601   pGeom->aParam = p->aParam;
125602
125603   pCons->xGeom = p->xGeom;
125604   pCons->pGeom = pGeom;
125605   return SQLITE_OK;
125606 }
125607
125608 /* 
125609 ** Rtree virtual table module xFilter method.
125610 */
125611 static int rtreeFilter(
125612   sqlite3_vtab_cursor *pVtabCursor, 
125613   int idxNum, const char *idxStr,
125614   int argc, sqlite3_value **argv
125615 ){
125616   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
125617   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
125618
125619   RtreeNode *pRoot = 0;
125620   int ii;
125621   int rc = SQLITE_OK;
125622
125623   rtreeReference(pRtree);
125624
125625   freeCursorConstraints(pCsr);
125626   pCsr->iStrategy = idxNum;
125627
125628   if( idxNum==1 ){
125629     /* Special case - lookup by rowid. */
125630     RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
125631     i64 iRowid = sqlite3_value_int64(argv[0]);
125632     rc = findLeafNode(pRtree, iRowid, &pLeaf);
125633     pCsr->pNode = pLeaf; 
125634     if( pLeaf ){
125635       assert( rc==SQLITE_OK );
125636       rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &pCsr->iCell);
125637     }
125638   }else{
125639     /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array 
125640     ** with the configured constraints. 
125641     */
125642     if( argc>0 ){
125643       pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
125644       pCsr->nConstraint = argc;
125645       if( !pCsr->aConstraint ){
125646         rc = SQLITE_NOMEM;
125647       }else{
125648         memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
125649         assert( (idxStr==0 && argc==0) || (int)strlen(idxStr)==argc*2 );
125650         for(ii=0; ii<argc; ii++){
125651           RtreeConstraint *p = &pCsr->aConstraint[ii];
125652           p->op = idxStr[ii*2];
125653           p->iCoord = idxStr[ii*2+1]-'a';
125654           if( p->op==RTREE_MATCH ){
125655             /* A MATCH operator. The right-hand-side must be a blob that
125656             ** can be cast into an RtreeMatchArg object. One created using
125657             ** an sqlite3_rtree_geometry_callback() SQL user function.
125658             */
125659             rc = deserializeGeometry(argv[ii], p);
125660             if( rc!=SQLITE_OK ){
125661               break;
125662             }
125663           }else{
125664             p->rValue = sqlite3_value_double(argv[ii]);
125665           }
125666         }
125667       }
125668     }
125669   
125670     if( rc==SQLITE_OK ){
125671       pCsr->pNode = 0;
125672       rc = nodeAcquire(pRtree, 1, 0, &pRoot);
125673     }
125674     if( rc==SQLITE_OK ){
125675       int isEof = 1;
125676       int nCell = NCELL(pRoot);
125677       pCsr->pNode = pRoot;
125678       for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
125679         assert( pCsr->pNode==pRoot );
125680         rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
125681         if( !isEof ){
125682           break;
125683         }
125684       }
125685       if( rc==SQLITE_OK && isEof ){
125686         assert( pCsr->pNode==pRoot );
125687         nodeRelease(pRtree, pRoot);
125688         pCsr->pNode = 0;
125689       }
125690       assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
125691     }
125692   }
125693
125694   rtreeRelease(pRtree);
125695   return rc;
125696 }
125697
125698 /*
125699 ** Rtree virtual table module xBestIndex method. There are three
125700 ** table scan strategies to choose from (in order from most to 
125701 ** least desirable):
125702 **
125703 **   idxNum     idxStr        Strategy
125704 **   ------------------------------------------------
125705 **     1        Unused        Direct lookup by rowid.
125706 **     2        See below     R-tree query or full-table scan.
125707 **   ------------------------------------------------
125708 **
125709 ** If strategy 1 is used, then idxStr is not meaningful. If strategy
125710 ** 2 is used, idxStr is formatted to contain 2 bytes for each 
125711 ** constraint used. The first two bytes of idxStr correspond to 
125712 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
125713 ** (argvIndex==1) etc.
125714 **
125715 ** The first of each pair of bytes in idxStr identifies the constraint
125716 ** operator as follows:
125717 **
125718 **   Operator    Byte Value
125719 **   ----------------------
125720 **      =        0x41 ('A')
125721 **     <=        0x42 ('B')
125722 **      <        0x43 ('C')
125723 **     >=        0x44 ('D')
125724 **      >        0x45 ('E')
125725 **   MATCH       0x46 ('F')
125726 **   ----------------------
125727 **
125728 ** The second of each pair of bytes identifies the coordinate column
125729 ** to which the constraint applies. The leftmost coordinate column
125730 ** is 'a', the second from the left 'b' etc.
125731 */
125732 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
125733   int rc = SQLITE_OK;
125734   int ii;
125735
125736   int iIdx = 0;
125737   char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
125738   memset(zIdxStr, 0, sizeof(zIdxStr));
125739   UNUSED_PARAMETER(tab);
125740
125741   assert( pIdxInfo->idxStr==0 );
125742   for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
125743     struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
125744
125745     if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
125746       /* We have an equality constraint on the rowid. Use strategy 1. */
125747       int jj;
125748       for(jj=0; jj<ii; jj++){
125749         pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
125750         pIdxInfo->aConstraintUsage[jj].omit = 0;
125751       }
125752       pIdxInfo->idxNum = 1;
125753       pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
125754       pIdxInfo->aConstraintUsage[jj].omit = 1;
125755
125756       /* This strategy involves a two rowid lookups on an B-Tree structures
125757       ** and then a linear search of an R-Tree node. This should be 
125758       ** considered almost as quick as a direct rowid lookup (for which 
125759       ** sqlite uses an internal cost of 0.0).
125760       */ 
125761       pIdxInfo->estimatedCost = 10.0;
125762       return SQLITE_OK;
125763     }
125764
125765     if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
125766       u8 op;
125767       switch( p->op ){
125768         case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
125769         case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
125770         case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
125771         case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
125772         case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
125773         default:
125774           assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
125775           op = RTREE_MATCH; 
125776           break;
125777       }
125778       zIdxStr[iIdx++] = op;
125779       zIdxStr[iIdx++] = p->iColumn - 1 + 'a';
125780       pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
125781       pIdxInfo->aConstraintUsage[ii].omit = 1;
125782     }
125783   }
125784
125785   pIdxInfo->idxNum = 2;
125786   pIdxInfo->needToFreeIdxStr = 1;
125787   if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
125788     return SQLITE_NOMEM;
125789   }
125790   assert( iIdx>=0 );
125791   pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
125792   return rc;
125793 }
125794
125795 /*
125796 ** Return the N-dimensional volumn of the cell stored in *p.
125797 */
125798 static float cellArea(Rtree *pRtree, RtreeCell *p){
125799   float area = 1.0;
125800   int ii;
125801   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
125802     area = (float)(area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
125803   }
125804   return area;
125805 }
125806
125807 /*
125808 ** Return the margin length of cell p. The margin length is the sum
125809 ** of the objects size in each dimension.
125810 */
125811 static float cellMargin(Rtree *pRtree, RtreeCell *p){
125812   float margin = 0.0;
125813   int ii;
125814   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
125815     margin += (float)(DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
125816   }
125817   return margin;
125818 }
125819
125820 /*
125821 ** Store the union of cells p1 and p2 in p1.
125822 */
125823 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
125824   int ii;
125825   if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
125826     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
125827       p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
125828       p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
125829     }
125830   }else{
125831     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
125832       p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
125833       p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
125834     }
125835   }
125836 }
125837
125838 /*
125839 ** Return true if the area covered by p2 is a subset of the area covered
125840 ** by p1. False otherwise.
125841 */
125842 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
125843   int ii;
125844   int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
125845   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
125846     RtreeCoord *a1 = &p1->aCoord[ii];
125847     RtreeCoord *a2 = &p2->aCoord[ii];
125848     if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f)) 
125849      || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i)) 
125850     ){
125851       return 0;
125852     }
125853   }
125854   return 1;
125855 }
125856
125857 /*
125858 ** Return the amount cell p would grow by if it were unioned with pCell.
125859 */
125860 static float cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
125861   float area;
125862   RtreeCell cell;
125863   memcpy(&cell, p, sizeof(RtreeCell));
125864   area = cellArea(pRtree, &cell);
125865   cellUnion(pRtree, &cell, pCell);
125866   return (cellArea(pRtree, &cell)-area);
125867 }
125868
125869 #if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
125870 static float cellOverlap(
125871   Rtree *pRtree, 
125872   RtreeCell *p, 
125873   RtreeCell *aCell, 
125874   int nCell, 
125875   int iExclude
125876 ){
125877   int ii;
125878   float overlap = 0.0;
125879   for(ii=0; ii<nCell; ii++){
125880 #if VARIANT_RSTARTREE_CHOOSESUBTREE
125881     if( ii!=iExclude )
125882 #else
125883     assert( iExclude==-1 );
125884     UNUSED_PARAMETER(iExclude);
125885 #endif
125886     {
125887       int jj;
125888       float o = 1.0;
125889       for(jj=0; jj<(pRtree->nDim*2); jj+=2){
125890         double x1;
125891         double x2;
125892
125893         x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
125894         x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
125895
125896         if( x2<x1 ){
125897           o = 0.0;
125898           break;
125899         }else{
125900           o = o * (float)(x2-x1);
125901         }
125902       }
125903       overlap += o;
125904     }
125905   }
125906   return overlap;
125907 }
125908 #endif
125909
125910 #if VARIANT_RSTARTREE_CHOOSESUBTREE
125911 static float cellOverlapEnlargement(
125912   Rtree *pRtree, 
125913   RtreeCell *p, 
125914   RtreeCell *pInsert, 
125915   RtreeCell *aCell, 
125916   int nCell, 
125917   int iExclude
125918 ){
125919   double before;
125920   double after;
125921   before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
125922   cellUnion(pRtree, p, pInsert);
125923   after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
125924   return (float)(after-before);
125925 }
125926 #endif
125927
125928
125929 /*
125930 ** This function implements the ChooseLeaf algorithm from Gutman[84].
125931 ** ChooseSubTree in r*tree terminology.
125932 */
125933 static int ChooseLeaf(
125934   Rtree *pRtree,               /* Rtree table */
125935   RtreeCell *pCell,            /* Cell to insert into rtree */
125936   int iHeight,                 /* Height of sub-tree rooted at pCell */
125937   RtreeNode **ppLeaf           /* OUT: Selected leaf page */
125938 ){
125939   int rc;
125940   int ii;
125941   RtreeNode *pNode;
125942   rc = nodeAcquire(pRtree, 1, 0, &pNode);
125943
125944   for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
125945     int iCell;
125946     sqlite3_int64 iBest = 0;
125947
125948     float fMinGrowth = 0.0;
125949     float fMinArea = 0.0;
125950     float fMinOverlap = 0.0;
125951
125952     int nCell = NCELL(pNode);
125953     RtreeCell cell;
125954     RtreeNode *pChild;
125955
125956     RtreeCell *aCell = 0;
125957
125958 #if VARIANT_RSTARTREE_CHOOSESUBTREE
125959     if( ii==(pRtree->iDepth-1) ){
125960       int jj;
125961       aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
125962       if( !aCell ){
125963         rc = SQLITE_NOMEM;
125964         nodeRelease(pRtree, pNode);
125965         pNode = 0;
125966         continue;
125967       }
125968       for(jj=0; jj<nCell; jj++){
125969         nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
125970       }
125971     }
125972 #endif
125973
125974     /* Select the child node which will be enlarged the least if pCell
125975     ** is inserted into it. Resolve ties by choosing the entry with
125976     ** the smallest area.
125977     */
125978     for(iCell=0; iCell<nCell; iCell++){
125979       int bBest = 0;
125980       float growth;
125981       float area;
125982       float overlap = 0.0;
125983       nodeGetCell(pRtree, pNode, iCell, &cell);
125984       growth = cellGrowth(pRtree, &cell, pCell);
125985       area = cellArea(pRtree, &cell);
125986
125987 #if VARIANT_RSTARTREE_CHOOSESUBTREE
125988       if( ii==(pRtree->iDepth-1) ){
125989         overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
125990       }
125991       if( (iCell==0) 
125992        || (overlap<fMinOverlap) 
125993        || (overlap==fMinOverlap && growth<fMinGrowth)
125994        || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
125995       ){
125996         bBest = 1;
125997       }
125998 #else
125999       if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
126000         bBest = 1;
126001       }
126002 #endif
126003       if( bBest ){
126004         fMinOverlap = overlap;
126005         fMinGrowth = growth;
126006         fMinArea = area;
126007         iBest = cell.iRowid;
126008       }
126009     }
126010
126011     sqlite3_free(aCell);
126012     rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
126013     nodeRelease(pRtree, pNode);
126014     pNode = pChild;
126015   }
126016
126017   *ppLeaf = pNode;
126018   return rc;
126019 }
126020
126021 /*
126022 ** A cell with the same content as pCell has just been inserted into
126023 ** the node pNode. This function updates the bounding box cells in
126024 ** all ancestor elements.
126025 */
126026 static int AdjustTree(
126027   Rtree *pRtree,                    /* Rtree table */
126028   RtreeNode *pNode,                 /* Adjust ancestry of this node. */
126029   RtreeCell *pCell                  /* This cell was just inserted */
126030 ){
126031   RtreeNode *p = pNode;
126032   while( p->pParent ){
126033     RtreeNode *pParent = p->pParent;
126034     RtreeCell cell;
126035     int iCell;
126036
126037     if( nodeParentIndex(pRtree, p, &iCell) ){
126038       return SQLITE_CORRUPT_VTAB;
126039     }
126040
126041     nodeGetCell(pRtree, pParent, iCell, &cell);
126042     if( !cellContains(pRtree, &cell, pCell) ){
126043       cellUnion(pRtree, &cell, pCell);
126044       nodeOverwriteCell(pRtree, pParent, &cell, iCell);
126045     }
126046  
126047     p = pParent;
126048   }
126049   return SQLITE_OK;
126050 }
126051
126052 /*
126053 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
126054 */
126055 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
126056   sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
126057   sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
126058   sqlite3_step(pRtree->pWriteRowid);
126059   return sqlite3_reset(pRtree->pWriteRowid);
126060 }
126061
126062 /*
126063 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
126064 */
126065 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
126066   sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
126067   sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
126068   sqlite3_step(pRtree->pWriteParent);
126069   return sqlite3_reset(pRtree->pWriteParent);
126070 }
126071
126072 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
126073
126074 #if VARIANT_GUTTMAN_LINEAR_SPLIT
126075 /*
126076 ** Implementation of the linear variant of the PickNext() function from
126077 ** Guttman[84].
126078 */
126079 static RtreeCell *LinearPickNext(
126080   Rtree *pRtree,
126081   RtreeCell *aCell, 
126082   int nCell, 
126083   RtreeCell *pLeftBox, 
126084   RtreeCell *pRightBox,
126085   int *aiUsed
126086 ){
126087   int ii;
126088   for(ii=0; aiUsed[ii]; ii++);
126089   aiUsed[ii] = 1;
126090   return &aCell[ii];
126091 }
126092
126093 /*
126094 ** Implementation of the linear variant of the PickSeeds() function from
126095 ** Guttman[84].
126096 */
126097 static void LinearPickSeeds(
126098   Rtree *pRtree,
126099   RtreeCell *aCell, 
126100   int nCell, 
126101   int *piLeftSeed, 
126102   int *piRightSeed
126103 ){
126104   int i;
126105   int iLeftSeed = 0;
126106   int iRightSeed = 1;
126107   float maxNormalInnerWidth = 0.0;
126108
126109   /* Pick two "seed" cells from the array of cells. The algorithm used
126110   ** here is the LinearPickSeeds algorithm from Gutman[1984]. The 
126111   ** indices of the two seed cells in the array are stored in local
126112   ** variables iLeftSeek and iRightSeed.
126113   */
126114   for(i=0; i<pRtree->nDim; i++){
126115     float x1 = DCOORD(aCell[0].aCoord[i*2]);
126116     float x2 = DCOORD(aCell[0].aCoord[i*2+1]);
126117     float x3 = x1;
126118     float x4 = x2;
126119     int jj;
126120
126121     int iCellLeft = 0;
126122     int iCellRight = 0;
126123
126124     for(jj=1; jj<nCell; jj++){
126125       float left = DCOORD(aCell[jj].aCoord[i*2]);
126126       float right = DCOORD(aCell[jj].aCoord[i*2+1]);
126127
126128       if( left<x1 ) x1 = left;
126129       if( right>x4 ) x4 = right;
126130       if( left>x3 ){
126131         x3 = left;
126132         iCellRight = jj;
126133       }
126134       if( right<x2 ){
126135         x2 = right;
126136         iCellLeft = jj;
126137       }
126138     }
126139
126140     if( x4!=x1 ){
126141       float normalwidth = (x3 - x2) / (x4 - x1);
126142       if( normalwidth>maxNormalInnerWidth ){
126143         iLeftSeed = iCellLeft;
126144         iRightSeed = iCellRight;
126145       }
126146     }
126147   }
126148
126149   *piLeftSeed = iLeftSeed;
126150   *piRightSeed = iRightSeed;
126151 }
126152 #endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
126153
126154 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
126155 /*
126156 ** Implementation of the quadratic variant of the PickNext() function from
126157 ** Guttman[84].
126158 */
126159 static RtreeCell *QuadraticPickNext(
126160   Rtree *pRtree,
126161   RtreeCell *aCell, 
126162   int nCell, 
126163   RtreeCell *pLeftBox, 
126164   RtreeCell *pRightBox,
126165   int *aiUsed
126166 ){
126167   #define FABS(a) ((a)<0.0?-1.0*(a):(a))
126168
126169   int iSelect = -1;
126170   float fDiff;
126171   int ii;
126172   for(ii=0; ii<nCell; ii++){
126173     if( aiUsed[ii]==0 ){
126174       float left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
126175       float right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
126176       float diff = FABS(right-left);
126177       if( iSelect<0 || diff>fDiff ){
126178         fDiff = diff;
126179         iSelect = ii;
126180       }
126181     }
126182   }
126183   aiUsed[iSelect] = 1;
126184   return &aCell[iSelect];
126185 }
126186
126187 /*
126188 ** Implementation of the quadratic variant of the PickSeeds() function from
126189 ** Guttman[84].
126190 */
126191 static void QuadraticPickSeeds(
126192   Rtree *pRtree,
126193   RtreeCell *aCell, 
126194   int nCell, 
126195   int *piLeftSeed, 
126196   int *piRightSeed
126197 ){
126198   int ii;
126199   int jj;
126200
126201   int iLeftSeed = 0;
126202   int iRightSeed = 1;
126203   float fWaste = 0.0;
126204
126205   for(ii=0; ii<nCell; ii++){
126206     for(jj=ii+1; jj<nCell; jj++){
126207       float right = cellArea(pRtree, &aCell[jj]);
126208       float growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
126209       float waste = growth - right;
126210
126211       if( waste>fWaste ){
126212         iLeftSeed = ii;
126213         iRightSeed = jj;
126214         fWaste = waste;
126215       }
126216     }
126217   }
126218
126219   *piLeftSeed = iLeftSeed;
126220   *piRightSeed = iRightSeed;
126221 }
126222 #endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
126223
126224 /*
126225 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
126226 ** nIdx. The aIdx array contains the set of integers from 0 to 
126227 ** (nIdx-1) in no particular order. This function sorts the values
126228 ** in aIdx according to the indexed values in aDistance. For
126229 ** example, assuming the inputs:
126230 **
126231 **   aIdx      = { 0,   1,   2,   3 }
126232 **   aDistance = { 5.0, 2.0, 7.0, 6.0 }
126233 **
126234 ** this function sets the aIdx array to contain:
126235 **
126236 **   aIdx      = { 0,   1,   2,   3 }
126237 **
126238 ** The aSpare array is used as temporary working space by the
126239 ** sorting algorithm.
126240 */
126241 static void SortByDistance(
126242   int *aIdx, 
126243   int nIdx, 
126244   float *aDistance, 
126245   int *aSpare
126246 ){
126247   if( nIdx>1 ){
126248     int iLeft = 0;
126249     int iRight = 0;
126250
126251     int nLeft = nIdx/2;
126252     int nRight = nIdx-nLeft;
126253     int *aLeft = aIdx;
126254     int *aRight = &aIdx[nLeft];
126255
126256     SortByDistance(aLeft, nLeft, aDistance, aSpare);
126257     SortByDistance(aRight, nRight, aDistance, aSpare);
126258
126259     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
126260     aLeft = aSpare;
126261
126262     while( iLeft<nLeft || iRight<nRight ){
126263       if( iLeft==nLeft ){
126264         aIdx[iLeft+iRight] = aRight[iRight];
126265         iRight++;
126266       }else if( iRight==nRight ){
126267         aIdx[iLeft+iRight] = aLeft[iLeft];
126268         iLeft++;
126269       }else{
126270         float fLeft = aDistance[aLeft[iLeft]];
126271         float fRight = aDistance[aRight[iRight]];
126272         if( fLeft<fRight ){
126273           aIdx[iLeft+iRight] = aLeft[iLeft];
126274           iLeft++;
126275         }else{
126276           aIdx[iLeft+iRight] = aRight[iRight];
126277           iRight++;
126278         }
126279       }
126280     }
126281
126282 #if 0
126283     /* Check that the sort worked */
126284     {
126285       int jj;
126286       for(jj=1; jj<nIdx; jj++){
126287         float left = aDistance[aIdx[jj-1]];
126288         float right = aDistance[aIdx[jj]];
126289         assert( left<=right );
126290       }
126291     }
126292 #endif
126293   }
126294 }
126295
126296 /*
126297 ** Arguments aIdx, aCell and aSpare all point to arrays of size
126298 ** nIdx. The aIdx array contains the set of integers from 0 to 
126299 ** (nIdx-1) in no particular order. This function sorts the values
126300 ** in aIdx according to dimension iDim of the cells in aCell. The
126301 ** minimum value of dimension iDim is considered first, the
126302 ** maximum used to break ties.
126303 **
126304 ** The aSpare array is used as temporary working space by the
126305 ** sorting algorithm.
126306 */
126307 static void SortByDimension(
126308   Rtree *pRtree,
126309   int *aIdx, 
126310   int nIdx, 
126311   int iDim, 
126312   RtreeCell *aCell, 
126313   int *aSpare
126314 ){
126315   if( nIdx>1 ){
126316
126317     int iLeft = 0;
126318     int iRight = 0;
126319
126320     int nLeft = nIdx/2;
126321     int nRight = nIdx-nLeft;
126322     int *aLeft = aIdx;
126323     int *aRight = &aIdx[nLeft];
126324
126325     SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
126326     SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
126327
126328     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
126329     aLeft = aSpare;
126330     while( iLeft<nLeft || iRight<nRight ){
126331       double xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
126332       double xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
126333       double xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
126334       double xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
126335       if( (iLeft!=nLeft) && ((iRight==nRight)
126336        || (xleft1<xright1)
126337        || (xleft1==xright1 && xleft2<xright2)
126338       )){
126339         aIdx[iLeft+iRight] = aLeft[iLeft];
126340         iLeft++;
126341       }else{
126342         aIdx[iLeft+iRight] = aRight[iRight];
126343         iRight++;
126344       }
126345     }
126346
126347 #if 0
126348     /* Check that the sort worked */
126349     {
126350       int jj;
126351       for(jj=1; jj<nIdx; jj++){
126352         float xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
126353         float xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
126354         float xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
126355         float xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
126356         assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
126357       }
126358     }
126359 #endif
126360   }
126361 }
126362
126363 #if VARIANT_RSTARTREE_SPLIT
126364 /*
126365 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
126366 */
126367 static int splitNodeStartree(
126368   Rtree *pRtree,
126369   RtreeCell *aCell,
126370   int nCell,
126371   RtreeNode *pLeft,
126372   RtreeNode *pRight,
126373   RtreeCell *pBboxLeft,
126374   RtreeCell *pBboxRight
126375 ){
126376   int **aaSorted;
126377   int *aSpare;
126378   int ii;
126379
126380   int iBestDim = 0;
126381   int iBestSplit = 0;
126382   float fBestMargin = 0.0;
126383
126384   int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
126385
126386   aaSorted = (int **)sqlite3_malloc(nByte);
126387   if( !aaSorted ){
126388     return SQLITE_NOMEM;
126389   }
126390
126391   aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
126392   memset(aaSorted, 0, nByte);
126393   for(ii=0; ii<pRtree->nDim; ii++){
126394     int jj;
126395     aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
126396     for(jj=0; jj<nCell; jj++){
126397       aaSorted[ii][jj] = jj;
126398     }
126399     SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
126400   }
126401
126402   for(ii=0; ii<pRtree->nDim; ii++){
126403     float margin = 0.0;
126404     float fBestOverlap = 0.0;
126405     float fBestArea = 0.0;
126406     int iBestLeft = 0;
126407     int nLeft;
126408
126409     for(
126410       nLeft=RTREE_MINCELLS(pRtree); 
126411       nLeft<=(nCell-RTREE_MINCELLS(pRtree)); 
126412       nLeft++
126413     ){
126414       RtreeCell left;
126415       RtreeCell right;
126416       int kk;
126417       float overlap;
126418       float area;
126419
126420       memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
126421       memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
126422       for(kk=1; kk<(nCell-1); kk++){
126423         if( kk<nLeft ){
126424           cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
126425         }else{
126426           cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
126427         }
126428       }
126429       margin += cellMargin(pRtree, &left);
126430       margin += cellMargin(pRtree, &right);
126431       overlap = cellOverlap(pRtree, &left, &right, 1, -1);
126432       area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
126433       if( (nLeft==RTREE_MINCELLS(pRtree))
126434        || (overlap<fBestOverlap)
126435        || (overlap==fBestOverlap && area<fBestArea)
126436       ){
126437         iBestLeft = nLeft;
126438         fBestOverlap = overlap;
126439         fBestArea = area;
126440       }
126441     }
126442
126443     if( ii==0 || margin<fBestMargin ){
126444       iBestDim = ii;
126445       fBestMargin = margin;
126446       iBestSplit = iBestLeft;
126447     }
126448   }
126449
126450   memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
126451   memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
126452   for(ii=0; ii<nCell; ii++){
126453     RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
126454     RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
126455     RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
126456     nodeInsertCell(pRtree, pTarget, pCell);
126457     cellUnion(pRtree, pBbox, pCell);
126458   }
126459
126460   sqlite3_free(aaSorted);
126461   return SQLITE_OK;
126462 }
126463 #endif
126464
126465 #if VARIANT_GUTTMAN_SPLIT
126466 /*
126467 ** Implementation of the regular R-tree SplitNode from Guttman[1984].
126468 */
126469 static int splitNodeGuttman(
126470   Rtree *pRtree,
126471   RtreeCell *aCell,
126472   int nCell,
126473   RtreeNode *pLeft,
126474   RtreeNode *pRight,
126475   RtreeCell *pBboxLeft,
126476   RtreeCell *pBboxRight
126477 ){
126478   int iLeftSeed = 0;
126479   int iRightSeed = 1;
126480   int *aiUsed;
126481   int i;
126482
126483   aiUsed = sqlite3_malloc(sizeof(int)*nCell);
126484   if( !aiUsed ){
126485     return SQLITE_NOMEM;
126486   }
126487   memset(aiUsed, 0, sizeof(int)*nCell);
126488
126489   PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
126490
126491   memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
126492   memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
126493   nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
126494   nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
126495   aiUsed[iLeftSeed] = 1;
126496   aiUsed[iRightSeed] = 1;
126497
126498   for(i=nCell-2; i>0; i--){
126499     RtreeCell *pNext;
126500     pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
126501     float diff =  
126502       cellGrowth(pRtree, pBboxLeft, pNext) - 
126503       cellGrowth(pRtree, pBboxRight, pNext)
126504     ;
126505     if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
126506      || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
126507     ){
126508       nodeInsertCell(pRtree, pRight, pNext);
126509       cellUnion(pRtree, pBboxRight, pNext);
126510     }else{
126511       nodeInsertCell(pRtree, pLeft, pNext);
126512       cellUnion(pRtree, pBboxLeft, pNext);
126513     }
126514   }
126515
126516   sqlite3_free(aiUsed);
126517   return SQLITE_OK;
126518 }
126519 #endif
126520
126521 static int updateMapping(
126522   Rtree *pRtree, 
126523   i64 iRowid, 
126524   RtreeNode *pNode, 
126525   int iHeight
126526 ){
126527   int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
126528   xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
126529   if( iHeight>0 ){
126530     RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
126531     if( pChild ){
126532       nodeRelease(pRtree, pChild->pParent);
126533       nodeReference(pNode);
126534       pChild->pParent = pNode;
126535     }
126536   }
126537   return xSetMapping(pRtree, iRowid, pNode->iNode);
126538 }
126539
126540 static int SplitNode(
126541   Rtree *pRtree,
126542   RtreeNode *pNode,
126543   RtreeCell *pCell,
126544   int iHeight
126545 ){
126546   int i;
126547   int newCellIsRight = 0;
126548
126549   int rc = SQLITE_OK;
126550   int nCell = NCELL(pNode);
126551   RtreeCell *aCell;
126552   int *aiUsed;
126553
126554   RtreeNode *pLeft = 0;
126555   RtreeNode *pRight = 0;
126556
126557   RtreeCell leftbbox;
126558   RtreeCell rightbbox;
126559
126560   /* Allocate an array and populate it with a copy of pCell and 
126561   ** all cells from node pLeft. Then zero the original node.
126562   */
126563   aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
126564   if( !aCell ){
126565     rc = SQLITE_NOMEM;
126566     goto splitnode_out;
126567   }
126568   aiUsed = (int *)&aCell[nCell+1];
126569   memset(aiUsed, 0, sizeof(int)*(nCell+1));
126570   for(i=0; i<nCell; i++){
126571     nodeGetCell(pRtree, pNode, i, &aCell[i]);
126572   }
126573   nodeZero(pRtree, pNode);
126574   memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
126575   nCell++;
126576
126577   if( pNode->iNode==1 ){
126578     pRight = nodeNew(pRtree, pNode);
126579     pLeft = nodeNew(pRtree, pNode);
126580     pRtree->iDepth++;
126581     pNode->isDirty = 1;
126582     writeInt16(pNode->zData, pRtree->iDepth);
126583   }else{
126584     pLeft = pNode;
126585     pRight = nodeNew(pRtree, pLeft->pParent);
126586     nodeReference(pLeft);
126587   }
126588
126589   if( !pLeft || !pRight ){
126590     rc = SQLITE_NOMEM;
126591     goto splitnode_out;
126592   }
126593
126594   memset(pLeft->zData, 0, pRtree->iNodeSize);
126595   memset(pRight->zData, 0, pRtree->iNodeSize);
126596
126597   rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
126598   if( rc!=SQLITE_OK ){
126599     goto splitnode_out;
126600   }
126601
126602   /* Ensure both child nodes have node numbers assigned to them by calling
126603   ** nodeWrite(). Node pRight always needs a node number, as it was created
126604   ** by nodeNew() above. But node pLeft sometimes already has a node number.
126605   ** In this case avoid the all to nodeWrite().
126606   */
126607   if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
126608    || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
126609   ){
126610     goto splitnode_out;
126611   }
126612
126613   rightbbox.iRowid = pRight->iNode;
126614   leftbbox.iRowid = pLeft->iNode;
126615
126616   if( pNode->iNode==1 ){
126617     rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
126618     if( rc!=SQLITE_OK ){
126619       goto splitnode_out;
126620     }
126621   }else{
126622     RtreeNode *pParent = pLeft->pParent;
126623     int iCell;
126624     rc = nodeParentIndex(pRtree, pLeft, &iCell);
126625     if( rc==SQLITE_OK ){
126626       nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
126627       rc = AdjustTree(pRtree, pParent, &leftbbox);
126628     }
126629     if( rc!=SQLITE_OK ){
126630       goto splitnode_out;
126631     }
126632   }
126633   if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
126634     goto splitnode_out;
126635   }
126636
126637   for(i=0; i<NCELL(pRight); i++){
126638     i64 iRowid = nodeGetRowid(pRtree, pRight, i);
126639     rc = updateMapping(pRtree, iRowid, pRight, iHeight);
126640     if( iRowid==pCell->iRowid ){
126641       newCellIsRight = 1;
126642     }
126643     if( rc!=SQLITE_OK ){
126644       goto splitnode_out;
126645     }
126646   }
126647   if( pNode->iNode==1 ){
126648     for(i=0; i<NCELL(pLeft); i++){
126649       i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
126650       rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
126651       if( rc!=SQLITE_OK ){
126652         goto splitnode_out;
126653       }
126654     }
126655   }else if( newCellIsRight==0 ){
126656     rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
126657   }
126658
126659   if( rc==SQLITE_OK ){
126660     rc = nodeRelease(pRtree, pRight);
126661     pRight = 0;
126662   }
126663   if( rc==SQLITE_OK ){
126664     rc = nodeRelease(pRtree, pLeft);
126665     pLeft = 0;
126666   }
126667
126668 splitnode_out:
126669   nodeRelease(pRtree, pRight);
126670   nodeRelease(pRtree, pLeft);
126671   sqlite3_free(aCell);
126672   return rc;
126673 }
126674
126675 /*
126676 ** If node pLeaf is not the root of the r-tree and its pParent pointer is 
126677 ** still NULL, load all ancestor nodes of pLeaf into memory and populate
126678 ** the pLeaf->pParent chain all the way up to the root node.
126679 **
126680 ** This operation is required when a row is deleted (or updated - an update
126681 ** is implemented as a delete followed by an insert). SQLite provides the
126682 ** rowid of the row to delete, which can be used to find the leaf on which
126683 ** the entry resides (argument pLeaf). Once the leaf is located, this 
126684 ** function is called to determine its ancestry.
126685 */
126686 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
126687   int rc = SQLITE_OK;
126688   RtreeNode *pChild = pLeaf;
126689   while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
126690     int rc2 = SQLITE_OK;          /* sqlite3_reset() return code */
126691     sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
126692     rc = sqlite3_step(pRtree->pReadParent);
126693     if( rc==SQLITE_ROW ){
126694       RtreeNode *pTest;           /* Used to test for reference loops */
126695       i64 iNode;                  /* Node number of parent node */
126696
126697       /* Before setting pChild->pParent, test that we are not creating a
126698       ** loop of references (as we would if, say, pChild==pParent). We don't
126699       ** want to do this as it leads to a memory leak when trying to delete
126700       ** the referenced counted node structures.
126701       */
126702       iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
126703       for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
126704       if( !pTest ){
126705         rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
126706       }
126707     }
126708     rc = sqlite3_reset(pRtree->pReadParent);
126709     if( rc==SQLITE_OK ) rc = rc2;
126710     if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
126711     pChild = pChild->pParent;
126712   }
126713   return rc;
126714 }
126715
126716 static int deleteCell(Rtree *, RtreeNode *, int, int);
126717
126718 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
126719   int rc;
126720   int rc2;
126721   RtreeNode *pParent = 0;
126722   int iCell;
126723
126724   assert( pNode->nRef==1 );
126725
126726   /* Remove the entry in the parent cell. */
126727   rc = nodeParentIndex(pRtree, pNode, &iCell);
126728   if( rc==SQLITE_OK ){
126729     pParent = pNode->pParent;
126730     pNode->pParent = 0;
126731     rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
126732   }
126733   rc2 = nodeRelease(pRtree, pParent);
126734   if( rc==SQLITE_OK ){
126735     rc = rc2;
126736   }
126737   if( rc!=SQLITE_OK ){
126738     return rc;
126739   }
126740
126741   /* Remove the xxx_node entry. */
126742   sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
126743   sqlite3_step(pRtree->pDeleteNode);
126744   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
126745     return rc;
126746   }
126747
126748   /* Remove the xxx_parent entry. */
126749   sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
126750   sqlite3_step(pRtree->pDeleteParent);
126751   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
126752     return rc;
126753   }
126754   
126755   /* Remove the node from the in-memory hash table and link it into
126756   ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
126757   */
126758   nodeHashDelete(pRtree, pNode);
126759   pNode->iNode = iHeight;
126760   pNode->pNext = pRtree->pDeleted;
126761   pNode->nRef++;
126762   pRtree->pDeleted = pNode;
126763
126764   return SQLITE_OK;
126765 }
126766
126767 static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
126768   RtreeNode *pParent = pNode->pParent;
126769   int rc = SQLITE_OK; 
126770   if( pParent ){
126771     int ii; 
126772     int nCell = NCELL(pNode);
126773     RtreeCell box;                            /* Bounding box for pNode */
126774     nodeGetCell(pRtree, pNode, 0, &box);
126775     for(ii=1; ii<nCell; ii++){
126776       RtreeCell cell;
126777       nodeGetCell(pRtree, pNode, ii, &cell);
126778       cellUnion(pRtree, &box, &cell);
126779     }
126780     box.iRowid = pNode->iNode;
126781     rc = nodeParentIndex(pRtree, pNode, &ii);
126782     if( rc==SQLITE_OK ){
126783       nodeOverwriteCell(pRtree, pParent, &box, ii);
126784       rc = fixBoundingBox(pRtree, pParent);
126785     }
126786   }
126787   return rc;
126788 }
126789
126790 /*
126791 ** Delete the cell at index iCell of node pNode. After removing the
126792 ** cell, adjust the r-tree data structure if required.
126793 */
126794 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
126795   RtreeNode *pParent;
126796   int rc;
126797
126798   if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
126799     return rc;
126800   }
126801
126802   /* Remove the cell from the node. This call just moves bytes around
126803   ** the in-memory node image, so it cannot fail.
126804   */
126805   nodeDeleteCell(pRtree, pNode, iCell);
126806
126807   /* If the node is not the tree root and now has less than the minimum
126808   ** number of cells, remove it from the tree. Otherwise, update the
126809   ** cell in the parent node so that it tightly contains the updated
126810   ** node.
126811   */
126812   pParent = pNode->pParent;
126813   assert( pParent || pNode->iNode==1 );
126814   if( pParent ){
126815     if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
126816       rc = removeNode(pRtree, pNode, iHeight);
126817     }else{
126818       rc = fixBoundingBox(pRtree, pNode);
126819     }
126820   }
126821
126822   return rc;
126823 }
126824
126825 static int Reinsert(
126826   Rtree *pRtree, 
126827   RtreeNode *pNode, 
126828   RtreeCell *pCell, 
126829   int iHeight
126830 ){
126831   int *aOrder;
126832   int *aSpare;
126833   RtreeCell *aCell;
126834   float *aDistance;
126835   int nCell;
126836   float aCenterCoord[RTREE_MAX_DIMENSIONS];
126837   int iDim;
126838   int ii;
126839   int rc = SQLITE_OK;
126840
126841   memset(aCenterCoord, 0, sizeof(float)*RTREE_MAX_DIMENSIONS);
126842
126843   nCell = NCELL(pNode)+1;
126844
126845   /* Allocate the buffers used by this operation. The allocation is
126846   ** relinquished before this function returns.
126847   */
126848   aCell = (RtreeCell *)sqlite3_malloc(nCell * (
126849     sizeof(RtreeCell) +         /* aCell array */
126850     sizeof(int)       +         /* aOrder array */
126851     sizeof(int)       +         /* aSpare array */
126852     sizeof(float)               /* aDistance array */
126853   ));
126854   if( !aCell ){
126855     return SQLITE_NOMEM;
126856   }
126857   aOrder    = (int *)&aCell[nCell];
126858   aSpare    = (int *)&aOrder[nCell];
126859   aDistance = (float *)&aSpare[nCell];
126860
126861   for(ii=0; ii<nCell; ii++){
126862     if( ii==(nCell-1) ){
126863       memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
126864     }else{
126865       nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
126866     }
126867     aOrder[ii] = ii;
126868     for(iDim=0; iDim<pRtree->nDim; iDim++){
126869       aCenterCoord[iDim] += (float)DCOORD(aCell[ii].aCoord[iDim*2]);
126870       aCenterCoord[iDim] += (float)DCOORD(aCell[ii].aCoord[iDim*2+1]);
126871     }
126872   }
126873   for(iDim=0; iDim<pRtree->nDim; iDim++){
126874     aCenterCoord[iDim] = (float)(aCenterCoord[iDim]/((float)nCell*2.0));
126875   }
126876
126877   for(ii=0; ii<nCell; ii++){
126878     aDistance[ii] = 0.0;
126879     for(iDim=0; iDim<pRtree->nDim; iDim++){
126880       float coord = (float)(DCOORD(aCell[ii].aCoord[iDim*2+1]) - 
126881           DCOORD(aCell[ii].aCoord[iDim*2]));
126882       aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
126883     }
126884   }
126885
126886   SortByDistance(aOrder, nCell, aDistance, aSpare);
126887   nodeZero(pRtree, pNode);
126888
126889   for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
126890     RtreeCell *p = &aCell[aOrder[ii]];
126891     nodeInsertCell(pRtree, pNode, p);
126892     if( p->iRowid==pCell->iRowid ){
126893       if( iHeight==0 ){
126894         rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
126895       }else{
126896         rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
126897       }
126898     }
126899   }
126900   if( rc==SQLITE_OK ){
126901     rc = fixBoundingBox(pRtree, pNode);
126902   }
126903   for(; rc==SQLITE_OK && ii<nCell; ii++){
126904     /* Find a node to store this cell in. pNode->iNode currently contains
126905     ** the height of the sub-tree headed by the cell.
126906     */
126907     RtreeNode *pInsert;
126908     RtreeCell *p = &aCell[aOrder[ii]];
126909     rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
126910     if( rc==SQLITE_OK ){
126911       int rc2;
126912       rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
126913       rc2 = nodeRelease(pRtree, pInsert);
126914       if( rc==SQLITE_OK ){
126915         rc = rc2;
126916       }
126917     }
126918   }
126919
126920   sqlite3_free(aCell);
126921   return rc;
126922 }
126923
126924 /*
126925 ** Insert cell pCell into node pNode. Node pNode is the head of a 
126926 ** subtree iHeight high (leaf nodes have iHeight==0).
126927 */
126928 static int rtreeInsertCell(
126929   Rtree *pRtree,
126930   RtreeNode *pNode,
126931   RtreeCell *pCell,
126932   int iHeight
126933 ){
126934   int rc = SQLITE_OK;
126935   if( iHeight>0 ){
126936     RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
126937     if( pChild ){
126938       nodeRelease(pRtree, pChild->pParent);
126939       nodeReference(pNode);
126940       pChild->pParent = pNode;
126941     }
126942   }
126943   if( nodeInsertCell(pRtree, pNode, pCell) ){
126944 #if VARIANT_RSTARTREE_REINSERT
126945     if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
126946       rc = SplitNode(pRtree, pNode, pCell, iHeight);
126947     }else{
126948       pRtree->iReinsertHeight = iHeight;
126949       rc = Reinsert(pRtree, pNode, pCell, iHeight);
126950     }
126951 #else
126952     rc = SplitNode(pRtree, pNode, pCell, iHeight);
126953 #endif
126954   }else{
126955     rc = AdjustTree(pRtree, pNode, pCell);
126956     if( rc==SQLITE_OK ){
126957       if( iHeight==0 ){
126958         rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
126959       }else{
126960         rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
126961       }
126962     }
126963   }
126964   return rc;
126965 }
126966
126967 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
126968   int ii;
126969   int rc = SQLITE_OK;
126970   int nCell = NCELL(pNode);
126971
126972   for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
126973     RtreeNode *pInsert;
126974     RtreeCell cell;
126975     nodeGetCell(pRtree, pNode, ii, &cell);
126976
126977     /* Find a node to store this cell in. pNode->iNode currently contains
126978     ** the height of the sub-tree headed by the cell.
126979     */
126980     rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
126981     if( rc==SQLITE_OK ){
126982       int rc2;
126983       rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
126984       rc2 = nodeRelease(pRtree, pInsert);
126985       if( rc==SQLITE_OK ){
126986         rc = rc2;
126987       }
126988     }
126989   }
126990   return rc;
126991 }
126992
126993 /*
126994 ** Select a currently unused rowid for a new r-tree record.
126995 */
126996 static int newRowid(Rtree *pRtree, i64 *piRowid){
126997   int rc;
126998   sqlite3_bind_null(pRtree->pWriteRowid, 1);
126999   sqlite3_bind_null(pRtree->pWriteRowid, 2);
127000   sqlite3_step(pRtree->pWriteRowid);
127001   rc = sqlite3_reset(pRtree->pWriteRowid);
127002   *piRowid = sqlite3_last_insert_rowid(pRtree->db);
127003   return rc;
127004 }
127005
127006 /*
127007 ** Remove the entry with rowid=iDelete from the r-tree structure.
127008 */
127009 static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
127010   int rc;                         /* Return code */
127011   RtreeNode *pLeaf;               /* Leaf node containing record iDelete */
127012   int iCell;                      /* Index of iDelete cell in pLeaf */
127013   RtreeNode *pRoot;               /* Root node of rtree structure */
127014
127015
127016   /* Obtain a reference to the root node to initialise Rtree.iDepth */
127017   rc = nodeAcquire(pRtree, 1, 0, &pRoot);
127018
127019   /* Obtain a reference to the leaf node that contains the entry 
127020   ** about to be deleted. 
127021   */
127022   if( rc==SQLITE_OK ){
127023     rc = findLeafNode(pRtree, iDelete, &pLeaf);
127024   }
127025
127026   /* Delete the cell in question from the leaf node. */
127027   if( rc==SQLITE_OK ){
127028     int rc2;
127029     rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
127030     if( rc==SQLITE_OK ){
127031       rc = deleteCell(pRtree, pLeaf, iCell, 0);
127032     }
127033     rc2 = nodeRelease(pRtree, pLeaf);
127034     if( rc==SQLITE_OK ){
127035       rc = rc2;
127036     }
127037   }
127038
127039   /* Delete the corresponding entry in the <rtree>_rowid table. */
127040   if( rc==SQLITE_OK ){
127041     sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
127042     sqlite3_step(pRtree->pDeleteRowid);
127043     rc = sqlite3_reset(pRtree->pDeleteRowid);
127044   }
127045
127046   /* Check if the root node now has exactly one child. If so, remove
127047   ** it, schedule the contents of the child for reinsertion and 
127048   ** reduce the tree height by one.
127049   **
127050   ** This is equivalent to copying the contents of the child into
127051   ** the root node (the operation that Gutman's paper says to perform 
127052   ** in this scenario).
127053   */
127054   if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
127055     int rc2;
127056     RtreeNode *pChild;
127057     i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
127058     rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
127059     if( rc==SQLITE_OK ){
127060       rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
127061     }
127062     rc2 = nodeRelease(pRtree, pChild);
127063     if( rc==SQLITE_OK ) rc = rc2;
127064     if( rc==SQLITE_OK ){
127065       pRtree->iDepth--;
127066       writeInt16(pRoot->zData, pRtree->iDepth);
127067       pRoot->isDirty = 1;
127068     }
127069   }
127070
127071   /* Re-insert the contents of any underfull nodes removed from the tree. */
127072   for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
127073     if( rc==SQLITE_OK ){
127074       rc = reinsertNodeContent(pRtree, pLeaf);
127075     }
127076     pRtree->pDeleted = pLeaf->pNext;
127077     sqlite3_free(pLeaf);
127078   }
127079
127080   /* Release the reference to the root node. */
127081   if( rc==SQLITE_OK ){
127082     rc = nodeRelease(pRtree, pRoot);
127083   }else{
127084     nodeRelease(pRtree, pRoot);
127085   }
127086
127087   return rc;
127088 }
127089
127090 /*
127091 ** The xUpdate method for rtree module virtual tables.
127092 */
127093 static int rtreeUpdate(
127094   sqlite3_vtab *pVtab, 
127095   int nData, 
127096   sqlite3_value **azData, 
127097   sqlite_int64 *pRowid
127098 ){
127099   Rtree *pRtree = (Rtree *)pVtab;
127100   int rc = SQLITE_OK;
127101   RtreeCell cell;                 /* New cell to insert if nData>1 */
127102   int bHaveRowid = 0;             /* Set to 1 after new rowid is determined */
127103
127104   rtreeReference(pRtree);
127105   assert(nData>=1);
127106
127107   /* Constraint handling. A write operation on an r-tree table may return
127108   ** SQLITE_CONSTRAINT for two reasons:
127109   **
127110   **   1. A duplicate rowid value, or
127111   **   2. The supplied data violates the "x2>=x1" constraint.
127112   **
127113   ** In the first case, if the conflict-handling mode is REPLACE, then
127114   ** the conflicting row can be removed before proceeding. In the second
127115   ** case, SQLITE_CONSTRAINT must be returned regardless of the
127116   ** conflict-handling mode specified by the user.
127117   */
127118   if( nData>1 ){
127119     int ii;
127120
127121     /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
127122     assert( nData==(pRtree->nDim*2 + 3) );
127123     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
127124       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
127125         cell.aCoord[ii].f = (float)sqlite3_value_double(azData[ii+3]);
127126         cell.aCoord[ii+1].f = (float)sqlite3_value_double(azData[ii+4]);
127127         if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
127128           rc = SQLITE_CONSTRAINT;
127129           goto constraint;
127130         }
127131       }
127132     }else{
127133       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
127134         cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
127135         cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
127136         if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
127137           rc = SQLITE_CONSTRAINT;
127138           goto constraint;
127139         }
127140       }
127141     }
127142
127143     /* If a rowid value was supplied, check if it is already present in 
127144     ** the table. If so, the constraint has failed. */
127145     if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
127146       cell.iRowid = sqlite3_value_int64(azData[2]);
127147       if( sqlite3_value_type(azData[0])==SQLITE_NULL
127148        || sqlite3_value_int64(azData[0])!=cell.iRowid
127149       ){
127150         int steprc;
127151         sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
127152         steprc = sqlite3_step(pRtree->pReadRowid);
127153         rc = sqlite3_reset(pRtree->pReadRowid);
127154         if( SQLITE_ROW==steprc ){
127155           if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
127156             rc = rtreeDeleteRowid(pRtree, cell.iRowid);
127157           }else{
127158             rc = SQLITE_CONSTRAINT;
127159             goto constraint;
127160           }
127161         }
127162       }
127163       bHaveRowid = 1;
127164     }
127165   }
127166
127167   /* If azData[0] is not an SQL NULL value, it is the rowid of a
127168   ** record to delete from the r-tree table. The following block does
127169   ** just that.
127170   */
127171   if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
127172     rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
127173   }
127174
127175   /* If the azData[] array contains more than one element, elements
127176   ** (azData[2]..azData[argc-1]) contain a new record to insert into
127177   ** the r-tree structure.
127178   */
127179   if( rc==SQLITE_OK && nData>1 ){
127180     /* Insert the new record into the r-tree */
127181     RtreeNode *pLeaf;
127182
127183     /* Figure out the rowid of the new row. */
127184     if( bHaveRowid==0 ){
127185       rc = newRowid(pRtree, &cell.iRowid);
127186     }
127187     *pRowid = cell.iRowid;
127188
127189     if( rc==SQLITE_OK ){
127190       rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
127191     }
127192     if( rc==SQLITE_OK ){
127193       int rc2;
127194       pRtree->iReinsertHeight = -1;
127195       rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
127196       rc2 = nodeRelease(pRtree, pLeaf);
127197       if( rc==SQLITE_OK ){
127198         rc = rc2;
127199       }
127200     }
127201   }
127202
127203 constraint:
127204   rtreeRelease(pRtree);
127205   return rc;
127206 }
127207
127208 /*
127209 ** The xRename method for rtree module virtual tables.
127210 */
127211 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
127212   Rtree *pRtree = (Rtree *)pVtab;
127213   int rc = SQLITE_NOMEM;
127214   char *zSql = sqlite3_mprintf(
127215     "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
127216     "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
127217     "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
127218     , pRtree->zDb, pRtree->zName, zNewName 
127219     , pRtree->zDb, pRtree->zName, zNewName 
127220     , pRtree->zDb, pRtree->zName, zNewName
127221   );
127222   if( zSql ){
127223     rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
127224     sqlite3_free(zSql);
127225   }
127226   return rc;
127227 }
127228
127229 static sqlite3_module rtreeModule = {
127230   0,                          /* iVersion */
127231   rtreeCreate,                /* xCreate - create a table */
127232   rtreeConnect,               /* xConnect - connect to an existing table */
127233   rtreeBestIndex,             /* xBestIndex - Determine search strategy */
127234   rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
127235   rtreeDestroy,               /* xDestroy - Drop a table */
127236   rtreeOpen,                  /* xOpen - open a cursor */
127237   rtreeClose,                 /* xClose - close a cursor */
127238   rtreeFilter,                /* xFilter - configure scan constraints */
127239   rtreeNext,                  /* xNext - advance a cursor */
127240   rtreeEof,                   /* xEof */
127241   rtreeColumn,                /* xColumn - read data */
127242   rtreeRowid,                 /* xRowid - read data */
127243   rtreeUpdate,                /* xUpdate - write data */
127244   0,                          /* xBegin - begin transaction */
127245   0,                          /* xSync - sync transaction */
127246   0,                          /* xCommit - commit transaction */
127247   0,                          /* xRollback - rollback transaction */
127248   0,                          /* xFindFunction - function overloading */
127249   rtreeRename,                /* xRename - rename the table */
127250   0,                          /* xSavepoint */
127251   0,                          /* xRelease */
127252   0                           /* xRollbackTo */
127253 };
127254
127255 static int rtreeSqlInit(
127256   Rtree *pRtree, 
127257   sqlite3 *db, 
127258   const char *zDb, 
127259   const char *zPrefix, 
127260   int isCreate
127261 ){
127262   int rc = SQLITE_OK;
127263
127264   #define N_STATEMENT 9
127265   static const char *azSql[N_STATEMENT] = {
127266     /* Read and write the xxx_node table */
127267     "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
127268     "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
127269     "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
127270
127271     /* Read and write the xxx_rowid table */
127272     "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
127273     "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
127274     "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
127275
127276     /* Read and write the xxx_parent table */
127277     "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
127278     "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
127279     "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
127280   };
127281   sqlite3_stmt **appStmt[N_STATEMENT];
127282   int i;
127283
127284   pRtree->db = db;
127285
127286   if( isCreate ){
127287     char *zCreate = sqlite3_mprintf(
127288 "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
127289 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
127290 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
127291 "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
127292       zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
127293     );
127294     if( !zCreate ){
127295       return SQLITE_NOMEM;
127296     }
127297     rc = sqlite3_exec(db, zCreate, 0, 0, 0);
127298     sqlite3_free(zCreate);
127299     if( rc!=SQLITE_OK ){
127300       return rc;
127301     }
127302   }
127303
127304   appStmt[0] = &pRtree->pReadNode;
127305   appStmt[1] = &pRtree->pWriteNode;
127306   appStmt[2] = &pRtree->pDeleteNode;
127307   appStmt[3] = &pRtree->pReadRowid;
127308   appStmt[4] = &pRtree->pWriteRowid;
127309   appStmt[5] = &pRtree->pDeleteRowid;
127310   appStmt[6] = &pRtree->pReadParent;
127311   appStmt[7] = &pRtree->pWriteParent;
127312   appStmt[8] = &pRtree->pDeleteParent;
127313
127314   for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
127315     char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
127316     if( zSql ){
127317       rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0); 
127318     }else{
127319       rc = SQLITE_NOMEM;
127320     }
127321     sqlite3_free(zSql);
127322   }
127323
127324   return rc;
127325 }
127326
127327 /*
127328 ** The second argument to this function contains the text of an SQL statement
127329 ** that returns a single integer value. The statement is compiled and executed
127330 ** using database connection db. If successful, the integer value returned
127331 ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
127332 ** code is returned and the value of *piVal after returning is not defined.
127333 */
127334 static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
127335   int rc = SQLITE_NOMEM;
127336   if( zSql ){
127337     sqlite3_stmt *pStmt = 0;
127338     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
127339     if( rc==SQLITE_OK ){
127340       if( SQLITE_ROW==sqlite3_step(pStmt) ){
127341         *piVal = sqlite3_column_int(pStmt, 0);
127342       }
127343       rc = sqlite3_finalize(pStmt);
127344     }
127345   }
127346   return rc;
127347 }
127348
127349 /*
127350 ** This function is called from within the xConnect() or xCreate() method to
127351 ** determine the node-size used by the rtree table being created or connected
127352 ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
127353 ** Otherwise, an SQLite error code is returned.
127354 **
127355 ** If this function is being called as part of an xConnect(), then the rtree
127356 ** table already exists. In this case the node-size is determined by inspecting
127357 ** the root node of the tree.
127358 **
127359 ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size. 
127360 ** This ensures that each node is stored on a single database page. If the 
127361 ** database page-size is so large that more than RTREE_MAXCELLS entries 
127362 ** would fit in a single node, use a smaller node-size.
127363 */
127364 static int getNodeSize(
127365   sqlite3 *db,                    /* Database handle */
127366   Rtree *pRtree,                  /* Rtree handle */
127367   int isCreate                    /* True for xCreate, false for xConnect */
127368 ){
127369   int rc;
127370   char *zSql;
127371   if( isCreate ){
127372     int iPageSize = 0;
127373     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
127374     rc = getIntFromStmt(db, zSql, &iPageSize);
127375     if( rc==SQLITE_OK ){
127376       pRtree->iNodeSize = iPageSize-64;
127377       if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
127378         pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
127379       }
127380     }
127381   }else{
127382     zSql = sqlite3_mprintf(
127383         "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
127384         pRtree->zDb, pRtree->zName
127385     );
127386     rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
127387   }
127388
127389   sqlite3_free(zSql);
127390   return rc;
127391 }
127392
127393 /* 
127394 ** This function is the implementation of both the xConnect and xCreate
127395 ** methods of the r-tree virtual table.
127396 **
127397 **   argv[0]   -> module name
127398 **   argv[1]   -> database name
127399 **   argv[2]   -> table name
127400 **   argv[...] -> column names...
127401 */
127402 static int rtreeInit(
127403   sqlite3 *db,                        /* Database connection */
127404   void *pAux,                         /* One of the RTREE_COORD_* constants */
127405   int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
127406   sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
127407   char **pzErr,                       /* OUT: Error message, if any */
127408   int isCreate                        /* True for xCreate, false for xConnect */
127409 ){
127410   int rc = SQLITE_OK;
127411   Rtree *pRtree;
127412   int nDb;              /* Length of string argv[1] */
127413   int nName;            /* Length of string argv[2] */
127414   int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
127415
127416   const char *aErrMsg[] = {
127417     0,                                                    /* 0 */
127418     "Wrong number of columns for an rtree table",         /* 1 */
127419     "Too few columns for an rtree table",                 /* 2 */
127420     "Too many columns for an rtree table"                 /* 3 */
127421   };
127422
127423   int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
127424   if( aErrMsg[iErr] ){
127425     *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
127426     return SQLITE_ERROR;
127427   }
127428
127429   sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
127430
127431   /* Allocate the sqlite3_vtab structure */
127432   nDb = strlen(argv[1]);
127433   nName = strlen(argv[2]);
127434   pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
127435   if( !pRtree ){
127436     return SQLITE_NOMEM;
127437   }
127438   memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
127439   pRtree->nBusy = 1;
127440   pRtree->base.pModule = &rtreeModule;
127441   pRtree->zDb = (char *)&pRtree[1];
127442   pRtree->zName = &pRtree->zDb[nDb+1];
127443   pRtree->nDim = (argc-4)/2;
127444   pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
127445   pRtree->eCoordType = eCoordType;
127446   memcpy(pRtree->zDb, argv[1], nDb);
127447   memcpy(pRtree->zName, argv[2], nName);
127448
127449   /* Figure out the node size to use. */
127450   rc = getNodeSize(db, pRtree, isCreate);
127451
127452   /* Create/Connect to the underlying relational database schema. If
127453   ** that is successful, call sqlite3_declare_vtab() to configure
127454   ** the r-tree table schema.
127455   */
127456   if( rc==SQLITE_OK ){
127457     if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
127458       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
127459     }else{
127460       char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
127461       char *zTmp;
127462       int ii;
127463       for(ii=4; zSql && ii<argc; ii++){
127464         zTmp = zSql;
127465         zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
127466         sqlite3_free(zTmp);
127467       }
127468       if( zSql ){
127469         zTmp = zSql;
127470         zSql = sqlite3_mprintf("%s);", zTmp);
127471         sqlite3_free(zTmp);
127472       }
127473       if( !zSql ){
127474         rc = SQLITE_NOMEM;
127475       }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
127476         *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
127477       }
127478       sqlite3_free(zSql);
127479     }
127480   }
127481
127482   if( rc==SQLITE_OK ){
127483     *ppVtab = (sqlite3_vtab *)pRtree;
127484   }else{
127485     rtreeRelease(pRtree);
127486   }
127487   return rc;
127488 }
127489
127490
127491 /*
127492 ** Implementation of a scalar function that decodes r-tree nodes to
127493 ** human readable strings. This can be used for debugging and analysis.
127494 **
127495 ** The scalar function takes two arguments, a blob of data containing
127496 ** an r-tree node, and the number of dimensions the r-tree indexes.
127497 ** For a two-dimensional r-tree structure called "rt", to deserialize
127498 ** all nodes, a statement like:
127499 **
127500 **   SELECT rtreenode(2, data) FROM rt_node;
127501 **
127502 ** The human readable string takes the form of a Tcl list with one
127503 ** entry for each cell in the r-tree node. Each entry is itself a
127504 ** list, containing the 8-byte rowid/pageno followed by the 
127505 ** <num-dimension>*2 coordinates.
127506 */
127507 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
127508   char *zText = 0;
127509   RtreeNode node;
127510   Rtree tree;
127511   int ii;
127512
127513   UNUSED_PARAMETER(nArg);
127514   memset(&node, 0, sizeof(RtreeNode));
127515   memset(&tree, 0, sizeof(Rtree));
127516   tree.nDim = sqlite3_value_int(apArg[0]);
127517   tree.nBytesPerCell = 8 + 8 * tree.nDim;
127518   node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
127519
127520   for(ii=0; ii<NCELL(&node); ii++){
127521     char zCell[512];
127522     int nCell = 0;
127523     RtreeCell cell;
127524     int jj;
127525
127526     nodeGetCell(&tree, &node, ii, &cell);
127527     sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
127528     nCell = strlen(zCell);
127529     for(jj=0; jj<tree.nDim*2; jj++){
127530       sqlite3_snprintf(512-nCell,&zCell[nCell]," %f",(double)cell.aCoord[jj].f);
127531       nCell = strlen(zCell);
127532     }
127533
127534     if( zText ){
127535       char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
127536       sqlite3_free(zText);
127537       zText = zTextNew;
127538     }else{
127539       zText = sqlite3_mprintf("{%s}", zCell);
127540     }
127541   }
127542   
127543   sqlite3_result_text(ctx, zText, -1, sqlite3_free);
127544 }
127545
127546 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
127547   UNUSED_PARAMETER(nArg);
127548   if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB 
127549    || sqlite3_value_bytes(apArg[0])<2
127550   ){
127551     sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1); 
127552   }else{
127553     u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
127554     sqlite3_result_int(ctx, readInt16(zBlob));
127555   }
127556 }
127557
127558 /*
127559 ** Register the r-tree module with database handle db. This creates the
127560 ** virtual table module "rtree" and the debugging/analysis scalar 
127561 ** function "rtreenode".
127562 */
127563 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
127564   const int utf8 = SQLITE_UTF8;
127565   int rc;
127566
127567   rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
127568   if( rc==SQLITE_OK ){
127569     rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
127570   }
127571   if( rc==SQLITE_OK ){
127572     void *c = (void *)RTREE_COORD_REAL32;
127573     rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
127574   }
127575   if( rc==SQLITE_OK ){
127576     void *c = (void *)RTREE_COORD_INT32;
127577     rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
127578   }
127579
127580   return rc;
127581 }
127582
127583 /*
127584 ** A version of sqlite3_free() that can be used as a callback. This is used
127585 ** in two places - as the destructor for the blob value returned by the
127586 ** invocation of a geometry function, and as the destructor for the geometry
127587 ** functions themselves.
127588 */
127589 static void doSqlite3Free(void *p){
127590   sqlite3_free(p);
127591 }
127592
127593 /*
127594 ** Each call to sqlite3_rtree_geometry_callback() creates an ordinary SQLite
127595 ** scalar user function. This C function is the callback used for all such
127596 ** registered SQL functions.
127597 **
127598 ** The scalar user functions return a blob that is interpreted by r-tree
127599 ** table MATCH operators.
127600 */
127601 static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
127602   RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
127603   RtreeMatchArg *pBlob;
127604   int nBlob;
127605
127606   nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(double);
127607   pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
127608   if( !pBlob ){
127609     sqlite3_result_error_nomem(ctx);
127610   }else{
127611     int i;
127612     pBlob->magic = RTREE_GEOMETRY_MAGIC;
127613     pBlob->xGeom = pGeomCtx->xGeom;
127614     pBlob->pContext = pGeomCtx->pContext;
127615     pBlob->nParam = nArg;
127616     for(i=0; i<nArg; i++){
127617       pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
127618     }
127619     sqlite3_result_blob(ctx, pBlob, nBlob, doSqlite3Free);
127620   }
127621 }
127622
127623 /*
127624 ** Register a new geometry function for use with the r-tree MATCH operator.
127625 */
127626 SQLITE_API int sqlite3_rtree_geometry_callback(
127627   sqlite3 *db,
127628   const char *zGeom,
127629   int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *),
127630   void *pContext
127631 ){
127632   RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
127633
127634   /* Allocate and populate the context object. */
127635   pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
127636   if( !pGeomCtx ) return SQLITE_NOMEM;
127637   pGeomCtx->xGeom = xGeom;
127638   pGeomCtx->pContext = pContext;
127639
127640   /* Create the new user-function. Register a destructor function to delete
127641   ** the context object when it is no longer required.  */
127642   return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY, 
127643       (void *)pGeomCtx, geomCallback, 0, 0, doSqlite3Free
127644   );
127645 }
127646
127647 #if !SQLITE_CORE
127648 SQLITE_API int sqlite3_extension_init(
127649   sqlite3 *db,
127650   char **pzErrMsg,
127651   const sqlite3_api_routines *pApi
127652 ){
127653   SQLITE_EXTENSION_INIT2(pApi)
127654   return sqlite3RtreeInit(db);
127655 }
127656 #endif
127657
127658 #endif
127659
127660 /************** End of rtree.c ***********************************************/
127661 /************** Begin file icu.c *********************************************/
127662 /*
127663 ** 2007 May 6
127664 **
127665 ** The author disclaims copyright to this source code.  In place of
127666 ** a legal notice, here is a blessing:
127667 **
127668 **    May you do good and not evil.
127669 **    May you find forgiveness for yourself and forgive others.
127670 **    May you share freely, never taking more than you give.
127671 **
127672 *************************************************************************
127673 ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
127674 **
127675 ** This file implements an integration between the ICU library 
127676 ** ("International Components for Unicode", an open-source library 
127677 ** for handling unicode data) and SQLite. The integration uses 
127678 ** ICU to provide the following to SQLite:
127679 **
127680 **   * An implementation of the SQL regexp() function (and hence REGEXP
127681 **     operator) using the ICU uregex_XX() APIs.
127682 **
127683 **   * Implementations of the SQL scalar upper() and lower() functions
127684 **     for case mapping.
127685 **
127686 **   * Integration of ICU and SQLite collation seqences.
127687 **
127688 **   * An implementation of the LIKE operator that uses ICU to 
127689 **     provide case-independent matching.
127690 */
127691
127692 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
127693
127694 /* Include ICU headers */
127695 #include <unicode/utypes.h>
127696 #include <unicode/uregex.h>
127697 #include <unicode/ustring.h>
127698 #include <unicode/ucol.h>
127699
127700
127701 #ifndef SQLITE_CORE
127702   SQLITE_EXTENSION_INIT1
127703 #else
127704 #endif
127705
127706 /*
127707 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
127708 ** operator.
127709 */
127710 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
127711 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
127712 #endif
127713
127714 /*
127715 ** Version of sqlite3_free() that is always a function, never a macro.
127716 */
127717 static void xFree(void *p){
127718   sqlite3_free(p);
127719 }
127720
127721 /*
127722 ** Compare two UTF-8 strings for equality where the first string is
127723 ** a "LIKE" expression. Return true (1) if they are the same and 
127724 ** false (0) if they are different.
127725 */
127726 static int icuLikeCompare(
127727   const uint8_t *zPattern,   /* LIKE pattern */
127728   const uint8_t *zString,    /* The UTF-8 string to compare against */
127729   const UChar32 uEsc         /* The escape character */
127730 ){
127731   static const int MATCH_ONE = (UChar32)'_';
127732   static const int MATCH_ALL = (UChar32)'%';
127733
127734   int iPattern = 0;       /* Current byte index in zPattern */
127735   int iString = 0;        /* Current byte index in zString */
127736
127737   int prevEscape = 0;     /* True if the previous character was uEsc */
127738
127739   while( zPattern[iPattern]!=0 ){
127740
127741     /* Read (and consume) the next character from the input pattern. */
127742     UChar32 uPattern;
127743     U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
127744     assert(uPattern!=0);
127745
127746     /* There are now 4 possibilities:
127747     **
127748     **     1. uPattern is an unescaped match-all character "%",
127749     **     2. uPattern is an unescaped match-one character "_",
127750     **     3. uPattern is an unescaped escape character, or
127751     **     4. uPattern is to be handled as an ordinary character
127752     */
127753     if( !prevEscape && uPattern==MATCH_ALL ){
127754       /* Case 1. */
127755       uint8_t c;
127756
127757       /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
127758       ** MATCH_ALL. For each MATCH_ONE, skip one character in the 
127759       ** test string.
127760       */
127761       while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
127762         if( c==MATCH_ONE ){
127763           if( zString[iString]==0 ) return 0;
127764           U8_FWD_1_UNSAFE(zString, iString);
127765         }
127766         iPattern++;
127767       }
127768
127769       if( zPattern[iPattern]==0 ) return 1;
127770
127771       while( zString[iString] ){
127772         if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
127773           return 1;
127774         }
127775         U8_FWD_1_UNSAFE(zString, iString);
127776       }
127777       return 0;
127778
127779     }else if( !prevEscape && uPattern==MATCH_ONE ){
127780       /* Case 2. */
127781       if( zString[iString]==0 ) return 0;
127782       U8_FWD_1_UNSAFE(zString, iString);
127783
127784     }else if( !prevEscape && uPattern==uEsc){
127785       /* Case 3. */
127786       prevEscape = 1;
127787
127788     }else{
127789       /* Case 4. */
127790       UChar32 uString;
127791       U8_NEXT_UNSAFE(zString, iString, uString);
127792       uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
127793       uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
127794       if( uString!=uPattern ){
127795         return 0;
127796       }
127797       prevEscape = 0;
127798     }
127799   }
127800
127801   return zString[iString]==0;
127802 }
127803
127804 /*
127805 ** Implementation of the like() SQL function.  This function implements
127806 ** the build-in LIKE operator.  The first argument to the function is the
127807 ** pattern and the second argument is the string.  So, the SQL statements:
127808 **
127809 **       A LIKE B
127810 **
127811 ** is implemented as like(B, A). If there is an escape character E, 
127812 **
127813 **       A LIKE B ESCAPE E
127814 **
127815 ** is mapped to like(B, A, E).
127816 */
127817 static void icuLikeFunc(
127818   sqlite3_context *context, 
127819   int argc, 
127820   sqlite3_value **argv
127821 ){
127822   const unsigned char *zA = sqlite3_value_text(argv[0]);
127823   const unsigned char *zB = sqlite3_value_text(argv[1]);
127824   UChar32 uEsc = 0;
127825
127826   /* Limit the length of the LIKE or GLOB pattern to avoid problems
127827   ** of deep recursion and N*N behavior in patternCompare().
127828   */
127829   if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
127830     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
127831     return;
127832   }
127833
127834
127835   if( argc==3 ){
127836     /* The escape character string must consist of a single UTF-8 character.
127837     ** Otherwise, return an error.
127838     */
127839     int nE= sqlite3_value_bytes(argv[2]);
127840     const unsigned char *zE = sqlite3_value_text(argv[2]);
127841     int i = 0;
127842     if( zE==0 ) return;
127843     U8_NEXT(zE, i, nE, uEsc);
127844     if( i!=nE){
127845       sqlite3_result_error(context, 
127846           "ESCAPE expression must be a single character", -1);
127847       return;
127848     }
127849   }
127850
127851   if( zA && zB ){
127852     sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
127853   }
127854 }
127855
127856 /*
127857 ** This function is called when an ICU function called from within
127858 ** the implementation of an SQL scalar function returns an error.
127859 **
127860 ** The scalar function context passed as the first argument is 
127861 ** loaded with an error message based on the following two args.
127862 */
127863 static void icuFunctionError(
127864   sqlite3_context *pCtx,       /* SQLite scalar function context */
127865   const char *zName,           /* Name of ICU function that failed */
127866   UErrorCode e                 /* Error code returned by ICU function */
127867 ){
127868   char zBuf[128];
127869   sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
127870   zBuf[127] = '\0';
127871   sqlite3_result_error(pCtx, zBuf, -1);
127872 }
127873
127874 /*
127875 ** Function to delete compiled regexp objects. Registered as
127876 ** a destructor function with sqlite3_set_auxdata().
127877 */
127878 static void icuRegexpDelete(void *p){
127879   URegularExpression *pExpr = (URegularExpression *)p;
127880   uregex_close(pExpr);
127881 }
127882
127883 /*
127884 ** Implementation of SQLite REGEXP operator. This scalar function takes
127885 ** two arguments. The first is a regular expression pattern to compile
127886 ** the second is a string to match against that pattern. If either 
127887 ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
127888 ** is 1 if the string matches the pattern, or 0 otherwise.
127889 **
127890 ** SQLite maps the regexp() function to the regexp() operator such
127891 ** that the following two are equivalent:
127892 **
127893 **     zString REGEXP zPattern
127894 **     regexp(zPattern, zString)
127895 **
127896 ** Uses the following ICU regexp APIs:
127897 **
127898 **     uregex_open()
127899 **     uregex_matches()
127900 **     uregex_close()
127901 */
127902 static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
127903   UErrorCode status = U_ZERO_ERROR;
127904   URegularExpression *pExpr;
127905   UBool res;
127906   const UChar *zString = sqlite3_value_text16(apArg[1]);
127907
127908   (void)nArg;  /* Unused parameter */
127909
127910   /* If the left hand side of the regexp operator is NULL, 
127911   ** then the result is also NULL. 
127912   */
127913   if( !zString ){
127914     return;
127915   }
127916
127917   pExpr = sqlite3_get_auxdata(p, 0);
127918   if( !pExpr ){
127919     const UChar *zPattern = sqlite3_value_text16(apArg[0]);
127920     if( !zPattern ){
127921       return;
127922     }
127923     pExpr = uregex_open(zPattern, -1, 0, 0, &status);
127924
127925     if( U_SUCCESS(status) ){
127926       sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
127927     }else{
127928       assert(!pExpr);
127929       icuFunctionError(p, "uregex_open", status);
127930       return;
127931     }
127932   }
127933
127934   /* Configure the text that the regular expression operates on. */
127935   uregex_setText(pExpr, zString, -1, &status);
127936   if( !U_SUCCESS(status) ){
127937     icuFunctionError(p, "uregex_setText", status);
127938     return;
127939   }
127940
127941   /* Attempt the match */
127942   res = uregex_matches(pExpr, 0, &status);
127943   if( !U_SUCCESS(status) ){
127944     icuFunctionError(p, "uregex_matches", status);
127945     return;
127946   }
127947
127948   /* Set the text that the regular expression operates on to a NULL
127949   ** pointer. This is not really necessary, but it is tidier than 
127950   ** leaving the regular expression object configured with an invalid
127951   ** pointer after this function returns.
127952   */
127953   uregex_setText(pExpr, 0, 0, &status);
127954
127955   /* Return 1 or 0. */
127956   sqlite3_result_int(p, res ? 1 : 0);
127957 }
127958
127959 /*
127960 ** Implementations of scalar functions for case mapping - upper() and 
127961 ** lower(). Function upper() converts its input to upper-case (ABC).
127962 ** Function lower() converts to lower-case (abc).
127963 **
127964 ** ICU provides two types of case mapping, "general" case mapping and
127965 ** "language specific". Refer to ICU documentation for the differences
127966 ** between the two.
127967 **
127968 ** To utilise "general" case mapping, the upper() or lower() scalar 
127969 ** functions are invoked with one argument:
127970 **
127971 **     upper('ABC') -> 'abc'
127972 **     lower('abc') -> 'ABC'
127973 **
127974 ** To access ICU "language specific" case mapping, upper() or lower()
127975 ** should be invoked with two arguments. The second argument is the name
127976 ** of the locale to use. Passing an empty string ("") or SQL NULL value
127977 ** as the second argument is the same as invoking the 1 argument version
127978 ** of upper() or lower().
127979 **
127980 **     lower('I', 'en_us') -> 'i'
127981 **     lower('I', 'tr_tr') -> 'ı' (small dotless i)
127982 **
127983 ** http://www.icu-project.org/userguide/posix.html#case_mappings
127984 */
127985 static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
127986   const UChar *zInput;
127987   UChar *zOutput;
127988   int nInput;
127989   int nOutput;
127990
127991   UErrorCode status = U_ZERO_ERROR;
127992   const char *zLocale = 0;
127993
127994   assert(nArg==1 || nArg==2);
127995   if( nArg==2 ){
127996     zLocale = (const char *)sqlite3_value_text(apArg[1]);
127997   }
127998
127999   zInput = sqlite3_value_text16(apArg[0]);
128000   if( !zInput ){
128001     return;
128002   }
128003   nInput = sqlite3_value_bytes16(apArg[0]);
128004
128005   nOutput = nInput * 2 + 2;
128006   zOutput = sqlite3_malloc(nOutput);
128007   if( !zOutput ){
128008     return;
128009   }
128010
128011   if( sqlite3_user_data(p) ){
128012     u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
128013   }else{
128014     u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
128015   }
128016
128017   if( !U_SUCCESS(status) ){
128018     icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
128019     return;
128020   }
128021
128022   sqlite3_result_text16(p, zOutput, -1, xFree);
128023 }
128024
128025 /*
128026 ** Collation sequence destructor function. The pCtx argument points to
128027 ** a UCollator structure previously allocated using ucol_open().
128028 */
128029 static void icuCollationDel(void *pCtx){
128030   UCollator *p = (UCollator *)pCtx;
128031   ucol_close(p);
128032 }
128033
128034 /*
128035 ** Collation sequence comparison function. The pCtx argument points to
128036 ** a UCollator structure previously allocated using ucol_open().
128037 */
128038 static int icuCollationColl(
128039   void *pCtx,
128040   int nLeft,
128041   const void *zLeft,
128042   int nRight,
128043   const void *zRight
128044 ){
128045   UCollationResult res;
128046   UCollator *p = (UCollator *)pCtx;
128047   res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
128048   switch( res ){
128049     case UCOL_LESS:    return -1;
128050     case UCOL_GREATER: return +1;
128051     case UCOL_EQUAL:   return 0;
128052   }
128053   assert(!"Unexpected return value from ucol_strcoll()");
128054   return 0;
128055 }
128056
128057 /*
128058 ** Implementation of the scalar function icu_load_collation().
128059 **
128060 ** This scalar function is used to add ICU collation based collation 
128061 ** types to an SQLite database connection. It is intended to be called
128062 ** as follows:
128063 **
128064 **     SELECT icu_load_collation(<locale>, <collation-name>);
128065 **
128066 ** Where <locale> is a string containing an ICU locale identifier (i.e.
128067 ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
128068 ** collation sequence to create.
128069 */
128070 static void icuLoadCollation(
128071   sqlite3_context *p, 
128072   int nArg, 
128073   sqlite3_value **apArg
128074 ){
128075   sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
128076   UErrorCode status = U_ZERO_ERROR;
128077   const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
128078   const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
128079   UCollator *pUCollator;    /* ICU library collation object */
128080   int rc;                   /* Return code from sqlite3_create_collation_x() */
128081
128082   assert(nArg==2);
128083   zLocale = (const char *)sqlite3_value_text(apArg[0]);
128084   zName = (const char *)sqlite3_value_text(apArg[1]);
128085
128086   if( !zLocale || !zName ){
128087     return;
128088   }
128089
128090   pUCollator = ucol_open(zLocale, &status);
128091   if( !U_SUCCESS(status) ){
128092     icuFunctionError(p, "ucol_open", status);
128093     return;
128094   }
128095   assert(p);
128096
128097   rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator, 
128098       icuCollationColl, icuCollationDel
128099   );
128100   if( rc!=SQLITE_OK ){
128101     ucol_close(pUCollator);
128102     sqlite3_result_error(p, "Error registering collation function", -1);
128103   }
128104 }
128105
128106 /*
128107 ** Register the ICU extension functions with database db.
128108 */
128109 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
128110   struct IcuScalar {
128111     const char *zName;                        /* Function name */
128112     int nArg;                                 /* Number of arguments */
128113     int enc;                                  /* Optimal text encoding */
128114     void *pContext;                           /* sqlite3_user_data() context */
128115     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
128116   } scalars[] = {
128117     {"regexp", 2, SQLITE_ANY,          0, icuRegexpFunc},
128118
128119     {"lower",  1, SQLITE_UTF16,        0, icuCaseFunc16},
128120     {"lower",  2, SQLITE_UTF16,        0, icuCaseFunc16},
128121     {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
128122     {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
128123
128124     {"lower",  1, SQLITE_UTF8,         0, icuCaseFunc16},
128125     {"lower",  2, SQLITE_UTF8,         0, icuCaseFunc16},
128126     {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
128127     {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
128128
128129     {"like",   2, SQLITE_UTF8,         0, icuLikeFunc},
128130     {"like",   3, SQLITE_UTF8,         0, icuLikeFunc},
128131
128132     {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
128133   };
128134
128135   int rc = SQLITE_OK;
128136   int i;
128137
128138   for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
128139     struct IcuScalar *p = &scalars[i];
128140     rc = sqlite3_create_function(
128141         db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
128142     );
128143   }
128144
128145   return rc;
128146 }
128147
128148 #if !SQLITE_CORE
128149 SQLITE_API int sqlite3_extension_init(
128150   sqlite3 *db, 
128151   char **pzErrMsg,
128152   const sqlite3_api_routines *pApi
128153 ){
128154   SQLITE_EXTENSION_INIT2(pApi)
128155   return sqlite3IcuInit(db);
128156 }
128157 #endif
128158
128159 #endif
128160
128161 /************** End of icu.c *************************************************/
128162 /************** Begin file fts3_icu.c ****************************************/
128163 /*
128164 ** 2007 June 22
128165 **
128166 ** The author disclaims copyright to this source code.  In place of
128167 ** a legal notice, here is a blessing:
128168 **
128169 **    May you do good and not evil.
128170 **    May you find forgiveness for yourself and forgive others.
128171 **    May you share freely, never taking more than you give.
128172 **
128173 *************************************************************************
128174 ** This file implements a tokenizer for fts3 based on the ICU library.
128175 */
128176 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
128177 #ifdef SQLITE_ENABLE_ICU
128178
128179
128180 #include <unicode/ubrk.h>
128181 #include <unicode/utf16.h>
128182
128183 typedef struct IcuTokenizer IcuTokenizer;
128184 typedef struct IcuCursor IcuCursor;
128185
128186 struct IcuTokenizer {
128187   sqlite3_tokenizer base;
128188   char *zLocale;
128189 };
128190
128191 struct IcuCursor {
128192   sqlite3_tokenizer_cursor base;
128193
128194   UBreakIterator *pIter;      /* ICU break-iterator object */
128195   int nChar;                  /* Number of UChar elements in pInput */
128196   UChar *aChar;               /* Copy of input using utf-16 encoding */
128197   int *aOffset;               /* Offsets of each character in utf-8 input */
128198
128199   int nBuffer;
128200   char *zBuffer;
128201
128202   int iToken;
128203 };
128204
128205 /*
128206 ** Create a new tokenizer instance.
128207 */
128208 static int icuCreate(
128209   int argc,                            /* Number of entries in argv[] */
128210   const char * const *argv,            /* Tokenizer creation arguments */
128211   sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
128212 ){
128213   IcuTokenizer *p;
128214   int n = 0;
128215
128216   if( argc>0 ){
128217     n = strlen(argv[0])+1;
128218   }
128219   p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
128220   if( !p ){
128221     return SQLITE_NOMEM;
128222   }
128223   memset(p, 0, sizeof(IcuTokenizer));
128224
128225   if( n ){
128226     p->zLocale = (char *)&p[1];
128227     memcpy(p->zLocale, argv[0], n);
128228   }
128229
128230   *ppTokenizer = (sqlite3_tokenizer *)p;
128231
128232   return SQLITE_OK;
128233 }
128234
128235 /*
128236 ** Destroy a tokenizer
128237 */
128238 static int icuDestroy(sqlite3_tokenizer *pTokenizer){
128239   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
128240   sqlite3_free(p);
128241   return SQLITE_OK;
128242 }
128243
128244 /*
128245 ** Prepare to begin tokenizing a particular string.  The input
128246 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
128247 ** used to incrementally tokenize this string is returned in 
128248 ** *ppCursor.
128249 */
128250 static int icuOpen(
128251   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
128252   const char *zInput,                    /* Input string */
128253   int nInput,                            /* Length of zInput in bytes */
128254   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
128255 ){
128256   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
128257   IcuCursor *pCsr;
128258
128259   const int32_t opt = U_FOLD_CASE_DEFAULT;
128260   UErrorCode status = U_ZERO_ERROR;
128261   int nChar;
128262
128263   UChar32 c;
128264   int iInput = 0;
128265   int iOut = 0;
128266
128267   *ppCursor = 0;
128268
128269   if( nInput<0 ){
128270     nInput = strlen(zInput);
128271   }
128272   nChar = nInput+1;
128273   pCsr = (IcuCursor *)sqlite3_malloc(
128274       sizeof(IcuCursor) +                /* IcuCursor */
128275       nChar * sizeof(UChar) +            /* IcuCursor.aChar[] */
128276       (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
128277   );
128278   if( !pCsr ){
128279     return SQLITE_NOMEM;
128280   }
128281   memset(pCsr, 0, sizeof(IcuCursor));
128282   pCsr->aChar = (UChar *)&pCsr[1];
128283   pCsr->aOffset = (int *)&pCsr->aChar[nChar];
128284
128285   pCsr->aOffset[iOut] = iInput;
128286   U8_NEXT(zInput, iInput, nInput, c); 
128287   while( c>0 ){
128288     int isError = 0;
128289     c = u_foldCase(c, opt);
128290     U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
128291     if( isError ){
128292       sqlite3_free(pCsr);
128293       return SQLITE_ERROR;
128294     }
128295     pCsr->aOffset[iOut] = iInput;
128296
128297     if( iInput<nInput ){
128298       U8_NEXT(zInput, iInput, nInput, c);
128299     }else{
128300       c = 0;
128301     }
128302   }
128303
128304   pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
128305   if( !U_SUCCESS(status) ){
128306     sqlite3_free(pCsr);
128307     return SQLITE_ERROR;
128308   }
128309   pCsr->nChar = iOut;
128310
128311   ubrk_first(pCsr->pIter);
128312   *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
128313   return SQLITE_OK;
128314 }
128315
128316 /*
128317 ** Close a tokenization cursor previously opened by a call to icuOpen().
128318 */
128319 static int icuClose(sqlite3_tokenizer_cursor *pCursor){
128320   IcuCursor *pCsr = (IcuCursor *)pCursor;
128321   ubrk_close(pCsr->pIter);
128322   sqlite3_free(pCsr->zBuffer);
128323   sqlite3_free(pCsr);
128324   return SQLITE_OK;
128325 }
128326
128327 /*
128328 ** Extract the next token from a tokenization cursor.
128329 */
128330 static int icuNext(
128331   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
128332   const char **ppToken,               /* OUT: *ppToken is the token text */
128333   int *pnBytes,                       /* OUT: Number of bytes in token */
128334   int *piStartOffset,                 /* OUT: Starting offset of token */
128335   int *piEndOffset,                   /* OUT: Ending offset of token */
128336   int *piPosition                     /* OUT: Position integer of token */
128337 ){
128338   IcuCursor *pCsr = (IcuCursor *)pCursor;
128339
128340   int iStart = 0;
128341   int iEnd = 0;
128342   int nByte = 0;
128343
128344   while( iStart==iEnd ){
128345     UChar32 c;
128346
128347     iStart = ubrk_current(pCsr->pIter);
128348     iEnd = ubrk_next(pCsr->pIter);
128349     if( iEnd==UBRK_DONE ){
128350       return SQLITE_DONE;
128351     }
128352
128353     while( iStart<iEnd ){
128354       int iWhite = iStart;
128355       U8_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
128356       if( u_isspace(c) ){
128357         iStart = iWhite;
128358       }else{
128359         break;
128360       }
128361     }
128362     assert(iStart<=iEnd);
128363   }
128364
128365   do {
128366     UErrorCode status = U_ZERO_ERROR;
128367     if( nByte ){
128368       char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
128369       if( !zNew ){
128370         return SQLITE_NOMEM;
128371       }
128372       pCsr->zBuffer = zNew;
128373       pCsr->nBuffer = nByte;
128374     }
128375
128376     u_strToUTF8(
128377         pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
128378         &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
128379         &status                                  /* Output success/failure */
128380     );
128381   } while( nByte>pCsr->nBuffer );
128382
128383   *ppToken = pCsr->zBuffer;
128384   *pnBytes = nByte;
128385   *piStartOffset = pCsr->aOffset[iStart];
128386   *piEndOffset = pCsr->aOffset[iEnd];
128387   *piPosition = pCsr->iToken++;
128388
128389   return SQLITE_OK;
128390 }
128391
128392 /*
128393 ** The set of routines that implement the simple tokenizer
128394 */
128395 static const sqlite3_tokenizer_module icuTokenizerModule = {
128396   0,                           /* iVersion */
128397   icuCreate,                   /* xCreate  */
128398   icuDestroy,                  /* xCreate  */
128399   icuOpen,                     /* xOpen    */
128400   icuClose,                    /* xClose   */
128401   icuNext,                     /* xNext    */
128402 };
128403
128404 /*
128405 ** Set *ppModule to point at the implementation of the ICU tokenizer.
128406 */
128407 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
128408   sqlite3_tokenizer_module const**ppModule
128409 ){
128410   *ppModule = &icuTokenizerModule;
128411 }
128412
128413 #endif /* defined(SQLITE_ENABLE_ICU) */
128414 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
128415
128416 /************** End of fts3_icu.c ********************************************/